repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Facades/Theme.php
app/Facades/Theme.php
<?php namespace BookStack\Facades; use BookStack\Theming\ThemeService; use Illuminate\Support\Facades\Facade; class Theme extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return ThemeService::class; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Facades/Activity.php
app/Facades/Activity.php
<?php namespace BookStack\Facades; use Illuminate\Support\Facades\Facade; /** * @mixin \BookStack\Activity\Tools\ActivityLogger */ class Activity extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'activity'; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Kernel.php
app/Console/Kernel.php
<?php namespace BookStack\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * * @return void */ protected function schedule(Schedule $schedule) { // } /** * Register the commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__ . '/Commands'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/CreateAdminCommand.php
app/Console/Commands/CreateAdminCommand.php
<?php namespace BookStack\Console\Commands; use BookStack\Users\Models\Role; use BookStack\Users\UserRepo; use Illuminate\Console\Command; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; use Illuminate\Validation\Rules\Password; class CreateAdminCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:create-admin {--email= : The email address for the new admin user} {--name= : The name of the new admin user} {--password= : The password to assign to the new admin user} {--external-auth-id= : The external authentication system id for the new admin user (SAML2/LDAP/OIDC)} {--generate-password : Generate a random password for the new admin user} {--initial : Indicate if this should set/update the details of the initial admin user}'; /** * The console command description. * * @var string */ protected $description = 'Add a new admin user to the system'; /** * Execute the console command. */ public function handle(UserRepo $userRepo): int { $initialAdminOnly = $this->option('initial'); $shouldGeneratePassword = $this->option('generate-password'); $details = $this->gatherDetails($shouldGeneratePassword, $initialAdminOnly); $validator = Validator::make($details, [ 'email' => ['required', 'email', 'min:5'], 'name' => ['required', 'min:2'], 'password' => ['required_without:external_auth_id', Password::default()], 'external_auth_id' => ['required_without:password'], ]); if ($validator->fails()) { foreach ($validator->errors()->all() as $error) { $this->error($error); } return 1; } $adminRole = Role::getSystemRole('admin'); if ($initialAdminOnly) { $handled = $this->handleInitialAdminIfExists($userRepo, $details, $shouldGeneratePassword, $adminRole); if ($handled !== null) { return $handled; } } $emailUsed = $userRepo->getByEmail($details['email']) !== null; if ($emailUsed) { $this->error("Could not create admin account."); $this->error("An account with the email address \"{$details['email']}\" already exists."); return 1; } $user = $userRepo->createWithoutActivity($validator->validated()); $user->attachRole($adminRole); $user->email_confirmed = true; $user->save(); if ($shouldGeneratePassword) { $this->line($details['password']); } else { $this->info("Admin account with email \"{$user->email}\" successfully created!"); } return 0; } /** * Handle updates to the original admin account if it exists. * Returns an int return status if handled, otherwise returns null if not handled (new user to be created). */ protected function handleInitialAdminIfExists(UserRepo $userRepo, array $data, bool $generatePassword, Role $adminRole): int|null { $defaultAdmin = $userRepo->getByEmail('admin@admin.com'); if ($defaultAdmin && $defaultAdmin->hasSystemRole('admin')) { if ($defaultAdmin->email !== $data['email'] && $userRepo->getByEmail($data['email']) !== null) { $this->error("Could not create admin account."); $this->error("An account with the email address \"{$data['email']}\" already exists."); return 1; } $userRepo->updateWithoutActivity($defaultAdmin, $data, true); if ($generatePassword) { $this->line($data['password']); } else { $this->info("The default admin user has been updated with the provided details!"); } return 0; } else if ($adminRole->users()->count() > 0) { $this->warn('Non-default admin user already exists. Skipping creation of new admin user.'); return 2; } return null; } protected function gatherDetails(bool $generatePassword, bool $initialAdmin): array { $details = $this->snakeCaseOptions(); if (empty($details['email'])) { if ($initialAdmin) { $details['email'] = 'admin@example.com'; } else { $details['email'] = $this->ask('Please specify an email address for the new admin user'); } } if (empty($details['name'])) { if ($initialAdmin) { $details['name'] = 'Admin'; } else { $details['name'] = $this->ask('Please specify a name for the new admin user'); } } if (empty($details['password'])) { if (empty($details['external_auth_id'])) { if ($generatePassword) { $details['password'] = Str::random(32); } else { $details['password'] = $this->ask('Please specify a password for the new admin user (8 characters min)'); } } else { $details['password'] = Str::random(32); } } return $details; } protected function snakeCaseOptions(): array { $returnOpts = []; foreach ($this->options() as $key => $value) { $returnOpts[str_replace('-', '_', $key)] = $value; } return $returnOpts; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/ClearViewsCommand.php
app/Console/Commands/ClearViewsCommand.php
<?php namespace BookStack\Console\Commands; use BookStack\Activity\Models\View; use Illuminate\Console\Command; class ClearViewsCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:clear-views'; /** * The console command description. * * @var string */ protected $description = 'Clear all view-counts for all entities'; /** * Execute the console command. */ public function handle(): int { View::query()->truncate(); $this->comment('Views cleared'); return 0; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/UpgradeDatabaseEncodingCommand.php
app/Console/Commands/UpgradeDatabaseEncodingCommand.php
<?php namespace BookStack\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; class UpgradeDatabaseEncodingCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:db-utf8mb4 {--database= : The database connection to use}'; /** * The console command description. * * @var string */ protected $description = 'Generate SQL commands to upgrade the database to UTF8mb4'; /** * Execute the console command. */ public function handle(): int { $connection = DB::getDefaultConnection(); if ($this->option('database') !== null) { DB::setDefaultConnection($this->option('database')); } $database = DB::getDatabaseName(); $tables = DB::select('SHOW TABLES'); $this->line('ALTER DATABASE `' . $database . '` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;'); $this->line('USE `' . $database . '`;'); $key = 'Tables_in_' . $database; foreach ($tables as $table) { $tableName = $table->$key; $this->line("ALTER TABLE `{$tableName}` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"); } DB::setDefaultConnection($connection); return 0; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/CopyShelfPermissionsCommand.php
app/Console/Commands/CopyShelfPermissionsCommand.php
<?php namespace BookStack\Console\Commands; use BookStack\Entities\Queries\BookshelfQueries; use BookStack\Entities\Tools\PermissionsUpdater; use Illuminate\Console\Command; class CopyShelfPermissionsCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:copy-shelf-permissions {--a|all : Perform for all shelves in the system} {--s|slug= : The slug for a shelf to target} '; /** * The console command description. * * @var string */ protected $description = 'Copy shelf permissions to all child books'; /** * Execute the console command. */ public function handle(PermissionsUpdater $permissionsUpdater, BookshelfQueries $queries): int { $shelfSlug = $this->option('slug'); $cascadeAll = $this->option('all'); $shelves = null; if (!$cascadeAll && !$shelfSlug) { $this->error('Either a --slug or --all option must be provided.'); return 1; } if ($cascadeAll) { $continue = $this->confirm( 'Permission settings for all shelves will be cascaded. ' . 'Books assigned to multiple shelves will receive only the permissions of it\'s last processed shelf. ' . 'Are you sure you want to proceed?' ); if (!$continue && !$this->hasOption('no-interaction')) { return 0; } $shelves = $queries->start()->get(['id']); } if ($shelfSlug) { $shelves = $queries->start()->where('slug', '=', $shelfSlug)->get(['id']); if ($shelves->count() === 0) { $this->info('No shelves found with the given slug.'); } } foreach ($shelves as $shelf) { $permissionsUpdater->updateBookPermissionsFromShelf($shelf, false); $this->info('Copied permissions for shelf [' . $shelf->id . ']'); } $this->info('Permissions copied for ' . $shelves->count() . ' shelves.'); return 0; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/RegenerateReferencesCommand.php
app/Console/Commands/RegenerateReferencesCommand.php
<?php namespace BookStack\Console\Commands; use BookStack\References\ReferenceStore; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; class RegenerateReferencesCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:regenerate-references {--database= : The database connection to use}'; /** * The console command description. * * @var string */ protected $description = 'Regenerate all the cross-item model reference index'; /** * Execute the console command. */ public function handle(ReferenceStore $references): int { $connection = DB::getDefaultConnection(); if ($this->option('database')) { DB::setDefaultConnection($this->option('database')); } $references->updateForAll(); DB::setDefaultConnection($connection); $this->comment('References have been regenerated'); return 0; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/RegenerateSearchCommand.php
app/Console/Commands/RegenerateSearchCommand.php
<?php namespace BookStack\Console\Commands; use BookStack\Entities\Models\Entity; use BookStack\Search\SearchIndex; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; class RegenerateSearchCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:regenerate-search {--database= : The database connection to use}'; /** * The console command description. * * @var string */ protected $description = 'Re-index all content for searching'; /** * Execute the console command. */ public function handle(SearchIndex $searchIndex): int { $connection = DB::getDefaultConnection(); if ($this->option('database') !== null) { DB::setDefaultConnection($this->option('database')); } $searchIndex->indexAllEntities(function (Entity $model, int $processed, int $total): void { $this->info('Indexed ' . class_basename($model) . ' entries (' . $processed . '/' . $total . ')'); }); DB::setDefaultConnection($connection); $this->line('Search index regenerated!'); return static::SUCCESS; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/RegeneratePermissionsCommand.php
app/Console/Commands/RegeneratePermissionsCommand.php
<?php namespace BookStack\Console\Commands; use BookStack\Permissions\JointPermissionBuilder; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; class RegeneratePermissionsCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:regenerate-permissions {--database= : The database connection to use}'; /** * The console command description. * * @var string */ protected $description = 'Regenerate all system permissions'; /** * Execute the console command. */ public function handle(JointPermissionBuilder $permissionBuilder): int { $connection = DB::getDefaultConnection(); if ($this->option('database')) { DB::setDefaultConnection($this->option('database')); } $permissionBuilder->rebuildForAll(); DB::setDefaultConnection($connection); $this->comment('Permissions regenerated'); return 0; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/ClearRevisionsCommand.php
app/Console/Commands/ClearRevisionsCommand.php
<?php namespace BookStack\Console\Commands; use BookStack\Entities\Models\PageRevision; use Illuminate\Console\Command; class ClearRevisionsCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:clear-revisions {--a|all : Include active update drafts in deletion} '; /** * The console command description. * * @var string */ protected $description = 'Clear page revisions'; /** * Execute the console command. */ public function handle(): int { $deleteTypes = $this->option('all') ? ['version', 'update_draft'] : ['version']; PageRevision::query()->whereIn('type', $deleteTypes)->delete(); $this->comment('Revisions deleted'); return 0; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/ClearActivityCommand.php
app/Console/Commands/ClearActivityCommand.php
<?php namespace BookStack\Console\Commands; use BookStack\Activity\Models\Activity; use Illuminate\Console\Command; class ClearActivityCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:clear-activity'; /** * The console command description. * * @var string */ protected $description = 'Clear user (audit-log) activity from the system'; /** * Execute the console command. */ public function handle(): int { Activity::query()->truncate(); $this->comment('System activity cleared'); return 0; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/AssignSortRuleCommand.php
app/Console/Commands/AssignSortRuleCommand.php
<?php namespace BookStack\Console\Commands; use BookStack\Entities\Models\Book; use BookStack\Sorting\BookSorter; use BookStack\Sorting\SortRule; use Illuminate\Console\Command; class AssignSortRuleCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:assign-sort-rule {sort-rule=0: ID of the sort rule to apply} {--all-books : Apply to all books in the system} {--books-without-sort : Apply to only books without a sort rule already assigned} {--books-with-sort= : Apply to only books with the sort rule of given id}'; /** * The console command description. * * @var string */ protected $description = 'Assign a sort rule to content in the system'; /** * Execute the console command. */ public function handle(BookSorter $sorter): int { $sortRuleId = intval($this->argument('sort-rule')) ?? 0; if ($sortRuleId === 0) { return $this->listSortRules(); } $rule = SortRule::query()->find($sortRuleId); if ($this->option('all-books')) { $query = Book::query(); } else if ($this->option('books-without-sort')) { $query = Book::query()->whereNull('sort_rule_id'); } else if ($this->option('books-with-sort')) { $sortId = intval($this->option('books-with-sort')) ?: 0; if (!$sortId) { $this->error("Provided --books-with-sort option value is invalid"); return 1; } $query = Book::query()->where('sort_rule_id', $sortId); } else { $this->error("No option provided to specify target. Run with the -h option to see all available options."); return 1; } if (!$rule) { $this->error("Sort rule of provided id {$sortRuleId} not found!"); return 1; } $count = $query->clone()->count(); $this->warn("This will apply sort rule [{$rule->id}: {$rule->name}] to {$count} book(s) and run the sort on each."); $confirmed = $this->confirm("Are you sure you want to continue?"); if (!$confirmed) { return 1; } $processed = 0; $query->chunkById(10, function ($books) use ($rule, $sorter, $count, &$processed) { $max = min($count, ($processed + 10)); $this->info("Applying to {$processed}-{$max} of {$count} books"); foreach ($books as $book) { $book->sort_rule_id = $rule->id; $book->save(); $sorter->runBookAutoSort($book); } $processed = $max; }); $this->info("Sort applied to {$processed} book(s)!"); return 0; } protected function listSortRules(): int { $rules = SortRule::query()->orderBy('id', 'asc')->get(); $this->error("Sort rule ID required!"); $this->warn("\nAvailable sort rules:"); foreach ($rules as $rule) { $this->info("{$rule->id}: {$rule->name}"); } return 1; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/UpdateUrlCommand.php
app/Console/Commands/UpdateUrlCommand.php
<?php namespace BookStack\Console\Commands; use Illuminate\Console\Command; use Illuminate\Database\Connection; class UpdateUrlCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:update-url {oldUrl : URL to replace} {newUrl : URL to use as the replacement} {--force : Force the operation to run, ignoring confirmations}'; /** * The console command description. * * @var string */ protected $description = 'Find and replace the given URLs in your BookStack database'; /** * Execute the console command. */ public function handle(Connection $db): int { $oldUrl = str_replace("'", '', $this->argument('oldUrl')); $newUrl = str_replace("'", '', $this->argument('newUrl')); $urlPattern = '/https?:\/\/(.+)/'; if (!preg_match($urlPattern, $oldUrl) || !preg_match($urlPattern, $newUrl)) { $this->error('The given urls are expected to be full urls starting with http:// or https://'); return 1; } if (!$this->checkUserOkayToProceed($oldUrl, $newUrl)) { return 1; } $columnsToUpdateByTable = [ 'attachments' => ['path'], 'entity_page_data' => ['html', 'text', 'markdown'], 'entity_container_data' => ['description_html'], 'page_revisions' => ['html', 'text', 'markdown'], 'images' => ['url'], 'settings' => ['value'], 'comments' => ['html'], ]; foreach ($columnsToUpdateByTable as $table => $columns) { foreach ($columns as $column) { $changeCount = $this->replaceValueInTable($db, $table, $column, $oldUrl, $newUrl); $this->info("Updated {$changeCount} rows in {$table}->{$column}"); } } $jsonColumnsToUpdateByTable = [ 'settings' => ['value'], ]; foreach ($jsonColumnsToUpdateByTable as $table => $columns) { foreach ($columns as $column) { $oldJson = trim(json_encode($oldUrl), '"'); $newJson = trim(json_encode($newUrl), '"'); $changeCount = $this->replaceValueInTable($db, $table, $column, $oldJson, $newJson); $this->info("Updated {$changeCount} JSON encoded rows in {$table}->{$column}"); } } $this->info('URL update procedure complete.'); $this->info('============================================================================'); $this->info('Be sure to run "php artisan cache:clear" to clear any old URLs in the cache.'); if (!str_starts_with($newUrl, url('/'))) { $this->warn('You still need to update your APP_URL env value. This is currently set to:'); $this->warn(url('/')); } $this->info('============================================================================'); return 0; } /** * Perform a find+replace operations in the provided table and column. * Returns the count of rows changed. */ protected function replaceValueInTable( Connection $db, string $table, string $column, string $oldUrl, string $newUrl ): int { $oldQuoted = $db->getPdo()->quote($oldUrl); $newQuoted = $db->getPdo()->quote($newUrl); return $db->table($table)->update([ $column => $db->raw("REPLACE({$column}, {$oldQuoted}, {$newQuoted})"), ]); } /** * Warn the user of the dangers of this operation. * Returns a boolean indicating if they've accepted the warnings. */ protected function checkUserOkayToProceed(string $oldUrl, string $newUrl): bool { if ($this->option('force')) { return true; } $dangerWarning = "This will search for \"{$oldUrl}\" in your database and replace it with \"{$newUrl}\".\n"; $dangerWarning .= 'Are you sure you want to proceed?'; $backupConfirmation = 'This operation could cause issues if used incorrectly. Have you made a backup of your existing database?'; return $this->confirm($dangerWarning) && $this->confirm($backupConfirmation); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/CleanupImagesCommand.php
app/Console/Commands/CleanupImagesCommand.php
<?php namespace BookStack\Console\Commands; use BookStack\Uploads\ImageService; use Illuminate\Console\Command; use Symfony\Component\Console\Output\OutputInterface; class CleanupImagesCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:cleanup-images {--a|all : Also delete images that are only used in old revisions} {--f|force : Actually run the deletions, Defaults to a dry-run} '; /** * The console command description. * * @var string */ protected $description = 'Cleanup images and drawings'; /** * Execute the console command. */ public function handle(ImageService $imageService): int { $checkRevisions = !$this->option('all'); $dryRun = !$this->option('force'); if (!$dryRun) { $this->warn("This operation is destructive and is not guaranteed to be fully accurate.\nEnsure you have a backup of your images.\n"); $proceed = !$this->input->isInteractive() || $this->confirm("Are you sure you want to proceed?"); if (!$proceed) { return 0; } } $deleted = $imageService->deleteUnusedImages($checkRevisions, $dryRun); $deleteCount = count($deleted); if ($dryRun) { $this->comment('Dry run, no images have been deleted'); $this->comment($deleteCount . ' image(s) found that would have been deleted'); $this->showDeletedImages($deleted); $this->comment('Run with -f or --force to perform deletions'); return 0; } $this->showDeletedImages($deleted); $this->comment("{$deleteCount} image(s) deleted"); return 0; } protected function showDeletedImages($paths): void { if ($this->getOutput()->getVerbosity() <= OutputInterface::VERBOSITY_NORMAL) { return; } if (count($paths) > 0) { $this->line('Image(s) to delete:'); } foreach ($paths as $path) { $this->line($path); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/HandlesSingleUser.php
app/Console/Commands/HandlesSingleUser.php
<?php namespace BookStack\Console\Commands; use BookStack\Users\Models\User; use Exception; use Illuminate\Console\Command; /** * @mixin Command */ trait HandlesSingleUser { /** * Fetch a user provided to this command. * Expects the command to accept 'id' and 'email' options. * @throws Exception */ private function fetchProvidedUser(): User { $id = $this->option('id'); $email = $this->option('email'); if (!$id && !$email) { throw new Exception("Either a --id=<number> or --email=<email> option must be provided.\nRun this command with `--help` to show more options."); } $field = $id ? 'id' : 'email'; $value = $id ?: $email; $user = User::query() ->where($field, '=', $value) ->first(); if (!$user) { throw new Exception("A user where {$field}={$value} could not be found."); } return $user; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/RefreshAvatarCommand.php
app/Console/Commands/RefreshAvatarCommand.php
<?php namespace BookStack\Console\Commands; use BookStack\Users\Models\User; use Exception; use Illuminate\Console\Command; use BookStack\Uploads\UserAvatars; class RefreshAvatarCommand extends Command { use HandlesSingleUser; /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:refresh-avatar {--id= : Numeric ID of the user to refresh avatar for} {--email= : Email address of the user to refresh avatar for} {--users-without-avatars : Refresh avatars for users that currently have no avatar} {--a|all : Refresh avatars for all users} {--f|force : Actually run the update, Defaults to a dry-run}'; /** * The console command description. * * @var string */ protected $description = 'Refresh avatar for the given user(s)'; public function handle(UserAvatars $userAvatar): int { if (!$userAvatar->avatarFetchEnabled()) { $this->error("Avatar fetching is disabled on this instance."); return self::FAILURE; } if ($this->option('users-without-avatars')) { return $this->processUsers(User::query()->whereDoesntHave('avatar')->get()->all(), $userAvatar); } if ($this->option('all')) { return $this->processUsers(User::query()->get()->all(), $userAvatar); } try { $user = $this->fetchProvidedUser(); return $this->processUsers([$user], $userAvatar); } catch (Exception $exception) { $this->error($exception->getMessage()); return self::FAILURE; } } /** * @param User[] $users */ private function processUsers(array $users, UserAvatars $userAvatar): int { $dryRun = !$this->option('force'); $this->info(count($users) . " user(s) found to update avatars for."); if (count($users) === 0) { return self::SUCCESS; } if (!$dryRun) { $fetchHost = parse_url($userAvatar->getAvatarUrl(), PHP_URL_HOST); $this->warn("This will destroy any existing avatar images these users have, and attempt to fetch new avatar images from {$fetchHost}."); $proceed = !$this->input->isInteractive() || $this->confirm('Are you sure you want to proceed?'); if (!$proceed) { return self::SUCCESS; } } $this->info(""); $exitCode = self::SUCCESS; foreach ($users as $user) { $linePrefix = "[ID: {$user->id}] $user->email -"; if ($dryRun) { $this->warn("{$linePrefix} Not updated"); continue; } if ($this->fetchAvatar($userAvatar, $user)) { $this->info("{$linePrefix} Updated"); } else { $this->error("{$linePrefix} Not updated"); $exitCode = self::FAILURE; } } if ($dryRun) { $this->comment(""); $this->comment("Dry run, no avatars were updated."); $this->comment('Run with -f or --force to perform the update.'); } return $exitCode; } private function fetchAvatar(UserAvatars $userAvatar, User $user): bool { $oldId = $user->avatar->id ?? 0; $userAvatar->fetchAndAssignToUser($user); $user->refresh(); $newId = $user->avatar->id ?? $oldId; return $oldId !== $newId; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/ResetMfaCommand.php
app/Console/Commands/ResetMfaCommand.php
<?php namespace BookStack\Console\Commands; use Exception; use Illuminate\Console\Command; class ResetMfaCommand extends Command { use HandlesSingleUser; /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:reset-mfa {--id= : Numeric ID of the user to reset MFA for} {--email= : Email address of the user to reset MFA for} '; /** * The console command description. * * @var string */ protected $description = 'Reset & Clear any configured MFA methods for the given user'; /** * Execute the console command. */ public function handle(): int { try { $user = $this->fetchProvidedUser(); } catch (Exception $exception) { $this->error($exception->getMessage()); return 1; } $this->info("This will delete any configure multi-factor authentication methods for user: \n- ID: {$user->id}\n- Name: {$user->name}\n- Email: {$user->email}\n"); $this->info('If multi-factor authentication is required for this user they will be asked to reconfigure their methods on next login.'); $confirm = $this->confirm('Are you sure you want to proceed?'); if (!$confirm) { return 1; } $user->mfaValues()->delete(); $this->info('User MFA methods have been reset.'); return 0; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Console/Commands/DeleteUsersCommand.php
app/Console/Commands/DeleteUsersCommand.php
<?php namespace BookStack\Console\Commands; use BookStack\Users\Models\User; use BookStack\Users\UserRepo; use Illuminate\Console\Command; class DeleteUsersCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'bookstack:delete-users'; /** * The console command description. * * @var string */ protected $description = 'Delete users that are not "admin" or system users'; /** * Execute the console command. */ public function handle(UserRepo $userRepo): int { $this->warn('This will delete all users from the system that are not "admin" or system users.'); $confirm = $this->confirm('Are you sure you want to continue?'); if (!$confirm) { return 0; } $totalUsers = User::query()->count(); $numDeleted = 0; $users = User::query()->whereNull('system_name')->with('roles')->get(); foreach ($users as $user) { if ($user->hasSystemRole('admin')) { // don't delete users with "admin" role continue; } $userRepo->destroy($user); $numDeleted++; } $this->info("Deleted $numDeleted of $totalUsers total users."); return 0; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/HtmlDocument.php
app/Util/HtmlDocument.php
<?php namespace BookStack\Util; use DOMDocument; use DOMElement; use DOMNode; use DOMNodeList; use DOMText; use DOMXPath; /** * HtmlDocument is a thin wrapper around DOMDocument built * specifically for loading, querying and generating HTML content. */ class HtmlDocument { protected DOMDocument $document; protected ?DOMXPath $xpath = null; protected int $loadOptions; public function __construct(string $partialHtml = '', int $loadOptions = 0) { libxml_use_internal_errors(true); $this->document = new DOMDocument(); $this->loadOptions = $loadOptions; if ($partialHtml) { $this->loadPartialHtml($partialHtml); } } /** * Load some HTML content that's part of a document (e.g. body content) * into the current document. */ public function loadPartialHtml(string $html): void { $html = '<?xml encoding="utf-8" ?><body>' . $html . '</body>'; $this->document->loadHTML($html, $this->loadOptions); $this->xpath = null; } /** * Load a complete page of HTML content into the document. */ public function loadCompleteHtml(string $html): void { $html = '<?xml encoding="utf-8" ?>' . $html; $this->document->loadHTML($html, $this->loadOptions); $this->xpath = null; } /** * Start an XPath query on the current document. */ public function queryXPath(string $expression): DOMNodeList { if (is_null($this->xpath)) { $this->xpath = new DOMXPath($this->document); } $result = $this->xpath->query($expression); if ($result === false) { throw new \InvalidArgumentException("XPath query for expression [$expression] failed to execute"); } return $result; } /** * Create a new DOMElement instance within the document. */ public function createElement(string $localName, string $value = ''): DOMElement { $element = $this->document->createElement($localName, $value); if ($element === false) { throw new \InvalidArgumentException("Failed to create element of name [$localName] and value [$value]"); } return $element; } /** * Create a new text node within this document. */ public function createTextNode(string $text): DOMText { return $this->document->createTextNode($text); } /** * Get an element within the document of the given ID. */ public function getElementById(string $elementId): ?DOMElement { return $this->document->getElementById($elementId); } /** * Get the DOMNode that represents the HTML body. */ public function getBody(): DOMNode { return $this->document->getElementsByTagName('body')[0]; } /** * Get the nodes that are a direct child of the body. * This is usually all the content nodes if loaded partially. */ public function getBodyChildren(): DOMNodeList { return $this->getBody()->childNodes; } /** * Get the inner HTML content of the body. * This is usually all the content if loaded partially. */ public function getBodyInnerHtml(): string { $html = ''; foreach ($this->getBodyChildren() as $child) { $html .= $this->document->saveHTML($child); } return $html; } /** * Get the HTML content of the whole document. */ public function getHtml(): string { return $this->document->saveHTML($this->document->documentElement); } /** * Get the inner HTML for the given node. */ public function getNodeInnerHtml(DOMNode $node): string { $html = ''; foreach ($node->childNodes as $childNode) { $html .= $this->document->saveHTML($childNode); } return $html; } /** * Get the outer HTML for the given node. */ public function getNodeOuterHtml(DOMNode $node): string { return $this->document->saveHTML($node); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/WebSafeMimeSniffer.php
app/Util/WebSafeMimeSniffer.php
<?php namespace BookStack\Util; use finfo; /** * Helper class to sniff out the mime-type of content resulting in * a mime-type that's relatively safe to serve to a browser. */ class WebSafeMimeSniffer { /** * @var string[] */ protected array $safeMimes = [ 'application/json', 'application/octet-stream', 'application/pdf', 'audio/aac', 'audio/midi', 'audio/mpeg', 'audio/ogg', 'audio/opus', 'audio/wav', 'audio/webm', 'audio/x-m4a', 'image/apng', 'image/bmp', 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/avif', 'image/heic', 'text/css', 'text/csv', 'text/javascript', 'text/json', 'text/plain', 'video/x-msvideo', 'video/mp4', 'video/mpeg', 'video/ogg', 'video/webm', 'video/vp9', 'video/h264', 'video/av1', ]; protected array $textTypesByExtension = [ 'css' => 'text/css', 'js' => 'text/javascript', 'json' => 'application/json', 'csv' => 'text/csv', ]; /** * Sniff the mime-type from the given file content while running the result * through an allow-list to ensure a web-safe result. * Takes the content as a reference since the value may be quite large. * Accepts an optional $extension which can be used for further guessing. */ public function sniff(string &$content, string $extension = ''): string { $fInfo = new finfo(FILEINFO_MIME_TYPE); $mime = $fInfo->buffer($content) ?: 'application/octet-stream'; if ($mime === 'text/plain' && $extension) { $mime = $this->textTypesByExtension[$extension] ?? 'text/plain'; } if (in_array($mime, $this->safeMimes)) { return $mime; } [$category] = explode('/', $mime, 2); if ($category === 'text') { return 'text/plain'; } return 'application/octet-stream'; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/CspService.php
app/Util/CspService.php
<?php namespace BookStack\Util; use Illuminate\Support\Str; class CspService { protected string $nonce; public function __construct(string $nonce = '') { $this->nonce = $nonce ?: Str::random(24); } /** * Get the nonce value for CSP. */ public function getNonce(): string { return $this->nonce; } /** * Get the CSP headers for the application. */ public function getCspHeader(): string { $headers = [ $this->getFrameAncestors(), $this->getFrameSrc(), $this->getScriptSrc(), $this->getObjectSrc(), $this->getBaseUri(), ]; return implode('; ', array_filter($headers)); } /** * Get the CSP rules for the application for a HTML meta tag. */ public function getCspMetaTagValue(): string { $headers = [ $this->getFrameSrc(), $this->getScriptSrc(), $this->getObjectSrc(), $this->getBaseUri(), ]; return implode('; ', array_filter($headers)); } /** * Check if the user has configured some allowed iframe hosts. */ public function allowedIFrameHostsConfigured(): bool { return count($this->getAllowedIframeHosts()) > 0; } /** * Create CSP 'script-src' rule to restrict the forms of script that can run on the page. */ protected function getScriptSrc(): string { if (config('app.allow_content_scripts')) { return ''; } $parts = [ 'http:', 'https:', '\'nonce-' . $this->nonce . '\'', '\'strict-dynamic\'', ]; return 'script-src ' . implode(' ', $parts); } /** * Create CSP "frame-ancestors" rule to restrict the hosts that BookStack can be iframed within. */ protected function getFrameAncestors(): string { $iframeHosts = $this->getAllowedIframeHosts(); array_unshift($iframeHosts, "'self'"); return 'frame-ancestors ' . implode(' ', $iframeHosts); } /** * Creates CSP "frame-src" rule to restrict what hosts/sources can be loaded * within iframes to provide an allow-list-style approach to iframe content. */ protected function getFrameSrc(): string { $iframeHosts = $this->getAllowedIframeSources(); array_unshift($iframeHosts, "'self'"); return 'frame-src ' . implode(' ', $iframeHosts); } /** * Creates CSP 'object-src' rule to restrict the types of dynamic content * that can be embedded on the page. */ protected function getObjectSrc(): string { if (config('app.allow_content_scripts')) { return ''; } return "object-src 'self'"; } /** * Creates CSP 'base-uri' rule to restrict what base tags can be set on * the page to prevent manipulation of relative links. */ protected function getBaseUri(): string { return "base-uri 'self'"; } protected function getAllowedIframeHosts(): array { $hosts = config('app.iframe_hosts') ?? ''; return array_filter(explode(' ', $hosts)); } protected function getAllowedIframeSources(): array { $sources = explode(' ', config('app.iframe_sources', '')); $sources[] = $this->getDrawioHost(); return array_filter($sources); } /** * Extract the host name of the configured drawio URL for use in CSP. * Returns empty string if not in use. */ protected function getDrawioHost(): string { $drawioConfigValue = config('services.drawio'); if (!$drawioConfigValue) { return ''; } $drawioSource = is_string($drawioConfigValue) ? $drawioConfigValue : 'https://embed.diagrams.net/'; $drawioSourceParsed = parse_url($drawioSource); $drawioHost = $drawioSourceParsed['scheme'] . '://' . $drawioSourceParsed['host']; if (isset($drawioSourceParsed['port'])) { $drawioHost .= ':' . $drawioSourceParsed['port']; } return $drawioHost; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/DatabaseTransaction.php
app/Util/DatabaseTransaction.php
<?php namespace BookStack\Util; use Closure; use Illuminate\Support\Facades\DB; use Throwable; /** * Run the given code within a database transactions. * Wraps Laravel's own transaction method, but sets a specific runtime isolation method. * This sets a session level since this won't cause issues if already within a transaction, * and this should apply to the next transactions anyway. * * "READ COMMITTED" ensures that changes from other transactions can be read within * a transaction, even if started afterward (and for example, it was blocked by the initial * transaction). This is quite important for things like permission generation, where we would * want to consider the changes made by other committed transactions by the time we come to * regenerate permission access. * * @throws Throwable * @template TReturn of mixed */ class DatabaseTransaction { /** * @param (Closure(static): TReturn) $callback */ public function __construct( protected Closure $callback ) { } /** * @return TReturn */ public function run(): mixed { DB::statement('SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED'); return DB::transaction($this->callback); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/FilePathNormalizer.php
app/Util/FilePathNormalizer.php
<?php namespace BookStack\Util; use League\Flysystem\WhitespacePathNormalizer; /** * Utility to normalize (potentially) user provided file paths * to avoid things like directory traversal. */ class FilePathNormalizer { public static function normalize(string $path): string { return (new WhitespacePathNormalizer())->normalizePath($path); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/OutOfMemoryHandler.php
app/Util/OutOfMemoryHandler.php
<?php namespace BookStack\Util; use BookStack\Exceptions\Handler; use Illuminate\Contracts\Debug\ExceptionHandler; /** * Create a handler which runs the provided actions upon an * out-of-memory event. This allows reserving of memory to allow * the desired action to run as needed. * * Essentially provides a wrapper and memory reserving around the * memory handling added to the default app error handler. */ class OutOfMemoryHandler { protected $onOutOfMemory; protected string $memoryReserve = ''; public function __construct(callable $onOutOfMemory, int $memoryReserveMB = 4) { $this->onOutOfMemory = $onOutOfMemory; $this->memoryReserve = str_repeat('x', $memoryReserveMB * 1_000_000); $this->getHandler()->prepareForOutOfMemory(function () { return $this->handle(); }); } protected function handle(): mixed { $result = null; $this->memoryReserve = ''; if ($this->onOutOfMemory) { $result = call_user_func($this->onOutOfMemory); $this->forget(); } return $result; } /** * Forget the handler, so no action is taken place on out of memory. */ public function forget(): void { $this->memoryReserve = ''; $this->onOutOfMemory = null; $this->getHandler()->forgetOutOfMemoryHandler(); } protected function getHandler(): Handler { /** * We want to resolve our specific BookStack handling via the set app handler * singleton, but phpstan will only infer based on the interface. * @phpstan-ignore return.type */ return app()->make(ExceptionHandler::class); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/SimpleListOptions.php
app/Util/SimpleListOptions.php
<?php namespace BookStack\Util; use Illuminate\Http\Request; /** * Handled options commonly used for item lists within the system, providing a standard * model for handling and validating sort, order and search options. */ class SimpleListOptions { protected string $typeKey; protected string $sort; protected string $order; protected string $search; protected array $sortOptions = []; public function __construct(string $typeKey, string $sort, string $order, string $search = '') { $this->typeKey = $typeKey; $this->sort = $sort; $this->order = $order; $this->search = $search; } /** * Create a new instance from the given request. * Takes the item type (plural) that's used as a key for storing sort preferences. */ public static function fromRequest(Request $request, string $typeKey, bool $sortDescDefault = false): self { $search = $request->get('search', ''); $sort = setting()->getForCurrentUser($typeKey . '_sort', ''); $order = setting()->getForCurrentUser($typeKey . '_sort_order', $sortDescDefault ? 'desc' : 'asc'); return new self($typeKey, $sort, $order, $search); } /** * Configure the valid sort options for this set of list options. * Provided sort options must be an array, keyed by search properties * with values being user-visible option labels. * Returns current options for easy fluent usage during creation. */ public function withSortOptions(array $sortOptions): self { $this->sortOptions = array_merge($this->sortOptions, $sortOptions); return $this; } /** * Get the current order option. */ public function getOrder(): string { return strtolower($this->order) === 'desc' ? 'desc' : 'asc'; } /** * Get the current sort option. */ public function getSort(): string { $default = array_key_first($this->sortOptions) ?? 'name'; $sort = $this->sort ?: $default; if (empty($this->sortOptions) || array_key_exists($sort, $this->sortOptions)) { return $sort; } return $default; } /** * Get the set search term. */ public function getSearch(): string { return $this->search; } /** * Get the data to append for pagination. */ public function getPaginationAppends(): array { return ['search' => $this->search]; } /** * Get the data required by the sort control view. */ public function getSortControlData(): array { return [ 'options' => $this->sortOptions, 'order' => $this->getOrder(), 'sort' => $this->getSort(), 'type' => $this->typeKey, ]; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/HtmlNonceApplicator.php
app/Util/HtmlNonceApplicator.php
<?php namespace BookStack\Util; use DOMElement; use DOMNodeList; class HtmlNonceApplicator { protected static string $placeholder = '[CSP_NONCE_VALUE]'; /** * Prepare the given HTML content with nonce attributes including a placeholder * value which we can target later. */ public static function prepare(string $html): string { if (empty($html)) { return $html; } // LIBXML_SCHEMA_CREATE was found to be required here otherwise // the PHP DOMDocument handling will attempt to format/close // HTML tags within scripts and therefore change JS content. $doc = new HtmlDocument($html, LIBXML_SCHEMA_CREATE); // Apply to scripts $scriptElems = $doc->queryXPath('//script'); static::addNonceAttributes($scriptElems, static::$placeholder); // Apply to styles $styleElems = $doc->queryXPath('//style'); static::addNonceAttributes($styleElems, static::$placeholder); return $doc->getBodyInnerHtml(); } /** * Apply the give nonce value to the given prepared HTML. */ public static function apply(string $html, string $nonce): string { return str_replace(static::$placeholder, $nonce, $html); } protected static function addNonceAttributes(DOMNodeList $nodes, string $attrValue): void { /** @var DOMElement $node */ foreach ($nodes as $node) { $node->setAttribute('nonce', $attrValue); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/SsrUrlValidator.php
app/Util/SsrUrlValidator.php
<?php namespace BookStack\Util; use BookStack\Exceptions\HttpFetchException; /** * Validate the host we're connecting to when making a server-side-request. * Will use the given hosts config if given during construction otherwise * will look to the app configured config. */ class SsrUrlValidator { protected string $config; public function __construct(?string $config = null) { $this->config = $config ?? config('app.ssr_hosts') ?? ''; } /** * @throws HttpFetchException */ public function ensureAllowed(string $url): void { if (!$this->allowed($url)) { throw new HttpFetchException(trans('errors.http_ssr_url_no_match')); } } /** * Check if the given URL is allowed by the configured SSR host values. */ public function allowed(string $url): bool { $allowed = $this->getHostPatterns(); foreach ($allowed as $pattern) { if ($this->urlMatchesPattern($url, $pattern)) { return true; } } return false; } protected function urlMatchesPattern($url, $pattern): bool { $pattern = rtrim(trim($pattern), '/'); $url = trim($url); if (empty($pattern) || empty($url)) { return false; } $quoted = preg_quote($pattern, '/'); $regexPattern = str_replace('\*', '.*', $quoted); return preg_match('/^' . $regexPattern . '($|\/.*$|#.*$)/i', $url); } /** * @return string[] */ protected function getHostPatterns(): array { return explode(' ', strtolower($this->config)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/SvgIcon.php
app/Util/SvgIcon.php
<?php namespace BookStack\Util; class SvgIcon { public function __construct( protected string $name, protected array $attrs = [] ) { } public function toHtml(): string { $attrs = array_merge([ 'class' => 'svg-icon', 'data-icon' => $this->name, 'role' => 'presentation', ], $this->attrs); $attrString = ' '; foreach ($attrs as $attrName => $attr) { $attrString .= $attrName . '="' . $attr . '" '; } $iconPath = resource_path('icons/' . $this->name . '.svg'); $themeIconPath = theme_path('icons/' . $this->name . '.svg'); if ($themeIconPath && file_exists($themeIconPath)) { $iconPath = $themeIconPath; } elseif (!file_exists($iconPath)) { return ''; } $fileContents = file_get_contents($iconPath); return str_replace('<svg', '<svg' . $attrString, $fileContents); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/DateFormatter.php
app/Util/DateFormatter.php
<?php namespace BookStack\Util; use Carbon\Carbon; use Carbon\CarbonInterface; class DateFormatter { public function __construct( protected string $displayTimezone, ) { } public function absolute(Carbon $date): string { $withDisplayTimezone = $date->clone()->setTimezone($this->displayTimezone); return $withDisplayTimezone->format('Y-m-d H:i:s T'); } public function relative(Carbon $date, bool $includeSuffix = true): string { return $date->diffForHumans(null, $includeSuffix ? null : CarbonInterface::DIFF_ABSOLUTE); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/HtmlContentFilter.php
app/Util/HtmlContentFilter.php
<?php namespace BookStack\Util; use DOMAttr; use DOMElement; use DOMNodeList; class HtmlContentFilter { /** * Remove all the script elements from the given HTML document. */ public static function removeScriptsFromDocument(HtmlDocument $doc) { // Remove standard script tags $scriptElems = $doc->queryXPath('//script'); static::removeNodes($scriptElems); // Remove clickable links to JavaScript URI $badLinks = $doc->queryXPath('//*[' . static::xpathContains('@href', 'javascript:') . ']'); static::removeNodes($badLinks); // Remove forms with calls to JavaScript URI $badForms = $doc->queryXPath('//*[' . static::xpathContains('@action', 'javascript:') . '] | //*[' . static::xpathContains('@formaction', 'javascript:') . ']'); static::removeNodes($badForms); // Remove meta tag to prevent external redirects $metaTags = $doc->queryXPath('//meta[' . static::xpathContains('@content', 'url') . ']'); static::removeNodes($metaTags); // Remove data or JavaScript iFrames $badIframes = $doc->queryXPath('//*[' . static::xpathContains('@src', 'data:') . '] | //*[' . static::xpathContains('@src', 'javascript:') . '] | //*[@srcdoc]'); static::removeNodes($badIframes); // Remove attributes, within svg children, hiding JavaScript or data uris. // A bunch of svg element and attribute combinations expose xss possibilities. // For example, SVG animate tag can exploit javascript in values. $badValuesAttrs = $doc->queryXPath('//svg//@*[' . static::xpathContains('.', 'data:') . '] | //svg//@*[' . static::xpathContains('.', 'javascript:') . ']'); static::removeAttributes($badValuesAttrs); // Remove elements with a xlink:href attribute // Used in SVG but deprecated anyway, so we'll be a bit more heavy-handed here. $xlinkHrefAttributes = $doc->queryXPath('//@*[contains(name(), \'xlink:href\')]'); static::removeAttributes($xlinkHrefAttributes); // Remove 'on*' attributes $onAttributes = $doc->queryXPath('//@*[starts-with(name(), \'on\')]'); static::removeAttributes($onAttributes); } /** * Remove scripts from the given HTML string. */ public static function removeScriptsFromHtmlString(string $html): string { if (empty($html)) { return $html; } $doc = new HtmlDocument($html); static::removeScriptsFromDocument($doc); return $doc->getBodyInnerHtml(); } /** * Create a xpath contains statement with a translation automatically built within * to affectively search in a cases-insensitive manner. */ protected static function xpathContains(string $property, string $value): string { $value = strtolower($value); $upperVal = strtoupper($value); return 'contains(translate(' . $property . ', \'' . $upperVal . '\', \'' . $value . '\'), \'' . $value . '\')'; } /** * Remove all the given DOMNodes. */ protected static function removeNodes(DOMNodeList $nodes): void { foreach ($nodes as $node) { $node->parentNode->removeChild($node); } } /** * Remove all the given attribute nodes. */ protected static function removeAttributes(DOMNodeList $attrs): void { /** @var DOMAttr $attr */ foreach ($attrs as $attr) { $attrName = $attr->nodeName; /** @var DOMElement $parentNode */ $parentNode = $attr->parentNode; $parentNode->removeAttribute($attrName); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Util/HtmlDescriptionFilter.php
app/Util/HtmlDescriptionFilter.php
<?php namespace BookStack\Util; use DOMAttr; use DOMElement; use DOMNode; /** * Filter to ensure HTML input for description content remains simple and * to a limited allow-list of elements and attributes. * More for consistency and to prevent nuisance rather than for security * (which would be done via a separate content filter and CSP). */ class HtmlDescriptionFilter { /** * @var array<string, string[]> */ protected static array $allowedAttrsByElements = [ 'p' => [], 'a' => ['href', 'title', 'target', 'data-mention-user-id'], 'ol' => [], 'ul' => [], 'li' => [], 'strong' => [], 'span' => [], 'em' => [], 'br' => [], ]; public static function filterFromString(string $html): string { if (empty(trim($html))) { return ''; } $doc = new HtmlDocument($html); $topLevel = [...$doc->getBodyChildren()]; foreach ($topLevel as $child) { /** @var DOMNode $child */ if ($child instanceof DOMElement) { static::filterElement($child); } else { $child->parentNode->removeChild($child); } } return $doc->getBodyInnerHtml(); } protected static function filterElement(DOMElement $element): void { $elType = strtolower($element->tagName); $allowedAttrs = static::$allowedAttrsByElements[$elType] ?? null; if (is_null($allowedAttrs)) { $element->remove(); return; } $attrs = $element->attributes; for ($i = $attrs->length - 1; $i >= 0; $i--) { /** @var DOMAttr $attr */ $attr = $attrs->item($i); $name = strtolower($attr->name); if (!in_array($name, $allowedAttrs)) { $element->removeAttribute($attr->name); } } $childNodes = [...$element->childNodes]; foreach ($childNodes as $child) { if ($child instanceof DOMElement) { static::filterElement($child); } } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/exports.php
app/Config/exports.php
<?php /** * Export configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ $snappyPaperSizeMap = [ 'a4' => 'A4', 'letter' => 'Letter', ]; $dompdfPaperSizeMap = [ 'a4' => 'a4', 'letter' => 'letter', ]; $exportPageSize = env('EXPORT_PAGE_SIZE', 'a4'); return [ // Set a command which can be used to convert a HTML file into a PDF file. // When false this will not be used. // String values represent the command to be called for conversion. // Supports '{input_html_path}' and '{output_pdf_path}' placeholder values. // Example: EXPORT_PDF_COMMAND="/scripts/convert.sh {input_html_path} {output_pdf_path}" 'pdf_command' => env('EXPORT_PDF_COMMAND', false), // The amount of time allowed for PDF generation command to run // before the process times out and is stopped. 'pdf_command_timeout' => env('EXPORT_PDF_COMMAND_TIMEOUT', 15), // 2024-04: Snappy/WKHTMLtoPDF now considered deprecated in regard to BookStack support. 'snappy' => [ 'pdf_binary' => env('WKHTMLTOPDF', false), 'options' => [ 'print-media-type' => true, 'outline' => true, 'page-size' => $snappyPaperSizeMap[$exportPageSize] ?? 'A4', ], ], 'dompdf' => [ /** * The location of the DOMPDF font directory. * * The location of the directory where DOMPDF will store fonts and font metrics * Note: This directory must exist and be writable by the webserver process. * *Please note the trailing slash.* * * Notes regarding fonts: * Additional .afm font metrics can be added by executing load_font.php from command line. * * Only the original "Base 14 fonts" are present on all pdf viewers. Additional fonts must * be embedded in the pdf file or the PDF may not display correctly. This can significantly * increase file size unless font subsetting is enabled. Before embedding a font please * review your rights under the font license. * * Any font specification in the source HTML is translated to the closest font available * in the font directory. * * The pdf standard "Base 14 fonts" are: * Courier, Courier-Bold, Courier-BoldOblique, Courier-Oblique, * Helvetica, Helvetica-Bold, Helvetica-BoldOblique, Helvetica-Oblique, * Times-Roman, Times-Bold, Times-BoldItalic, Times-Italic, * Symbol, ZapfDingbats. */ 'font_dir' => storage_path('fonts/'), // advised by dompdf (https://github.com/dompdf/dompdf/pull/782) /** * The location of the DOMPDF font cache directory. * * This directory contains the cached font metrics for the fonts used by DOMPDF. * This directory can be the same as DOMPDF_FONT_DIR * * Note: This directory must exist and be writable by the webserver process. */ 'font_cache' => storage_path('fonts/'), /** * The location of a temporary directory. * * The directory specified must be writeable by the webserver process. * The temporary directory is required to download remote images and when * using the PFDLib back end. */ 'temp_dir' => sys_get_temp_dir(), /** * ==== IMPORTANT ====. * * dompdf's "chroot": Prevents dompdf from accessing system files or other * files on the webserver. All local files opened by dompdf must be in a * subdirectory of this directory. DO NOT set it to '/' since this could * allow an attacker to use dompdf to read any files on the server. This * should be an absolute path. * This is only checked on command line call by dompdf.php, but not by * direct class use like: * $dompdf = new DOMPDF(); $dompdf->load_html($htmldata); $dompdf->render(); $pdfdata = $dompdf->output(); */ 'chroot' => realpath(public_path()), /** * Protocol whitelist. * * Protocols and PHP wrappers allowed in URIs, and the validation rules * that determine if a resouce may be loaded. Full support is not guaranteed * for the protocols/wrappers specified * by this array. * * @var array */ 'allowed_protocols' => [ "data://" => ["rules" => []], 'file://' => ['rules' => []], 'http://' => ['rules' => []], 'https://' => ['rules' => []], ], /** * @var string */ 'log_output_file' => null, /** * Whether to enable font subsetting or not. */ 'enable_font_subsetting' => false, /** * The PDF rendering backend to use. * * Valid settings are 'PDFLib', 'CPDF' (the bundled R&OS PDF class), 'GD' and * 'auto'. 'auto' will look for PDFLib and use it if found, or if not it will * fall back on CPDF. 'GD' renders PDFs to graphic files. {@link * Canvas_Factory} ultimately determines which rendering class to instantiate * based on this setting. * * Both PDFLib & CPDF rendering backends provide sufficient rendering * capabilities for dompdf, however additional features (e.g. object, * image and font support, etc.) differ between backends. Please see * {@link PDFLib_Adapter} for more information on the PDFLib backend * and {@link CPDF_Adapter} and lib/class.pdf.php for more information * on CPDF. Also see the documentation for each backend at the links * below. * * The GD rendering backend is a little different than PDFLib and * CPDF. Several features of CPDF and PDFLib are not supported or do * not make any sense when creating image files. For example, * multiple pages are not supported, nor are PDF 'objects'. Have a * look at {@link GD_Adapter} for more information. GD support is * experimental, so use it at your own risk. * * @link http://www.pdflib.com * @link http://www.ros.co.nz/pdf * @link http://www.php.net/image */ 'pdf_backend' => 'CPDF', /** * PDFlib license key. * * If you are using a licensed, commercial version of PDFlib, specify * your license key here. If you are using PDFlib-Lite or are evaluating * the commercial version of PDFlib, comment out this setting. * * @link http://www.pdflib.com * * If pdflib present in web server and auto or selected explicitely above, * a real license code must exist! */ //"DOMPDF_PDFLIB_LICENSE" => "your license key here", /** * html target media view which should be rendered into pdf. * List of types and parsing rules for future extensions: * http://www.w3.org/TR/REC-html40/types.html * screen, tty, tv, projection, handheld, print, braille, aural, all * Note: aural is deprecated in CSS 2.1 because it is replaced by speech in CSS 3. * Note, even though the generated pdf file is intended for print output, * the desired content might be different (e.g. screen or projection view of html file). * Therefore allow specification of content here. */ 'default_media_type' => 'print', /** * The default paper size. * * North America standard is "letter"; other countries generally "a4" * * @see CPDF_Adapter::PAPER_SIZES for valid sizes ('letter', 'legal', 'A4', etc.) */ 'default_paper_size' => $dompdfPaperSizeMap[$exportPageSize] ?? 'a4', /** * The default paper orientation. * * The orientation of the page (portrait or landscape). * * @var string */ 'default_paper_orientation' => 'portrait', /** * The default font family. * * Used if no suitable fonts can be found. This must exist in the font folder. * * @var string */ 'default_font' => 'dejavu sans', /** * Image DPI setting. * * This setting determines the default DPI setting for images and fonts. The * DPI may be overridden for inline images by explictly setting the * image's width & height style attributes (i.e. if the image's native * width is 600 pixels and you specify the image's width as 72 points, * the image will have a DPI of 600 in the rendered PDF. The DPI of * background images can not be overridden and is controlled entirely * via this parameter. * * For the purposes of DOMPDF, pixels per inch (PPI) = dots per inch (DPI). * If a size in html is given as px (or without unit as image size), * this tells the corresponding size in pt. * This adjusts the relative sizes to be similar to the rendering of the * html page in a reference browser. * * In pdf, always 1 pt = 1/72 inch * * Rendering resolution of various browsers in px per inch: * Windows Firefox and Internet Explorer: * SystemControl->Display properties->FontResolution: Default:96, largefonts:120, custom:? * Linux Firefox: * about:config *resolution: Default:96 * (xorg screen dimension in mm and Desktop font dpi settings are ignored) * * Take care about extra font/image zoom factor of browser. * * In images, <img> size in pixel attribute, img css style, are overriding * the real image dimension in px for rendering. * * @var int */ 'dpi' => 96, /** * Enable inline PHP. * * If this setting is set to true then DOMPDF will automatically evaluate * inline PHP contained within <script type="text/php"> ... </script> tags. * * Enabling this for documents you do not trust (e.g. arbitrary remote html * pages) is a security risk. Set this option to false if you wish to process * untrusted documents. * * @var bool */ 'enable_php' => false, /** * Enable inline Javascript. * * If this setting is set to true then DOMPDF will automatically insert * JavaScript code contained within <script type="text/javascript"> ... </script> tags. * * @var bool */ 'enable_javascript' => false, /** * Enable remote file access. * * If this setting is set to true, DOMPDF will access remote sites for * images and CSS files as required. * This is required for part of test case www/test/image_variants.html through www/examples.php * * Attention! * This can be a security risk, in particular in combination with DOMPDF_ENABLE_PHP and * allowing remote access to dompdf.php or on allowing remote html code to be passed to * $dompdf = new DOMPDF(, $dompdf->load_html(..., * This allows anonymous users to download legally doubtful internet content which on * tracing back appears to being downloaded by your server, or allows malicious php code * in remote html pages to be executed by your server with your account privileges. * * @var bool */ 'enable_remote' => env('ALLOW_UNTRUSTED_SERVER_FETCHING', false), /** * A ratio applied to the fonts height to be more like browsers' line height. */ 'font_height_ratio' => 1.1, /** * Use the HTML5 Lib parser. * * @deprecated This feature is now always on in dompdf 2.x * * @var bool */ 'enable_html5_parser' => true, ], ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/app.php
app/Config/app.php
<?php /** * Global app configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ use Illuminate\Support\Facades\Facade; use Illuminate\Support\ServiceProvider; return [ // The environment to run BookStack in. // Options: production, development, demo, testing 'env' => env('APP_ENV', 'production'), // Enter the application in debug mode. // Shows much more verbose error messages. Has potential to show // private configuration variables so should remain disabled in public. 'debug' => env('APP_DEBUG', false), // The number of revisions to keep in the database. // Once this limit is reached older revisions will be deleted. // If set to false then a limit will not be enforced. 'revision_limit' => env('REVISION_LIMIT', 100), // The number of days that content will remain in the recycle bin before // being considered for auto-removal. It is not a guarantee that content will // be removed after this time. // Set to 0 for no recycle bin functionality. // Set to -1 for unlimited recycle bin lifetime. 'recycle_bin_lifetime' => env('RECYCLE_BIN_LIFETIME', 30), // The limit for all uploaded files, including images and attachments in MB. 'upload_limit' => env('FILE_UPLOAD_SIZE_LIMIT', 50), // Allow <script> tags to entered within page content. // <script> tags are escaped by default. // Even when overridden the WYSIWYG editor may still escape script content. 'allow_content_scripts' => env('ALLOW_CONTENT_SCRIPTS', false), // Allow server-side fetches to be performed to potentially unknown // and user-provided locations. Primarily used in exports when loading // in externally referenced assets. 'allow_untrusted_server_fetching' => env('ALLOW_UNTRUSTED_SERVER_FETCHING', false), // Override the default behaviour for allowing crawlers to crawl the instance. // May be ignored if view has be overridden or modified. // Defaults to null since, if not set, 'app-public' status used instead. 'allow_robots' => env('ALLOW_ROBOTS', null), // Application Base URL, Used by laravel in development commands // and used by BookStack in URL generation. 'url' => env('APP_URL', '') === 'http://bookstack.dev' ? '' : env('APP_URL', ''), // A list of hosts that BookStack can be iframed within. // Space separated if multiple. BookStack host domain is auto-inferred. 'iframe_hosts' => env('ALLOWED_IFRAME_HOSTS', null), // A list of sources/hostnames that can be loaded within iframes within BookStack. // Space separated if multiple. BookStack host domain is auto-inferred. // Can be set to a lone "*" to allow all sources for iframe content (Not advised). // Defaults to a set of common services. // Current host and source for the "DRAWIO" setting will be auto-appended to the sources configured. 'iframe_sources' => env('ALLOWED_IFRAME_SOURCES', 'https://*.draw.io https://*.youtube.com https://*.youtube-nocookie.com https://*.vimeo.com'), // A list of the sources/hostnames that can be reached by application SSR calls. // This is used wherever users can provide URLs/hosts in-platform, like for webhooks. // Host-specific functionality (usually controlled via other options) like auth // or user avatars, for example, won't use this list. // Space separated if multiple. Can use '*' as a wildcard. // Values will be compared prefix-matched, case-insensitive, against called SSR urls. // Defaults to allow all hosts. 'ssr_hosts' => env('ALLOWED_SSR_HOSTS', '*'), // Alter the precision of IP addresses stored by BookStack. // Integer value between 0 (IP hidden) to 4 (Full IP usage) 'ip_address_precision' => env('IP_ADDRESS_PRECISION', 4), // Application timezone for stored date/time values. 'timezone' => env('APP_TIMEZONE', 'UTC'), // Application timezone for displayed date/time values in the UI. 'display_timezone' => env('APP_DISPLAY_TIMEZONE', env('APP_TIMEZONE', 'UTC')), // Default locale to use // A default variant is also stored since Laravel can overwrite // app.locale when dynamically setting the locale in-app. 'locale' => env('APP_LANG', 'en'), 'default_locale' => env('APP_LANG', 'en'), // Application Fallback Locale 'fallback_locale' => 'en', // Faker Locale 'faker_locale' => 'en_GB', // Auto-detect the locale for public users // For public users their locale can be guessed by headers sent by their // browser. This is usually set by users in their browser settings. // If not found the default app locale will be used. 'auto_detect_locale' => env('APP_AUTO_LANG_PUBLIC', true), // Encryption key 'key' => env('APP_KEY', 'AbAZchsay4uBTU33RubBzLKw203yqSqr'), // Encryption cipher 'cipher' => 'AES-256-CBC', // Maintenance Mode Driver 'maintenance' => [ 'driver' => 'file', // 'store' => 'redis', ], // Application Service Providers 'providers' => ServiceProvider::defaultProviders()->merge([ // Third party service providers SocialiteProviders\Manager\ServiceProvider::class, // BookStack custom service providers BookStack\App\Providers\ThemeServiceProvider::class, BookStack\App\Providers\AppServiceProvider::class, BookStack\App\Providers\AuthServiceProvider::class, BookStack\App\Providers\EventServiceProvider::class, BookStack\App\Providers\RouteServiceProvider::class, BookStack\App\Providers\TranslationServiceProvider::class, BookStack\App\Providers\ValidationRuleServiceProvider::class, BookStack\App\Providers\ViewTweaksServiceProvider::class, ])->toArray(), // Class Aliases // This array of class aliases to be registered on application start. 'aliases' => Facade::defaultAliases()->merge([ // Laravel Packages 'Socialite' => Laravel\Socialite\Facades\Socialite::class, // Custom BookStack 'Activity' => BookStack\Facades\Activity::class, 'Theme' => BookStack\Facades\Theme::class, ])->toArray(), // Proxy configuration 'proxies' => env('APP_PROXIES', ''), ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/clockwork.php
app/Config/clockwork.php
<?php return [ /* |------------------------------------------------------------------------------------------------------------------ | Enable Clockwork |------------------------------------------------------------------------------------------------------------------ | | Clockwork is enabled by default only when your application is in debug mode. Here you can explicitly enable or | disable Clockwork. When disabled, no data is collected and the api and web ui are inactive. | */ 'enable' => env('CLOCKWORK_ENABLE', false), /* |------------------------------------------------------------------------------------------------------------------ | Features |------------------------------------------------------------------------------------------------------------------ | | You can enable or disable various Clockwork features here. Some features have additional settings (eg. slow query | threshold for database queries). | */ 'features' => [ // Cache usage stats and cache queries including results 'cache' => [ 'enabled' => true, // Collect cache queries 'collect_queries' => true, // Collect values from cache queries (high performance impact with a very high number of queries) 'collect_values' => false, ], // Database usage stats and queries 'database' => [ 'enabled' => true, // Collect database queries (high performance impact with a very high number of queries) 'collect_queries' => true, // Collect details of models updates (high performance impact with a lot of model updates) 'collect_models_actions' => true, // Collect details of retrieved models (very high performance impact with a lot of models retrieved) 'collect_models_retrieved' => false, // Query execution time threshold in miliseconds after which the query will be marked as slow 'slow_threshold' => null, // Collect only slow database queries 'slow_only' => false, // Detect and report duplicate (N+1) queries 'detect_duplicate_queries' => false, ], // Dispatched events 'events' => [ 'enabled' => true, // Ignored events (framework events are ignored by default) 'ignored_events' => [ // App\Events\UserRegistered::class, // 'user.registered' ], ], // Laravel log (you can still log directly to Clockwork with laravel log disabled) 'log' => [ 'enabled' => true, ], // Sent notifications 'notifications' => [ 'enabled' => true, ], // Performance metrics 'performance' => [ // Allow collecting of client metrics. Requires separate clockwork-browser npm package. 'client_metrics' => true, ], // Dispatched queue jobs 'queue' => [ 'enabled' => true, ], // Redis commands 'redis' => [ 'enabled' => true, ], // Routes list 'routes' => [ 'enabled' => false, // Collect only routes from particular namespaces (only application routes by default) 'only_namespaces' => ['App'], ], // Rendered views 'views' => [ 'enabled' => true, // Collect views including view data (high performance impact with a high number of views) 'collect_data' => false, // Use Twig profiler instead of Laravel events for apps using laravel-twigbridge (more precise, but does // not support collecting view data) 'use_twig_profiler' => false, ], ], /* |------------------------------------------------------------------------------------------------------------------ | Enable web UI |------------------------------------------------------------------------------------------------------------------ | | Clockwork comes with a web UI accessibla via http://your.app/clockwork. Here you can enable or disable this | feature. You can also set a custom path for the web UI. | */ 'web' => true, /* |------------------------------------------------------------------------------------------------------------------ | Enable toolbar |------------------------------------------------------------------------------------------------------------------ | | Clockwork can show a toolbar with basic metrics on all responses. Here you can enable or disable this feature. | Requires a separate clockwork-browser npm library. | For installation instructions see https://underground.works/clockwork/#docs-viewing-data | */ 'toolbar' => true, /* |------------------------------------------------------------------------------------------------------------------ | HTTP requests collection |------------------------------------------------------------------------------------------------------------------ | | Clockwork collects data about HTTP requests to your app. Here you can choose which requests should be collected. | */ 'requests' => [ // With on-demand mode enabled, Clockwork will only profile requests when the browser extension is open or you // manually pass a "clockwork-profile" cookie or get/post data key. // Optionally you can specify a "secret" that has to be passed as the value to enable profiling. 'on_demand' => false, // Collect only errors (requests with HTTP 4xx and 5xx responses) 'errors_only' => false, // Response time threshold in miliseconds after which the request will be marked as slow 'slow_threshold' => null, // Collect only slow requests 'slow_only' => false, // Sample the collected requests (eg. set to 100 to collect only 1 in 100 requests) 'sample' => false, // List of URIs that should not be collected 'except' => [ '/uploads/images/.*', // BookStack image requests '/horizon/.*', // Laravel Horizon requests '/telescope/.*', // Laravel Telescope requests '/_debugbar/.*', // Laravel DebugBar requests ], // List of URIs that should be collected, any other URI will not be collected if not empty 'only' => [ // '/api/.*' ], // Don't collect OPTIONS requests, mostly used in the CSRF pre-flight requests and are rarely of interest 'except_preflight' => true, ], /* |------------------------------------------------------------------------------------------------------------------ | Artisan commands collection |------------------------------------------------------------------------------------------------------------------ | | Clockwork can collect data about executed artisan commands. Here you can enable and configure which commands | should be collected. | */ 'artisan' => [ // Enable or disable collection of executed Artisan commands 'collect' => false, // List of commands that should not be collected (built-in commands are not collected by default) 'except' => [ // 'inspire' ], // List of commands that should be collected, any other command will not be collected if not empty 'only' => [ // 'inspire' ], // Enable or disable collection of command output 'collect_output' => false, // Enable or disable collection of built-in Laravel commands 'except_laravel_commands' => true, ], /* |------------------------------------------------------------------------------------------------------------------ | Queue jobs collection |------------------------------------------------------------------------------------------------------------------ | | Clockwork can collect data about executed queue jobs. Here you can enable and configure which queue jobs should | be collected. | */ 'queue' => [ // Enable or disable collection of executed queue jobs 'collect' => false, // List of queue jobs that should not be collected 'except' => [ // App\Jobs\ExpensiveJob::class ], // List of queue jobs that should be collected, any other queue job will not be collected if not empty 'only' => [ // App\Jobs\BuggyJob::class ], ], /* |------------------------------------------------------------------------------------------------------------------ | Tests collection |------------------------------------------------------------------------------------------------------------------ | | Clockwork can collect data about executed tests. Here you can enable and configure which tests should be | collected. | */ 'tests' => [ // Enable or disable collection of ran tests 'collect' => false, // List of tests that should not be collected 'except' => [ // Tests\Unit\ExampleTest::class ], ], /* |------------------------------------------------------------------------------------------------------------------ | Enable data collection when Clockwork is disabled |------------------------------------------------------------------------------------------------------------------ | | You can enable this setting to collect data even when Clockwork is disabled. Eg. for future analysis. | */ 'collect_data_always' => false, /* |------------------------------------------------------------------------------------------------------------------ | Metadata storage |------------------------------------------------------------------------------------------------------------------ | | Configure how is the metadata collected by Clockwork stored. Two options are available: | - files - A simple fast storage implementation storing data in one-per-request files. | - sql - Stores requests in a sql database. Supports MySQL, Postgresql, Sqlite and requires PDO. | */ 'storage' => 'files', // Path where the Clockwork metadata is stored 'storage_files_path' => storage_path('clockwork'), // Compress the metadata files using gzip, trading a little bit of performance for lower disk usage 'storage_files_compress' => false, // SQL database to use, can be a name of database configured in database.php or a path to a sqlite file 'storage_sql_database' => storage_path('clockwork.sqlite'), // SQL table name to use, the table is automatically created and udpated when needed 'storage_sql_table' => 'clockwork', // Maximum lifetime of collected metadata in minutes, older requests will automatically be deleted, false to disable 'storage_expiration' => 60 * 24 * 7, /* |------------------------------------------------------------------------------------------------------------------ | Authentication |------------------------------------------------------------------------------------------------------------------ | | Clockwork can be configured to require authentication before allowing access to the collected data. This might be | useful when the application is publicly accessible. Setting to true will enable a simple authentication with a | pre-configured password. You can also pass a class name of a custom implementation. | */ 'authentication' => false, // Password for the simple authentication 'authentication_password' => 'VerySecretPassword', /* |------------------------------------------------------------------------------------------------------------------ | Stack traces collection |------------------------------------------------------------------------------------------------------------------ | | Clockwork can collect stack traces for log messages and certain data like database queries. Here you can set | whether to collect stack traces, limit the number of collected frames and set further configuration. Collecting | long stack traces considerably increases metadata size. | */ 'stack_traces' => [ // Enable or disable collecting of stack traces 'enabled' => true, // Limit the number of frames to be collected 'limit' => 10, // List of vendor names to skip when determining caller, common vendors are automatically added 'skip_vendors' => [ // 'phpunit' ], // List of namespaces to skip when determining caller 'skip_namespaces' => [ // 'Laravel' ], // List of class names to skip when determining caller 'skip_classes' => [ // App\CustomLog::class ], ], /* |------------------------------------------------------------------------------------------------------------------ | Serialization |------------------------------------------------------------------------------------------------------------------ | | Clockwork serializes the collected data to json for storage and transfer. Here you can configure certain aspects | of serialization. Serialization has a large effect on the cpu time and memory usage. | */ // Maximum depth of serialized multi-level arrays and objects 'serialization_depth' => 10, // A list of classes that will never be serialized (eg. a common service container class) 'serialization_blackbox' => [ \Illuminate\Container\Container::class, \Illuminate\Foundation\Application::class, ], /* |------------------------------------------------------------------------------------------------------------------ | Register helpers |------------------------------------------------------------------------------------------------------------------ | | Clockwork comes with a "clock" global helper function. You can use this helper to quickly log something and to | access the Clockwork instance. | */ 'register_helpers' => true, /* |------------------------------------------------------------------------------------------------------------------ | Send Headers for AJAX request |------------------------------------------------------------------------------------------------------------------ | | When trying to collect data the AJAX method can sometimes fail if it is missing required headers. For example, an | API might require a version number using Accept headers to route the HTTP request to the correct codebase. | */ 'headers' => [ // 'Accept' => 'application/vnd.com.whatever.v1+json', ], /* |------------------------------------------------------------------------------------------------------------------ | Server-Timing |------------------------------------------------------------------------------------------------------------------ | | Clockwork supports the W3C Server Timing specification, which allows for collecting a simple performance metrics | in a cross-browser way. Eg. in Chrome, your app, database and timeline event timings will be shown in the Dev | Tools network tab. This setting specifies the max number of timeline events that will be sent. Setting to false | will disable the feature. | */ 'server_timing' => 10, ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/logging.php
app/Config/logging.php
<?php use Monolog\Formatter\LineFormatter; use Monolog\Handler\ErrorLogHandler; use Monolog\Handler\NullHandler; use Monolog\Handler\StreamHandler; use Monolog\Processor\PsrLogMessageProcessor; /** * Logging configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ return [ // Default Log Channel // This option defines the default log channel that gets used when writing // messages to the logs. The name specified in this option should match // one of the channels defined in the "channels" configuration array. 'default' => env('LOG_CHANNEL', 'single'), // Deprecations Log Channel // This option controls the log channel that should be used to log warnings // regarding deprecated PHP and library features. This allows you to get // your application ready for upcoming major versions of dependencies. 'deprecations' => [ 'channel' => 'null', 'trace' => false, ], // Log Channels // Here you may configure the log channels for your application. Out of // the box, Laravel uses the Monolog PHP logging library. This gives // you a variety of powerful log handlers / formatters to utilize. // Available Drivers: "single", "daily", "slack", "syslog", // "errorlog", "monolog", // "custom", "stack" 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['daily'], 'ignore_exceptions' => false, ], 'single' => [ 'driver' => 'single', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', 'days' => 14, 'replace_placeholders' => true, ], 'daily' => [ 'driver' => 'daily', 'path' => storage_path('logs/laravel.log'), 'level' => 'debug', 'days' => 7, 'replace_placeholders' => true, ], 'stderr' => [ 'driver' => 'monolog', 'level' => 'debug', 'handler' => StreamHandler::class, 'with' => [ 'stream' => 'php://stderr', ], 'processors' => [PsrLogMessageProcessor::class], ], 'syslog' => [ 'driver' => 'syslog', 'level' => 'debug', 'facility' => LOG_USER, 'replace_placeholders' => true, ], 'errorlog' => [ 'driver' => 'errorlog', 'level' => 'debug', 'replace_placeholders' => true, ], // Custom errorlog implementation that logs out a plain, // non-formatted message intended for the webserver log. 'errorlog_plain_webserver' => [ 'driver' => 'monolog', 'level' => 'debug', 'handler' => ErrorLogHandler::class, 'handler_with' => [4], 'formatter' => LineFormatter::class, 'formatter_with' => [ 'format' => '%message%', ], 'replace_placeholders' => true, ], 'null' => [ 'driver' => 'monolog', 'handler' => NullHandler::class, ], // Testing channel // Uses a shared testing instance during tests // so that logs can be checked against. 'testing' => [ 'driver' => 'testing', ], 'emergency' => [ 'path' => storage_path('logs/laravel.log'), ], ], // Failed Login Message // Allows a configurable message to be logged when a login request fails. 'failed_login' => [ 'message' => env('LOG_FAILED_LOGIN_MESSAGE', null), 'channel' => env('LOG_FAILED_LOGIN_CHANNEL', 'errorlog_plain_webserver'), ], ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/session.php
app/Config/session.php
<?php use Illuminate\Support\Str; /** * Session configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ return [ // Default session driver // Options: file, cookie, database, redis, memcached, array 'driver' => env('SESSION_DRIVER', 'file'), // Session lifetime, in minutes 'lifetime' => env('SESSION_LIFETIME', 120), // Expire session on browser close 'expire_on_close' => false, // Encrypt session data 'encrypt' => false, // Location to store session files 'files' => storage_path('framework/sessions'), // Session Database Connection // When using the "database" or "redis" session drivers, you can specify a // connection that should be used to manage these sessions. This should // correspond to a connection in your database configuration options. 'connection' => null, // Session database table, if database driver is in use 'table' => 'sessions', // Session Cache Store // When using the "apc" or "memcached" session drivers, you may specify a // cache store that should be used for these sessions. This value must // correspond with one of the application's configured cache stores. 'store' => null, // Session Sweeping Lottery // Some session drivers must manually sweep their storage location to get // rid of old sessions from storage. Here are the chances that it will // happen on a given request. By default, the odds are 2 out of 100. 'lottery' => [2, 100], // Session Cookie Name // Here you may change the name of the cookie used to identify a session // instance by ID. The name specified here will get used every time a // new session cookie is created by the framework for every driver. 'cookie' => env('SESSION_COOKIE_NAME', 'bookstack_session'), // Session Cookie Path // The session cookie path determines the path for which the cookie will // be regarded as available. Typically, this will be the root path of // your application but you are free to change this when necessary. 'path' => '/' . (explode('/', env('APP_URL', ''), 4)[3] ?? ''), // Session Cookie Domain // Here you may change the domain of the cookie used to identify a session // in your application. This will determine which domains the cookie is // available to in your application. A sensible default has been set. 'domain' => env('SESSION_DOMAIN', null), // HTTPS Only Cookies // By setting this option to true, session cookies will only be sent back // to the server if the browser has a HTTPS connection. This will keep // the cookie from being sent to you if it can not be done securely. 'secure' => env('SESSION_SECURE_COOKIE', null) ?? Str::startsWith(env('APP_URL', ''), 'https:'), // HTTP Access Only // Setting this value to true will prevent JavaScript from accessing the // value of the cookie and the cookie will only be accessible through the HTTP protocol. 'http_only' => true, // Same-Site Cookies // This option determines how your cookies behave when cross-site requests // take place, and can be used to mitigate CSRF attacks. By default, we // do not enable this as other CSRF protection services are in place. // Options: lax, strict, none 'same_site' => 'lax', // Partitioned Cookies // Setting this value to true will tie the cookie to the top-level site for // a cross-site context. Partitioned cookies are accepted by the browser // when flagged "secure" and the Same-Site attribute is set to "none". 'partitioned' => false, ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/queue.php
app/Config/queue.php
<?php /** * Queue configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ return [ // Default driver to use for the queue // Options: sync, database, redis 'default' => env('QUEUE_CONNECTION', 'sync'), // Queue connection configuration 'connections' => [ 'sync' => [ 'driver' => 'sync', ], 'database' => [ 'driver' => 'database', 'connection' => null, 'table' => 'jobs', 'queue' => 'default', 'retry_after' => 90, 'after_commit' => false, ], 'redis' => [ 'driver' => 'redis', 'connection' => 'default', 'queue' => env('REDIS_QUEUE', 'default'), 'retry_after' => 90, 'block_for' => null, 'after_commit' => false, ], ], // Job batching 'batching' => [ 'database' => 'mysql', 'table' => 'job_batches', ], // Failed queue job logging 'failed' => [ 'driver' => 'database-uuids', 'database' => 'mysql', 'table' => 'failed_jobs', ], ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/setting-defaults.php
app/Config/setting-defaults.php
<?php /** * Default system settings. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ return [ 'app-name' => 'BookStack', 'app-logo' => '', 'app-name-header' => true, 'app-editor' => 'wysiwyg', 'app-color' => '#206ea7', 'app-color-light' => 'rgba(32,110,167,0.15)', 'link-color' => '#206ea7', 'bookshelf-color' => '#a94747', 'book-color' => '#077b70', 'chapter-color' => '#af4d0d', 'page-color' => '#206ea7', 'page-draft-color' => '#7e50b1', 'app-color-dark' => '#195785', 'app-color-light-dark' => 'rgba(32,110,167,0.15)', 'link-color-dark' => '#429fe3', 'bookshelf-color-dark' => '#ff5454', 'book-color-dark' => '#389f60', 'chapter-color-dark' => '#ee7a2d', 'page-color-dark' => '#429fe3', 'page-draft-color-dark' => '#a66ce8', 'app-custom-head' => false, 'registration-enabled' => false, // User-level default settings 'user' => [ 'ui-shortcuts' => '{}', 'ui-shortcuts-enabled' => false, 'dark-mode-enabled' => env('APP_DEFAULT_DARK_MODE', false), 'bookshelves_view_type' => env('APP_VIEWS_BOOKSHELVES', 'grid'), 'bookshelf_view_type' => env('APP_VIEWS_BOOKSHELF', 'grid'), 'books_view_type' => env('APP_VIEWS_BOOKS', 'grid'), 'notifications#comment-mentions' => true, ], ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/debugbar.php
app/Config/debugbar.php
<?php /** * Debugbar Configuration Options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ return [ // Debugbar is enabled by default, when debug is set to true in app.php. // You can override the value by setting enable to true or false instead of null. // // You can provide an array of URI's that must be ignored (eg. 'api/*') 'enabled' => env('DEBUGBAR_ENABLED', false), 'except' => [ 'telescope*', ], // DebugBar stores data for session/ajax requests. // You can disable this, so the debugbar stores data in headers/session, // but this can cause problems with large data collectors. // By default, file storage (in the storage folder) is used. Redis and PDO // can also be used. For PDO, run the package migrations first. 'storage' => [ 'enabled' => true, 'driver' => 'file', // redis, file, pdo, custom 'path' => storage_path('debugbar'), // For file driver 'connection' => null, // Leave null for default connection (Redis/PDO) 'provider' => '', // Instance of StorageInterface for custom driver ], // Vendor files are included by default, but can be set to false. // This can also be set to 'js' or 'css', to only include javascript or css vendor files. // Vendor files are for css: font-awesome (including fonts) and highlight.js (css files) // and for js: jquery and and highlight.js // So if you want syntax highlighting, set it to true. // jQuery is set to not conflict with existing jQuery scripts. 'include_vendors' => true, // The Debugbar can capture Ajax requests and display them. If you don't want this (ie. because of errors), // you can use this option to disable sending the data through the headers. // Optionally, you can also send ServerTiming headers on ajax requests for the Chrome DevTools. 'capture_ajax' => true, 'add_ajax_timing' => false, // When enabled, the Debugbar shows deprecated warnings for Symfony components // in the Messages tab. 'error_handler' => false, // The Debugbar can emulate the Clockwork headers, so you can use the Chrome // Extension, without the server-side code. It uses Debugbar collectors instead. 'clockwork' => false, // Enable/disable DataCollectors 'collectors' => [ 'phpinfo' => true, // Php version 'messages' => true, // Messages 'time' => true, // Time Datalogger 'memory' => true, // Memory usage 'exceptions' => true, // Exception displayer 'log' => true, // Logs from Monolog (merged in messages if enabled) 'db' => true, // Show database (PDO) queries and bindings 'views' => true, // Views with their data 'route' => true, // Current route information 'auth' => true, // Display Laravel authentication status 'gate' => true, // Display Laravel Gate checks 'session' => true, // Display session data 'symfony_request' => true, // Only one can be enabled.. 'mail' => true, // Catch mail messages 'laravel' => false, // Laravel version and environment 'events' => false, // All events fired 'default_request' => false, // Regular or special Symfony request logger 'logs' => false, // Add the latest log messages 'files' => false, // Show the included files 'config' => false, // Display config settings 'cache' => false, // Display cache events 'models' => true, // Display models ], // Configure some DataCollectors 'options' => [ 'auth' => [ 'show_name' => true, // Also show the users name/email in the debugbar ], 'db' => [ 'with_params' => true, // Render SQL with the parameters substituted 'backtrace' => true, // Use a backtrace to find the origin of the query in your files. 'timeline' => false, // Add the queries to the timeline 'explain' => [ // Show EXPLAIN output on queries 'enabled' => false, 'types' => ['SELECT'], // ['SELECT', 'INSERT', 'UPDATE', 'DELETE']; for MySQL 5.6.3+ ], 'hints' => true, // Show hints for common mistakes ], 'mail' => [ 'full_log' => false, ], 'views' => [ 'data' => false, //Note: Can slow down the application, because the data can be quite large.. ], 'route' => [ 'label' => true, // show complete route on bar ], 'logs' => [ 'file' => null, ], 'cache' => [ 'values' => true, // collect cache values ], ], // Inject Debugbar into the response // Usually, the debugbar is added just before </body>, by listening to the // Response after the App is done. If you disable this, you have to add them // in your template yourself. See http://phpdebugbar.com/docs/rendering.html 'inject' => true, // DebugBar route prefix // Sometimes you want to set route prefix to be used by DebugBar to load // its resources from. Usually the need comes from misconfigured web server or // from trying to overcome bugs like this: http://trac.nginx.org/nginx/ticket/97 'route_prefix' => '_debugbar', // DebugBar route domain // By default DebugBar route served from the same domain that request served. // To override default domain, specify it as a non-empty value. 'route_domain' => env('APP_URL', '') === 'http://bookstack.dev' ? '' : env('APP_URL', ''), ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/cache.php
app/Config/cache.php
<?php use Illuminate\Support\Str; /** * Caching configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ // MEMCACHED - Split out configuration into an array if (env('CACHE_DRIVER') === 'memcached') { $memcachedServerKeys = ['host', 'port', 'weight']; $memcachedServers = explode(',', trim(env('MEMCACHED_SERVERS', '127.0.0.1:11211:100'), ',')); foreach ($memcachedServers as $index => $memcachedServer) { $memcachedServerDetails = explode(':', $memcachedServer); if (count($memcachedServerDetails) < 2) { $memcachedServerDetails[] = '11211'; } if (count($memcachedServerDetails) < 3) { $memcachedServerDetails[] = '100'; } $memcachedServers[$index] = array_combine($memcachedServerKeys, $memcachedServerDetails); } } return [ // Default cache store to use // Can be overridden at cache call-time 'default' => env('CACHE_DRIVER', 'file'), // Available caches stores 'stores' => [ 'array' => [ 'driver' => 'array', 'serialize' => false, ], 'database' => [ 'driver' => 'database', 'table' => 'cache', 'connection' => null, 'lock_connection' => null, 'lock_table' => null, ], 'file' => [ 'driver' => 'file', 'path' => storage_path('framework/cache'), 'lock_path' => storage_path('framework/cache'), ], 'memcached' => [ 'driver' => 'memcached', 'options' => [ // Memcached::OPT_CONNECT_TIMEOUT => 2000, ], 'servers' => $memcachedServers ?? [], ], 'redis' => [ 'driver' => 'redis', 'connection' => 'default', 'lock_connection' => 'default', ], 'octane' => [ 'driver' => 'octane', ], ], /* |-------------------------------------------------------------------------- | Cache Key Prefix |-------------------------------------------------------------------------- | | When utilizing a RAM based store such as APC or Memcached, there might | be other applications utilizing the same cache. So, we'll specify a | value to get prefixed to all our keys so we can avoid collisions. | */ 'prefix' => env('CACHE_PREFIX', 'bookstack_cache_'), ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/hashing.php
app/Config/hashing.php
<?php /** * Hashing configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ return [ // Default Hash Driver // This option controls the default hash driver that will be used to hash // passwords for your application. By default, the bcrypt algorithm is used. // Supported: "bcrypt", "argon", "argon2id" 'driver' => 'bcrypt', // Bcrypt Options // Here you may specify the configuration options that should be used when // passwords are hashed using the Bcrypt algorithm. This will allow you // to control the amount of time it takes to hash the given password. 'bcrypt' => [ 'rounds' => env('BCRYPT_ROUNDS', 12), 'verify' => true, ], // Argon Options // Here you may specify the configuration options that should be used when // passwords are hashed using the Argon algorithm. These will allow you // to control the amount of time it takes to hash the given password. 'argon' => [ 'memory' => 1024, 'threads' => 2, 'time' => 2, ], ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/view.php
app/Config/view.php
<?php /** * View configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ // Join up possible view locations $viewPaths = [realpath(base_path('resources/views'))]; if ($theme = env('APP_THEME', false)) { array_unshift($viewPaths, base_path('themes/' . $theme)); } return [ // App theme // This option defines the theme to use for the application. When a theme // is set there must be a `themes/<theme_name>` folder to hold the // custom theme overrides. 'theme' => env('APP_THEME', false), // View Storage Paths // Most templating systems load templates from disk. Here you may specify // an array of paths that should be checked for your views. Of course // the usual Laravel view path has already been registered for you. 'paths' => $viewPaths, // Compiled View Path // This option determines where all the compiled Blade templates will be // stored for your application. Typically, this is within the storage // directory. However, as usual, you are free to change this value. 'compiled' => realpath(storage_path('framework/views')), ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/database.php
app/Config/database.php
<?php /** * Database configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ // REDIS // Split out configuration into an array if (env('REDIS_SERVERS', false)) { $redisDefaults = ['host' => '127.0.0.1', 'port' => '6379', 'database' => '0', 'password' => null]; $redisServers = explode(',', trim(env('REDIS_SERVERS', '127.0.0.1:6379:0'), ',')); $redisConfig = ['client' => 'predis']; $cluster = count($redisServers) > 1; if ($cluster) { $redisConfig['clusters'] = ['default' => []]; } foreach ($redisServers as $index => $redisServer) { $redisServerDetails = explode(':', $redisServer); $serverConfig = []; $configIndex = 0; foreach ($redisDefaults as $configKey => $configDefault) { $serverConfig[$configKey] = ($redisServerDetails[$configIndex] ?? $configDefault); $configIndex++; } if ($cluster) { $redisConfig['clusters']['default'][] = $serverConfig; } else { $redisConfig['default'] = $serverConfig; } } } // MYSQL // Split out port from host if set $mysqlHost = env('DB_HOST', 'localhost'); $mysqlHostExploded = explode(':', $mysqlHost); $mysqlPort = env('DB_PORT', 3306); $mysqlHostIpv6 = str_starts_with($mysqlHost, '['); if ($mysqlHostIpv6 && str_contains($mysqlHost, ']:')) { $mysqlHost = implode(':', array_slice($mysqlHostExploded, 0, -1)); $mysqlPort = intval(end($mysqlHostExploded)); } else if (!$mysqlHostIpv6 && count($mysqlHostExploded) > 1) { $mysqlHost = $mysqlHostExploded[0]; $mysqlPort = intval($mysqlHostExploded[1]); } return [ // Default database connection name. // Options: mysql, mysql_testing 'default' => env('DB_CONNECTION', 'mysql'), // Available database connections // Many of those shown here are unsupported by BookStack. 'connections' => [ 'mysql' => [ 'driver' => 'mysql', 'url' => env('DATABASE_URL'), 'host' => $mysqlHost, 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'port' => $mysqlPort, 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', // Prefixes are only semi-supported and may be unstable // since they are not tested as part of our automated test suite. // If used, the prefix should not be changed; otherwise you will likely receive errors. 'prefix' => env('DB_TABLE_PREFIX', ''), 'prefix_indexes' => true, 'strict' => false, 'engine' => null, 'options' => extension_loaded('pdo_mysql') ? array_filter([ // @phpstan-ignore class.notFound (PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'), ]) : [], ], 'mysql_testing' => [ 'driver' => 'mysql', 'url' => env('TEST_DATABASE_URL'), 'host' => '127.0.0.1', 'database' => 'bookstack-test', 'username' => env('MYSQL_USER', 'bookstack-test'), 'password' => env('MYSQL_PASSWORD', 'bookstack-test'), 'port' => $mysqlPort, 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'prefix_indexes' => true, 'strict' => false, ], ], // Migration Repository Table // This table keeps track of all the migrations that have already run for the application. 'migrations' => 'migrations', // Redis configuration to use if set 'redis' => $redisConfig ?? [], ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/services.php
app/Config/services.php
<?php /** * Third party service configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ return [ // Single option to disable non-auth external services such as Gravatar and Draw.io 'disable_services' => env('DISABLE_EXTERNAL_SERVICES', false), // Draw.io integration active 'drawio' => env('DRAWIO', !env('DISABLE_EXTERNAL_SERVICES', false)), // URL for fetching avatars 'avatar_url' => env('AVATAR_URL', ''), // Callback URL for social authentication methods 'callback_url' => env('APP_URL', false), 'github' => [ 'client_id' => env('GITHUB_APP_ID', false), 'client_secret' => env('GITHUB_APP_SECRET', false), 'redirect' => env('APP_URL') . '/login/service/github/callback', 'name' => 'GitHub', 'auto_register' => env('GITHUB_AUTO_REGISTER', false), 'auto_confirm' => env('GITHUB_AUTO_CONFIRM_EMAIL', false), ], 'google' => [ 'client_id' => env('GOOGLE_APP_ID', false), 'client_secret' => env('GOOGLE_APP_SECRET', false), 'redirect' => env('APP_URL') . '/login/service/google/callback', 'name' => 'Google', 'auto_register' => env('GOOGLE_AUTO_REGISTER', false), 'auto_confirm' => env('GOOGLE_AUTO_CONFIRM_EMAIL', false), 'select_account' => env('GOOGLE_SELECT_ACCOUNT', false), ], 'slack' => [ 'client_id' => env('SLACK_APP_ID', false), 'client_secret' => env('SLACK_APP_SECRET', false), 'redirect' => env('APP_URL') . '/login/service/slack/callback', 'name' => 'Slack', 'auto_register' => env('SLACK_AUTO_REGISTER', false), 'auto_confirm' => env('SLACK_AUTO_CONFIRM_EMAIL', false), ], 'facebook' => [ 'client_id' => env('FACEBOOK_APP_ID', false), 'client_secret' => env('FACEBOOK_APP_SECRET', false), 'redirect' => env('APP_URL') . '/login/service/facebook/callback', 'name' => 'Facebook', 'auto_register' => env('FACEBOOK_AUTO_REGISTER', false), 'auto_confirm' => env('FACEBOOK_AUTO_CONFIRM_EMAIL', false), ], 'twitter' => [ 'client_id' => env('TWITTER_APP_ID', false), 'client_secret' => env('TWITTER_APP_SECRET', false), 'redirect' => env('APP_URL') . '/login/service/twitter/callback', 'name' => 'Twitter', 'auto_register' => env('TWITTER_AUTO_REGISTER', false), 'auto_confirm' => env('TWITTER_AUTO_CONFIRM_EMAIL', false), ], 'azure' => [ 'client_id' => env('AZURE_APP_ID', false), 'client_secret' => env('AZURE_APP_SECRET', false), 'tenant' => env('AZURE_TENANT', false), 'redirect' => env('APP_URL') . '/login/service/azure/callback', 'name' => 'Microsoft Azure', 'auto_register' => env('AZURE_AUTO_REGISTER', false), 'auto_confirm' => env('AZURE_AUTO_CONFIRM_EMAIL', false), ], 'okta' => [ 'client_id' => env('OKTA_APP_ID'), 'client_secret' => env('OKTA_APP_SECRET'), 'redirect' => env('APP_URL') . '/login/service/okta/callback', 'base_url' => env('OKTA_BASE_URL'), 'name' => 'Okta', 'auto_register' => env('OKTA_AUTO_REGISTER', false), 'auto_confirm' => env('OKTA_AUTO_CONFIRM_EMAIL', false), ], 'gitlab' => [ 'client_id' => env('GITLAB_APP_ID'), 'client_secret' => env('GITLAB_APP_SECRET'), 'redirect' => env('APP_URL') . '/login/service/gitlab/callback', 'instance_uri' => env('GITLAB_BASE_URI'), // Needed only for self hosted instances 'name' => 'GitLab', 'auto_register' => env('GITLAB_AUTO_REGISTER', false), 'auto_confirm' => env('GITLAB_AUTO_CONFIRM_EMAIL', false), ], 'twitch' => [ 'client_id' => env('TWITCH_APP_ID'), 'client_secret' => env('TWITCH_APP_SECRET'), 'redirect' => env('APP_URL') . '/login/service/twitch/callback', 'name' => 'Twitch', 'auto_register' => env('TWITCH_AUTO_REGISTER', false), 'auto_confirm' => env('TWITCH_AUTO_CONFIRM_EMAIL', false), ], 'discord' => [ 'client_id' => env('DISCORD_APP_ID'), 'client_secret' => env('DISCORD_APP_SECRET'), 'redirect' => env('APP_URL') . '/login/service/discord/callback', 'name' => 'Discord', 'auto_register' => env('DISCORD_AUTO_REGISTER', false), 'auto_confirm' => env('DISCORD_AUTO_CONFIRM_EMAIL', false), ], 'ldap' => [ 'server' => env('LDAP_SERVER', false), 'dump_user_details' => env('LDAP_DUMP_USER_DETAILS', false), 'dump_user_groups' => env('LDAP_DUMP_USER_GROUPS', false), 'dn' => env('LDAP_DN', false), 'pass' => env('LDAP_PASS', false), 'base_dn' => env('LDAP_BASE_DN', false), 'user_filter' => env('LDAP_USER_FILTER', '(&(uid={user}))'), 'version' => env('LDAP_VERSION', false), 'id_attribute' => env('LDAP_ID_ATTRIBUTE', 'uid'), 'email_attribute' => env('LDAP_EMAIL_ATTRIBUTE', 'mail'), 'display_name_attribute' => env('LDAP_DISPLAY_NAME_ATTRIBUTE', 'cn'), 'follow_referrals' => env('LDAP_FOLLOW_REFERRALS', false), 'user_to_groups' => env('LDAP_USER_TO_GROUPS', false), 'group_attribute' => env('LDAP_GROUP_ATTRIBUTE', 'memberOf'), 'remove_from_groups' => env('LDAP_REMOVE_FROM_GROUPS', false), 'tls_insecure' => env('LDAP_TLS_INSECURE', false), 'tls_ca_cert' => env('LDAP_TLS_CA_CERT', false), 'start_tls' => env('LDAP_START_TLS', false), 'thumbnail_attribute' => env('LDAP_THUMBNAIL_ATTRIBUTE', null), ], ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/filesystems.php
app/Config/filesystems.php
<?php /** * Filesystem configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ return [ // Default Filesystem Disk // Options: local, local_secure, local_secure_restricted, s3 'default' => env('STORAGE_TYPE', 'local'), // Filesystem to use specifically for image uploads. 'images' => env('STORAGE_IMAGE_TYPE', env('STORAGE_TYPE', 'local')), // Filesystem to use specifically for file attachments. 'attachments' => env('STORAGE_ATTACHMENT_TYPE', env('STORAGE_TYPE', 'local')), // Storage URL // This is the url to where the storage is located for when using an external // file storage service, such as s3, to store publicly accessible assets. 'url' => env('STORAGE_URL', false), // Available filesystem disks // Only local, local_secure & s3 are supported by BookStack 'disks' => [ 'local' => [ 'driver' => 'local', 'root' => public_path(), 'serve' => false, 'throw' => true, 'directory_visibility' => 'public', ], 'local_secure_attachments' => [ 'driver' => 'local', 'root' => storage_path('uploads/files/'), 'serve' => false, 'throw' => true, ], 'local_secure_images' => [ 'driver' => 'local', 'root' => storage_path('uploads/images/'), 'serve' => false, 'throw' => true, ], 's3' => [ 'driver' => 's3', 'key' => env('STORAGE_S3_KEY', 'your-key'), 'secret' => env('STORAGE_S3_SECRET', 'your-secret'), 'region' => env('STORAGE_S3_REGION', 'your-region'), 'bucket' => env('STORAGE_S3_BUCKET', 'your-bucket'), 'endpoint' => env('STORAGE_S3_ENDPOINT', null), 'use_path_style_endpoint' => env('STORAGE_S3_ENDPOINT', null) !== null, 'throw' => true, 'stream_reads' => false, ], ], // Symbolic Links // Here you may configure the symbolic links that will be created when the // `storage:link` Artisan command is executed. The array keys should be // the locations of the links and the values should be their targets. 'links' => [ public_path('storage') => storage_path('app/public'), ], ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/saml2.php
app/Config/saml2.php
<?php $SAML2_IDP_AUTHNCONTEXT = env('SAML2_IDP_AUTHNCONTEXT', true); $SAML2_SP_x509 = env('SAML2_SP_x509', false); return [ // Display name, shown to users, for SAML2 option 'name' => env('SAML2_NAME', 'SSO'), // Dump user details after a login request for debugging purposes 'dump_user_details' => env('SAML2_DUMP_USER_DETAILS', false), // Attribute, within a SAML response, to find the user's email address 'email_attribute' => env('SAML2_EMAIL_ATTRIBUTE', 'email'), // Attribute, within a SAML response, to find the user's display name 'display_name_attributes' => explode('|', env('SAML2_DISPLAY_NAME_ATTRIBUTES', 'username')), // Attribute, within a SAML response, to use to connect a BookStack user to the SAML user. 'external_id_attribute' => env('SAML2_EXTERNAL_ID_ATTRIBUTE', null), // Group sync options // Enable syncing, upon login, of SAML2 groups to BookStack groups 'user_to_groups' => env('SAML2_USER_TO_GROUPS', false), // Attribute, within a SAML response, to find group names on 'group_attribute' => env('SAML2_GROUP_ATTRIBUTE', 'group'), // When syncing groups, remove any groups that no longer match. Otherwise sync only adds new groups. 'remove_from_groups' => env('SAML2_REMOVE_FROM_GROUPS', false), // Autoload IDP details from the metadata endpoint 'autoload_from_metadata' => env('SAML2_AUTOLOAD_METADATA', false), // Overrides, in JSON format, to the configuration passed to underlying onelogin library. 'onelogin_overrides' => env('SAML2_ONELOGIN_OVERRIDES', null), 'onelogin' => [ // If 'strict' is True, then the PHP Toolkit will reject unsigned // or unencrypted messages if it expects them signed or encrypted // Also will reject the messages if not strictly follow the SAML // standard: Destination, NameId, Conditions ... are validated too. 'strict' => true, // Enable debug mode (to print errors) 'debug' => env('APP_DEBUG', false), // Set a BaseURL to be used instead of try to guess // the BaseURL of the view that process the SAML Message. // Ex. http://sp.example.com/ // http://example.com/sp/ 'baseurl' => null, // Service Provider Data that we are deploying 'sp' => [ // Identifier of the SP entity (must be a URI) 'entityId' => '', // Specifies info about where and how the <AuthnResponse> message MUST be // returned to the requester, in this case our SP. 'assertionConsumerService' => [ // URL Location where the <Response> from the IdP will be returned 'url' => '', // SAML protocol binding to be used when returning the <Response> // message. Onelogin Toolkit supports for this endpoint the // HTTP-POST binding only 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST', ], // Specifies info about where and how the <Logout Response> message MUST be // returned to the requester, in this case our SP. 'singleLogoutService' => [ // URL Location where the <Response> from the IdP will be returned 'url' => '', // SAML protocol binding to be used when returning the <Response> // message. Onelogin Toolkit supports for this endpoint the // HTTP-Redirect binding only 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect', ], // Specifies constraints on the name identifier to be used to // represent the requested subject. // Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported 'NameIDFormat' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress', // Usually x509cert and privateKey of the SP are provided by files placed at // the certs folder. But we can also provide them with the following parameters 'x509cert' => $SAML2_SP_x509 ?: '', 'privateKey' => env('SAML2_SP_x509_KEY', ''), ], // Identity Provider Data that we want connect with our SP 'idp' => [ // Identifier of the IdP entity (must be a URI) 'entityId' => env('SAML2_IDP_ENTITYID', null), // SSO endpoint info of the IdP. (Authentication Request protocol) 'singleSignOnService' => [ // URL Target of the IdP where the SP will send the Authentication Request Message 'url' => env('SAML2_IDP_SSO', null), // SAML protocol binding to be used when returning the <Response> // message. Onelogin Toolkit supports for this endpoint the // HTTP-Redirect binding only 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect', ], // SLO endpoint info of the IdP. 'singleLogoutService' => [ // URL Location of the IdP where the SP will send the SLO Request 'url' => env('SAML2_IDP_SLO', null), // URL location of the IdP where the SP will send the SLO Response (ResponseLocation) // if not set, url for the SLO Request will be used 'responseUrl' => null, // SAML protocol binding to be used when returning the <Response> // message. Onelogin Toolkit supports for this endpoint the // HTTP-Redirect binding only 'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect', ], // Public x509 certificate of the IdP 'x509cert' => env('SAML2_IDP_x509', null), /* * Instead of use the whole x509cert you can use a fingerprint in * order to validate the SAMLResponse, but we don't recommend to use * that method on production since is exploitable by a collision * attack. * (openssl x509 -noout -fingerprint -in "idp.crt" to generate it, * or add for example the -sha256 , -sha384 or -sha512 parameter) * * If a fingerprint is provided, then the certFingerprintAlgorithm is required in order to * let the toolkit know which Algorithm was used. Possible values: sha1, sha256, sha384 or sha512 * 'sha1' is the default value. */ // 'certFingerprint' => '', // 'certFingerprintAlgorithm' => 'sha1', /* In some scenarios the IdP uses different certificates for * signing/encryption, or is under key rollover phase and more * than one certificate is published on IdP metadata. * In order to handle that the toolkit offers that parameter. * (when used, 'x509cert' and 'certFingerprint' values are * ignored). */ // 'x509certMulti' => array( // 'signing' => array( // 0 => '<cert1-string>', // ), // 'encryption' => array( // 0 => '<cert2-string>', // ) // ), ], 'security' => [ // SAML2 Authn context // When set to false no AuthContext will be sent in the AuthNRequest, // When set to true (Default) you will get an AuthContext 'exact' 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport'. // Multiple forced values can be passed via a space separated array, For example: // SAML2_IDP_AUTHNCONTEXT="urn:federation:authentication:windows urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport" 'requestedAuthnContext' => is_string($SAML2_IDP_AUTHNCONTEXT) ? explode(' ', $SAML2_IDP_AUTHNCONTEXT) : $SAML2_IDP_AUTHNCONTEXT, // Sign requests and responses if a certificate is in use 'logoutRequestSigned' => (bool) $SAML2_SP_x509, 'logoutResponseSigned' => (bool) $SAML2_SP_x509, 'authnRequestsSigned' => (bool) $SAML2_SP_x509, 'lowercaseUrlencoding' => false, ], ], ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/mail.php
app/Config/mail.php
<?php /** * Mail configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ // Configured mail encryption method. // STARTTLS should still be attempted, but tls/ssl forces TLS usage. $mailEncryption = env('MAIL_ENCRYPTION', null); $mailPort = intval(env('MAIL_PORT', 587)); return [ // Mail driver to use. // From Laravel 7+ this is MAIL_MAILER in laravel. // Kept as MAIL_DRIVER in BookStack to prevent breaking change. // Options: smtp, sendmail, log, array 'default' => env('MAIL_DRIVER', 'smtp'), // Global "From" address & name 'from' => [ 'address' => env('MAIL_FROM', 'bookstack@example.com'), 'name' => env('MAIL_FROM_NAME', 'BookStack'), ], // Mailer Configurations // Available mailing methods and their settings. 'mailers' => [ 'smtp' => [ 'transport' => 'smtp', 'scheme' => null, 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), 'port' => $mailPort, 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), 'verify_peer' => env('MAIL_VERIFY_SSL', true), 'timeout' => null, 'local_domain' => null, 'require_tls' => ($mailEncryption === 'tls' || $mailEncryption === 'ssl' || $mailPort === 465), ], 'sendmail' => [ 'transport' => 'sendmail', 'path' => env('MAIL_SENDMAIL_COMMAND', '/usr/sbin/sendmail -bs'), ], 'log' => [ 'transport' => 'log', 'channel' => env('MAIL_LOG_CHANNEL'), ], 'array' => [ 'transport' => 'array', ], 'failover' => [ 'transport' => 'failover', 'mailers' => [ 'smtp', 'log', ], ], ], ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/api.php
app/Config/api.php
<?php /** * API configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ return [ // The default number of items that are returned in listing API requests. // This count can often be overridden, up the the max option, per-request via request options. 'default_item_count' => env('API_DEFAULT_ITEM_COUNT', 100), // The maximum number of items that can be returned in a listing API request. 'max_item_count' => env('API_MAX_ITEM_COUNT', 500), // The number of API requests that can be made per minute by a single user. 'requests_per_minute' => env('API_REQUESTS_PER_MIN', 180), ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/oidc.php
app/Config/oidc.php
<?php return [ // Display name, shown to users, for OpenId option 'name' => env('OIDC_NAME', 'SSO'), // Dump user details after a login request for debugging purposes 'dump_user_details' => env('OIDC_DUMP_USER_DETAILS', false), // Claim, within an OpenId token, to find the user's display name 'display_name_claims' => env('OIDC_DISPLAY_NAME_CLAIMS', 'name'), // Claim, within an OpenID token, to use to connect a BookStack user to the OIDC user. 'external_id_claim' => env('OIDC_EXTERNAL_ID_CLAIM', 'sub'), // OAuth2/OpenId client id, as configured in your Authorization server. 'client_id' => env('OIDC_CLIENT_ID', null), // OAuth2/OpenId client secret, as configured in your Authorization server. 'client_secret' => env('OIDC_CLIENT_SECRET', null), // The issuer of the identity token (id_token) this will be compared with // what is returned in the token. 'issuer' => env('OIDC_ISSUER', null), // Auto-discover the relevant endpoints and keys from the issuer. // Fetched details are cached for 15 minutes. 'discover' => env('OIDC_ISSUER_DISCOVER', false), // Public key that's used to verify the JWT token with. // Can be the key value itself or a local 'file://public.key' reference. 'jwt_public_key' => env('OIDC_PUBLIC_KEY', null), // OAuth2 endpoints. 'authorization_endpoint' => env('OIDC_AUTH_ENDPOINT', null), 'token_endpoint' => env('OIDC_TOKEN_ENDPOINT', null), 'userinfo_endpoint' => env('OIDC_USERINFO_ENDPOINT', null), // OIDC RP-Initiated Logout endpoint URL. // A false value force-disables RP-Initiated Logout. // A true value gets the URL from discovery, if active. // A string value is used as the URL. 'end_session_endpoint' => env('OIDC_END_SESSION_ENDPOINT', false), // Add extra scopes, upon those required, to the OIDC authentication request // Multiple values can be provided comma seperated. 'additional_scopes' => env('OIDC_ADDITIONAL_SCOPES', null), // Enable fetching of the user's avatar from the 'picture' claim on login. // Will only be fetched if the user doesn't already have an avatar image assigned. // This can be a security risk due to performing server-side fetching (with up to 3 redirects) of // data from external URLs. Only enable if you trust the OIDC auth provider to provide safe URLs for user images. 'fetch_avatar' => env('OIDC_FETCH_AVATAR', false), // Group sync options // Enable syncing, upon login, of OIDC groups to BookStack roles 'user_to_groups' => env('OIDC_USER_TO_GROUPS', false), // Attribute, within a OIDC ID token, to find group names within 'groups_claim' => env('OIDC_GROUPS_CLAIM', 'groups'), // When syncing groups, remove any groups that no longer match. Otherwise, sync only adds new groups. 'remove_from_groups' => env('OIDC_REMOVE_FROM_GROUPS', false), ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Config/auth.php
app/Config/auth.php
<?php /** * Authentication configuration options. * * Changes to these config files are not supported by BookStack and may break upon updates. * Configuration should be altered via the `.env` file or environment variables. * Do not edit this file unless you're happy to maintain any changes yourself. */ return [ // Options: standard, ldap, saml2, oidc 'method' => env('AUTH_METHOD', 'standard'), // Automatically initiate login via external auth system if it's the sole auth method. // Works with saml2 or oidc auth methods. 'auto_initiate' => env('AUTH_AUTO_INITIATE', false), // Authentication Defaults // This option controls the default authentication "guard" and password // reset options for your application. 'defaults' => [ 'guard' => env('AUTH_METHOD', 'standard'), 'passwords' => 'users', ], // Authentication Guards // All authentication drivers have a user provider. This defines how the // users are actually retrieved out of your database or other storage // mechanisms used by this application to persist your user's data. // Supported drivers: "session", "api-token", "ldap-session", "async-external-session" 'guards' => [ 'standard' => [ 'driver' => 'session', 'provider' => 'users', ], 'ldap' => [ 'driver' => 'ldap-session', 'provider' => 'external', ], 'saml2' => [ 'driver' => 'async-external-session', 'provider' => 'external', ], 'oidc' => [ 'driver' => 'async-external-session', 'provider' => 'external', ], 'api' => [ 'driver' => 'api-token', ], ], // User Providers // All authentication drivers have a user provider. This defines how the // users are actually retrieved out of your database or other storage // mechanisms used by this application to persist your user's data. 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => \BookStack\Users\Models\User::class, ], 'external' => [ 'driver' => 'external-users', 'model' => \BookStack\Users\Models\User::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ], // Resetting Passwords // The expire time is the number of minutes that the reset token should be // considered valid. This security feature keeps tokens short-lived so // they have less time to be guessed. You may change this as needed. 'passwords' => [ 'users' => [ 'provider' => 'users', 'email' => 'emails.password', 'table' => 'password_resets', 'expire' => 60, 'throttle' => 60, ], ], // Password Confirmation Timeout // Here you may define the amount of seconds before a password confirmation // times out and the user is prompted to re-enter their password via the // confirmation screen. By default, the timeout lasts for three hours. 'password_timeout' => 10800, ];
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Api/ApiEntityListFormatter.php
app/Api/ApiEntityListFormatter.php
<?php namespace BookStack\Api; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; class ApiEntityListFormatter { /** * The list to be formatted. * @var Entity[] */ protected array $list = []; /** * The fields to show in the formatted data. * Can be a plain string array item for a direct model field (If existing on model). * If the key is a string, with a callable value, the return value of the callable * will be used for the resultant value. A null return value will omit the property. * @var array<string|int, string|callable> */ protected array $fields = [ 'id', 'name', 'slug', 'book_id', 'chapter_id', 'draft', 'template', 'priority', 'created_at', 'updated_at', ]; public function __construct(array $list) { $this->list = $list; // Default dynamic fields $this->withField('url', fn(Entity $entity) => $entity->getUrl()); } /** * Add a field to be used in the formatter, with the property using the given * name and value being the return type of the given callback. */ public function withField(string $property, callable $callback): self { $this->fields[$property] = $callback; return $this; } /** * Show the 'type' property in the response reflecting the entity type. * EG: page, chapter, bookshelf, book * To be included in results with non-pre-determined types. */ public function withType(): self { $this->withField('type', fn(Entity $entity) => $entity->getType()); return $this; } /** * Include tags in the formatted data. */ public function withTags(): self { $this->withField('tags', fn(Entity $entity) => $entity->tags); return $this; } /** * Include parent book/chapter info in the formatted data. */ public function withParents(): self { $this->withField('book', function (Entity $entity) { if ($entity instanceof BookChild && $entity->book) { return $entity->book->only(['id', 'name', 'slug']); } return null; }); $this->withField('chapter', function (Entity $entity) { if ($entity instanceof Page && $entity->chapter) { return $entity->chapter->only(['id', 'name', 'slug']); } return null; }); return $this; } /** * Format the data and return an array of formatted content. * @return array[] */ public function format(): array { $results = []; foreach ($this->list as $item) { $results[] = $this->formatSingle($item); } return $results; } /** * Format a single entity item to a plain array. */ protected function formatSingle(Entity $entity): array { $result = []; $values = (clone $entity)->toArray(); foreach ($this->fields as $field => $callback) { if (is_string($callback)) { $field = $callback; if (!isset($values[$field])) { continue; } $value = $values[$field]; } else { $value = $callback($entity); if (is_null($value)) { continue; } } $result[$field] = $value; } return $result; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Api/ApiDocsGenerator.php
app/Api/ApiDocsGenerator.php
<?php namespace BookStack\Api; use BookStack\App\AppVersion; use BookStack\Http\ApiController; use Exception; use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Route; use Illuminate\Support\Str; use Illuminate\Validation\Rules\Password; use ReflectionClass; use ReflectionException; use ReflectionMethod; class ApiDocsGenerator { protected array $reflectionClasses = []; protected array $controllerClasses = []; /** * Load the docs form the cache if existing * otherwise generate and store in the cache. */ public static function generateConsideringCache(): Collection { $appVersion = AppVersion::get(); $cacheKey = 'api-docs::' . $appVersion; $isProduction = config('app.env') === 'production'; $cacheVal = $isProduction ? Cache::get($cacheKey) : null; if (!is_null($cacheVal)) { return $cacheVal; } $docs = (new ApiDocsGenerator())->generate(); Cache::put($cacheKey, $docs, 60 * 24); return $docs; } /** * Generate API documentation. */ protected function generate(): Collection { $apiRoutes = $this->getFlatApiRoutes(); $apiRoutes = $this->loadDetailsFromControllers($apiRoutes); $apiRoutes = $this->loadDetailsFromFiles($apiRoutes); $apiRoutes = $apiRoutes->groupBy('base_model'); return $apiRoutes; } /** * Load any API details stored in static files. */ protected function loadDetailsFromFiles(Collection $routes): Collection { return $routes->map(function (array $route) { $exampleTypes = ['request', 'response']; $fileTypes = ['json', 'http']; foreach ($exampleTypes as $exampleType) { foreach ($fileTypes as $fileType) { $exampleFile = base_path("dev/api/{$exampleType}s/{$route['name']}." . $fileType); if (file_exists($exampleFile)) { $route["example_{$exampleType}"] = file_get_contents($exampleFile); continue 2; } } $route["example_{$exampleType}"] = null; } return $route; }); } /** * Load any details we can fetch from the controller and its methods. */ protected function loadDetailsFromControllers(Collection $routes): Collection { return $routes->map(function (array $route) { $class = $this->getReflectionClass($route['controller']); $method = $this->getReflectionMethod($route['controller'], $route['controller_method']); $comment = $method->getDocComment(); $route['description'] = $comment ? $this->parseDescriptionFromDocBlockComment($comment) : null; $route['body_params'] = $this->getBodyParamsFromClass($route['controller'], $route['controller_method']); // Load class description for the model // Not ideal to have it here on each route, but adding it in a more structured manner would break // docs resulting JSON format and therefore be an API break. // Save refactoring for a more significant set of changes. $classComment = $class->getDocComment(); $route['model_description'] = $classComment ? $this->parseDescriptionFromDocBlockComment($classComment) : null; return $route; }); } /** * Load body params and their rules by inspecting the given class and method name. * * @throws BindingResolutionException */ protected function getBodyParamsFromClass(string $className, string $methodName): ?array { /** @var ApiController $class */ $class = $this->controllerClasses[$className] ?? null; if ($class === null) { $class = app()->make($className); $this->controllerClasses[$className] = $class; } $rules = collect($class->getValidationRules()[$methodName] ?? [])->map(function ($validations) { return array_map(function ($validation) { return $this->getValidationAsString($validation); }, $validations); })->toArray(); return empty($rules) ? null : $rules; } /** * Convert the given validation message to a readable string. */ protected function getValidationAsString($validation): string { if (is_string($validation)) { return $validation; } if (is_object($validation) && method_exists($validation, '__toString')) { return strval($validation); } if ($validation instanceof Password) { return 'min:8'; } $class = get_class($validation); throw new Exception("Cannot provide string representation of rule for class: {$class}"); } /** * Parse out the description text from a class method comment. */ protected function parseDescriptionFromDocBlockComment(string $comment): string { $matches = []; preg_match_all('/^\s*?\*\s?($|((?![\/@\s]).*?))$/m', $comment, $matches); $text = implode(' ', $matches[1] ?? []); return str_replace(' ', "\n", $text); } /** * Get a reflection method from the given class name and method name. * * @throws ReflectionException */ protected function getReflectionMethod(string $className, string $methodName): ReflectionMethod { return $this->getReflectionClass($className)->getMethod($methodName); } /** * Get a reflection class from the given class name. * * @throws ReflectionException */ protected function getReflectionClass(string $className): ReflectionClass { $class = $this->reflectionClasses[$className] ?? null; if ($class === null) { $class = new ReflectionClass($className); $this->reflectionClasses[$className] = $class; } return $class; } /** * Get the system API routes, formatted into a flat collection. */ protected function getFlatApiRoutes(): Collection { return collect(Route::getRoutes()->getRoutes())->filter(function ($route) { return strpos($route->uri, 'api/') === 0; })->map(function ($route) { [$controller, $controllerMethod] = explode('@', $route->action['uses']); $baseModelName = explode('.', explode('/', $route->uri)[1])[0]; $shortName = $baseModelName . '-' . $controllerMethod; return [ 'name' => $shortName, 'uri' => $route->uri, 'method' => $route->methods[0], 'controller' => $controller, 'controller_method' => $controllerMethod, 'controller_method_kebab' => Str::kebab($controllerMethod), 'base_model' => $baseModelName, ]; }); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Api/ApiToken.php
app/Api/ApiToken.php
<?php namespace BookStack\Api; use BookStack\Activity\Models\Loggable; use BookStack\Users\Models\User; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Support\Carbon; /** * Class ApiToken. * * @property int $id * @property string $token_id * @property string $secret * @property string $name * @property Carbon $expires_at * @property User $user */ class ApiToken extends Model implements Loggable { use HasFactory; protected $fillable = ['name', 'expires_at']; protected $casts = [ 'expires_at' => 'date:Y-m-d', ]; /** * Get the user that this token belongs to. */ public function user(): BelongsTo { return $this->belongsTo(User::class); } /** * Get the default expiry value for an API token. * Set to 100 years from now. */ public static function defaultExpiry(): string { return Carbon::now()->addYears(100)->format('Y-m-d'); } /** * {@inheritdoc} */ public function logDescriptor(): string { return "({$this->id}) {$this->name}; User: {$this->user->logDescriptor()}"; } /** * Get the URL for managing this token. */ public function getUrl(string $path = ''): string { return url("/api-tokens/{$this->user_id}/{$this->id}/" . trim($path, '/')); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Api/ListingResponseBuilder.php
app/Api/ListingResponseBuilder.php
<?php namespace BookStack\Api; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; class ListingResponseBuilder { protected Builder $query; protected Request $request; /** * @var string[] */ protected array $fields; /** * @var array<callable> */ protected array $resultModifiers = []; /** * @var array<string, string> */ protected array $filterOperators = [ 'eq' => '=', 'ne' => '!=', 'gt' => '>', 'lt' => '<', 'gte' => '>=', 'lte' => '<=', 'like' => 'like', ]; /** * ListingResponseBuilder constructor. * The given fields will be forced visible within the model results. */ public function __construct(Builder $query, Request $request, array $fields) { $this->query = $query; $this->request = $request; $this->fields = $fields; } /** * Get the response from this builder. */ public function toResponse(): JsonResponse { $filteredQuery = $this->filterQuery($this->query); $total = $filteredQuery->count(); $data = $this->fetchData($filteredQuery)->each(function ($model) { foreach ($this->resultModifiers as $modifier) { $modifier($model); } }); return response()->json([ 'data' => $data, 'total' => $total, ]); } /** * Add a callback to modify each element of the results. * * @param (callable(Model): void) $modifier */ public function modifyResults(callable $modifier): void { $this->resultModifiers[] = $modifier; } /** * Fetch the data to return within the response. */ protected function fetchData(Builder $query): Collection { $query = $this->countAndOffsetQuery($query); $query = $this->sortQuery($query); return $query->get($this->fields); } /** * Apply any filtering operations found in the request. */ protected function filterQuery(Builder $query): Builder { $query = clone $query; $requestFilters = $this->request->get('filter', []); if (!is_array($requestFilters)) { return $query; } $queryFilters = collect($requestFilters)->map(function ($value, $key) { return $this->requestFilterToQueryFilter($key, $value); })->filter(function ($value) { return !is_null($value); })->values()->toArray(); return $query->where($queryFilters); } /** * Convert a request filter query key/value pair into a [field, op, value] where condition. */ protected function requestFilterToQueryFilter($fieldKey, $value): ?array { $splitKey = explode(':', $fieldKey); $field = $splitKey[0]; $filterOperator = $splitKey[1] ?? 'eq'; if (!in_array($field, $this->fields)) { return null; } if (!in_array($filterOperator, array_keys($this->filterOperators))) { $filterOperator = 'eq'; } $queryOperator = $this->filterOperators[$filterOperator]; return [$field, $queryOperator, $value]; } /** * Apply sorting operations to the query from given parameters * otherwise falling back to the first given field, ascending. */ protected function sortQuery(Builder $query): Builder { $query = clone $query; $defaultSortName = $this->fields[0]; $direction = 'asc'; $sort = $this->request->get('sort', ''); if (strpos($sort, '-') === 0) { $direction = 'desc'; } $sortName = ltrim($sort, '+- '); if (!in_array($sortName, $this->fields)) { $sortName = $defaultSortName; } return $query->orderBy($sortName, $direction); } /** * Apply count and offset for paging, based on params from the request while falling * back to system defined default, taking the max limit into account. */ protected function countAndOffsetQuery(Builder $query): Builder { $query = clone $query; $offset = max(0, $this->request->get('offset', 0)); $maxCount = config('api.max_item_count'); $count = $this->request->get('count', config('api.default_item_count')); $count = max(min($maxCount, $count), 1); return $query->skip($offset)->take($count); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Api/ApiDocsController.php
app/Api/ApiDocsController.php
<?php namespace BookStack\Api; use BookStack\Http\ApiController; class ApiDocsController extends ApiController { /** * Load the docs page for the API. */ public function display() { $docs = ApiDocsGenerator::generateConsideringCache(); $this->setPageTitle(trans('settings.users_api_tokens_docs')); return view('api-docs.index', [ 'docs' => $docs, ]); } /** * Show a JSON view of the API docs data. */ public function json() { $docs = ApiDocsGenerator::generateConsideringCache(); return response()->json($docs); } /** * Redirect to the API docs page. * Required as a controller method, instead of the Route::redirect helper, * to ensure the URL is generated correctly. */ public function redirect() { return redirect('/api/docs'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Api/UserApiTokenController.php
app/Api/UserApiTokenController.php
<?php namespace BookStack\Api; use BookStack\Activity\ActivityType; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use BookStack\Users\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; class UserApiTokenController extends Controller { /** * Show the form to create a new API token. */ public function create(Request $request, int $userId) { $this->checkPermission(Permission::AccessApi); $this->checkPermissionOrCurrentUser(Permission::UsersManage, $userId); $this->updateContext($request); $user = User::query()->findOrFail($userId); $this->setPageTitle(trans('settings.user_api_token_create')); return view('users.api-tokens.create', [ 'user' => $user, 'back' => $this->getRedirectPath($user), ]); } /** * Store a new API token in the system. */ public function store(Request $request, int $userId) { $this->checkPermission(Permission::AccessApi); $this->checkPermissionOrCurrentUser(Permission::UsersManage, $userId); $this->validate($request, [ 'name' => ['required', 'max:250'], 'expires_at' => ['date_format:Y-m-d'], ]); $user = User::query()->findOrFail($userId); $secret = Str::random(32); $token = (new ApiToken())->forceFill([ 'name' => $request->get('name'), 'token_id' => Str::random(32), 'secret' => Hash::make($secret), 'user_id' => $user->id, 'expires_at' => $request->get('expires_at') ?: ApiToken::defaultExpiry(), ]); while (ApiToken::query()->where('token_id', '=', $token->token_id)->exists()) { $token->token_id = Str::random(32); } $token->save(); session()->flash('api-token-secret:' . $token->id, $secret); $this->logActivity(ActivityType::API_TOKEN_CREATE, $token); return redirect($token->getUrl()); } /** * Show the details for a user API token, with access to edit. */ public function edit(Request $request, int $userId, int $tokenId) { $this->updateContext($request); [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId); $secret = session()->pull('api-token-secret:' . $token->id, null); $this->setPageTitle(trans('settings.user_api_token')); return view('users.api-tokens.edit', [ 'user' => $user, 'token' => $token, 'model' => $token, 'secret' => $secret, 'back' => $this->getRedirectPath($user), ]); } /** * Update the API token. */ public function update(Request $request, int $userId, int $tokenId) { $this->validate($request, [ 'name' => ['required', 'max:250'], 'expires_at' => ['date_format:Y-m-d'], ]); [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId); $token->fill([ 'name' => $request->get('name'), 'expires_at' => $request->get('expires_at') ?: ApiToken::defaultExpiry(), ])->save(); $this->logActivity(ActivityType::API_TOKEN_UPDATE, $token); return redirect($token->getUrl()); } /** * Show the delete view for this token. */ public function delete(int $userId, int $tokenId) { [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId); $this->setPageTitle(trans('settings.user_api_token_delete')); return view('users.api-tokens.delete', [ 'user' => $user, 'token' => $token, ]); } /** * Destroy a token from the system. */ public function destroy(int $userId, int $tokenId) { [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId); $token->delete(); $this->logActivity(ActivityType::API_TOKEN_DELETE, $token); return redirect($this->getRedirectPath($user)); } /** * Check the permission for the current user and return an array * where the first item is the user in context and the second item is their * API token in context. */ protected function checkPermissionAndFetchUserToken(int $userId, int $tokenId): array { $this->checkPermissionOr(Permission::UsersManage, function () use ($userId) { return $userId === user()->id && userCan(Permission::AccessApi); }); $user = User::query()->findOrFail($userId); $token = ApiToken::query()->where('user_id', '=', $user->id)->where('id', '=', $tokenId)->firstOrFail(); return [$user, $token]; } /** * Update the context for where the user is coming from to manage API tokens. * (Track of location for correct return redirects) */ protected function updateContext(Request $request): void { $context = $request->query('context'); if ($context) { session()->put('api-token-context', $context); } } /** * Get the redirect path for the current api token editing session. * Attempts to recall the context of where the user is editing from. */ protected function getRedirectPath(User $relatedUser): string { $context = session()->get('api-token-context'); if ($context === 'settings' || user()->id !== $relatedUser->id) { return $relatedUser->getEditUrl('#api_tokens'); } return url('/my-account/auth#api_tokens'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Api/ApiTokenGuard.php
app/Api/ApiTokenGuard.php
<?php namespace BookStack\Api; use BookStack\Access\LoginService; use BookStack\Exceptions\ApiAuthException; use BookStack\Permissions\Permission; use Illuminate\Auth\GuardHelpers; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\Guard; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Hash; use Symfony\Component\HttpFoundation\Request; class ApiTokenGuard implements Guard { use GuardHelpers; /** * The request instance. */ protected $request; /** * @var LoginService */ protected $loginService; /** * The last auth exception thrown in this request. * * @var ApiAuthException */ protected $lastAuthException; /** * ApiTokenGuard constructor. */ public function __construct(Request $request, LoginService $loginService) { $this->request = $request; $this->loginService = $loginService; } /** * {@inheritdoc} */ public function user() { // Return the user if we've already retrieved them. // Effectively a request-instance cache for this method. if (!is_null($this->user)) { return $this->user; } $user = null; try { $user = $this->getAuthorisedUserFromRequest(); } catch (ApiAuthException $exception) { $this->lastAuthException = $exception; } $this->user = $user; return $user; } /** * Determine if current user is authenticated. If not, throw an exception. * * @throws ApiAuthException * * @return \Illuminate\Contracts\Auth\Authenticatable */ public function authenticate() { if (!is_null($user = $this->user())) { return $user; } if ($this->lastAuthException) { throw $this->lastAuthException; } throw new ApiAuthException('Unauthorized'); } /** * Check the API token in the request and fetch a valid authorised user. * * @throws ApiAuthException */ protected function getAuthorisedUserFromRequest(): Authenticatable { $authToken = trim($this->request->headers->get('Authorization', '')); $this->validateTokenHeaderValue($authToken); [$id, $secret] = explode(':', str_replace('Token ', '', $authToken)); $token = ApiToken::query() ->where('token_id', '=', $id) ->with(['user'])->first(); $this->validateToken($token, $secret); if ($this->loginService->awaitingEmailConfirmation($token->user)) { throw new ApiAuthException(trans('errors.email_confirmation_awaiting')); } return $token->user; } /** * Validate the format of the token header value string. * * @throws ApiAuthException */ protected function validateTokenHeaderValue(string $authToken): void { if (empty($authToken)) { throw new ApiAuthException(trans('errors.api_no_authorization_found')); } if (strpos($authToken, ':') === false || strpos($authToken, 'Token ') !== 0) { throw new ApiAuthException(trans('errors.api_bad_authorization_format')); } } /** * Validate the given secret against the given token and ensure the token * currently has access to the instance API. * * @throws ApiAuthException */ protected function validateToken(?ApiToken $token, string $secret): void { if ($token === null) { throw new ApiAuthException(trans('errors.api_user_token_not_found')); } if (!Hash::check($secret, $token->secret)) { throw new ApiAuthException(trans('errors.api_incorrect_token_secret')); } $now = Carbon::now(); if ($token->expires_at <= $now) { throw new ApiAuthException(trans('errors.api_user_token_expired'), 403); } if (!$token->user->can(Permission::AccessApi)) { throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403); } } /** * {@inheritdoc} */ public function validate(array $credentials = []) { if (empty($credentials['id']) || empty($credentials['secret'])) { return false; } $token = ApiToken::query() ->where('token_id', '=', $credentials['id']) ->with(['user'])->first(); if ($token === null) { return false; } return Hash::check($credentials['secret'], $token->secret); } /** * "Log out" the currently authenticated user. */ public function logout() { $this->user = null; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/SearchResultsFormatter.php
app/Search/SearchResultsFormatter.php
<?php namespace BookStack\Search; use BookStack\Activity\Models\Tag; use BookStack\Entities\Models\Entity; use Illuminate\Support\HtmlString; class SearchResultsFormatter { /** * For the given array of entities, Prepare the models to be shown in search result * output. This sets a series of additional attributes. * * @param Entity[] $results */ public function format(array $results, SearchOptions $options): void { foreach ($results as $result) { $this->setSearchPreview($result, $options); } } /** * Update the given entity model to set attributes used for previews of the item * primarily within search result lists. */ protected function setSearchPreview(Entity $entity, SearchOptions $options): void { $textProperty = $entity->textField; $textContent = $entity->$textProperty; $relevantSearchOptions = $options->exacts->merge($options->searches); $terms = $relevantSearchOptions->toValueArray(); $originalContentByNewAttribute = [ 'preview_name' => $entity->name, 'preview_content' => $textContent, ]; foreach ($originalContentByNewAttribute as $attributeName => $content) { $targetLength = ($attributeName === 'preview_name') ? 0 : 260; $matchRefs = $this->getMatchPositions($content, $terms); $mergedRefs = $this->sortAndMergeMatchPositions($matchRefs); $formatted = $this->formatTextUsingMatchPositions($mergedRefs, $content, $targetLength); $entity->setAttribute($attributeName, new HtmlString($formatted)); } $tags = $entity->relationLoaded('tags') ? $entity->tags->all() : []; $this->highlightTagsContainingTerms($tags, $terms); } /** * Highlight tags which match the given terms. * * @param Tag[] $tags * @param string[] $terms */ protected function highlightTagsContainingTerms(array $tags, array $terms): void { foreach ($tags as $tag) { $tagName = mb_strtolower($tag->name); $tagValue = mb_strtolower($tag->value); foreach ($terms as $term) { $termLower = mb_strtolower($term); if (mb_strpos($tagName, $termLower) !== false) { $tag->setAttribute('highlight_name', true); } if (mb_strpos($tagValue, $termLower) !== false) { $tag->setAttribute('highlight_value', true); } } } } /** * Get positions of the given terms within the given text. * Is in the array format of [int $startIndex => int $endIndex] where the indexes * are positions within the provided text. * * @return array<int, int> */ protected function getMatchPositions(string $text, array $terms): array { $matchRefs = []; $text = mb_strtolower($text); foreach ($terms as $term) { $offset = 0; $term = mb_strtolower($term); $pos = mb_strpos($text, $term, $offset); while ($pos !== false && count($matchRefs) < 25) { $end = $pos + mb_strlen($term); $matchRefs[$pos] = $end; $offset = $end; $pos = mb_strpos($text, $term, $offset); } } return $matchRefs; } /** * Sort the given match positions before merging them where they're * adjacent or where they overlap. * * @param array<int, int> $matchPositions * * @return array<int, int> */ protected function sortAndMergeMatchPositions(array $matchPositions): array { ksort($matchPositions); $mergedRefs = []; $lastStart = 0; $lastEnd = 0; foreach ($matchPositions as $start => $end) { if ($start > $lastEnd) { $mergedRefs[$start] = $end; $lastStart = $start; $lastEnd = $end; } elseif ($end > $lastEnd) { $mergedRefs[$lastStart] = $end; $lastEnd = $end; } } return $mergedRefs; } /** * Format the given original text, returning a version where terms are highlighted within. * Returned content is in HTML text format. * A given $targetLength of 0 asserts no target length limit. * * This is a complex function but written to be relatively efficient, going through the term matches in order * so that we're only doing a one-time loop through of the matches. There is no further searching * done within here. */ protected function formatTextUsingMatchPositions(array $matchPositions, string $originalText, int $targetLength): string { $maxEnd = mb_strlen($originalText); $fetchAll = ($targetLength === 0); $contextLength = ($fetchAll ? 0 : 32); $firstStart = null; $lastEnd = 0; $content = ''; $contentTextLength = 0; if ($fetchAll) { $targetLength = $maxEnd * 2; } foreach ($matchPositions as $start => $end) { // Get our outer text ranges for the added context we want to show upon the result. $contextStart = max($start - $contextLength, 0, $lastEnd); $contextEnd = min($end + $contextLength, $maxEnd); // Adjust the start if we're going to be touching the previous match. $startDiff = $start - $lastEnd; if ($startDiff < 0) { $contextStart = $start; // Trims off '$startDiff' number of characters to bring it back to the start // if this current match zone. $content = mb_substr($content, 0, mb_strlen($content) + $startDiff); $contentTextLength += $startDiff; } // Add ellipsis between results if (!$fetchAll && $contextStart !== 0 && $contextStart !== $start) { $content .= ' ...'; $contentTextLength += 4; } elseif ($fetchAll) { // Or fill in gap since the previous match $fillLength = $contextStart - $lastEnd; $content .= e(mb_substr($originalText, $lastEnd, $fillLength)); $contentTextLength += $fillLength; } // Add our content including the bolded matching text $content .= e(mb_substr($originalText, $contextStart, $start - $contextStart)); $contentTextLength += $start - $contextStart; $content .= '<strong>' . e(mb_substr($originalText, $start, $end - $start)) . '</strong>'; $contentTextLength += $end - $start; $content .= e(mb_substr($originalText, $end, $contextEnd - $end)); $contentTextLength += $contextEnd - $end; // Update our last end position $lastEnd = $contextEnd; // Update the first start position if it's not already been set if (is_null($firstStart)) { $firstStart = $contextStart; } // Stop if we're near our target if ($contentTextLength >= $targetLength - 10) { break; } } // Just copy out the content if we haven't moved along anywhere. if ($lastEnd === 0) { $content = e(mb_substr($originalText, 0, $targetLength)); $contentTextLength = $targetLength; $lastEnd = $targetLength; } // Pad out the end if we're low $remainder = $targetLength - $contentTextLength; if ($remainder > 10) { $padEndLength = min($maxEnd - $lastEnd, $remainder); $content .= e(mb_substr($originalText, $lastEnd, $padEndLength)); $lastEnd += $padEndLength; $contentTextLength += $padEndLength; } // Pad out the start if we're still low $remainder = $targetLength - $contentTextLength; $firstStart = $firstStart ?: 0; if (!$fetchAll && $remainder > 10 && $firstStart !== 0) { $padStart = max(0, $firstStart - $remainder); $content = ($padStart === 0 ? '' : '...') . e(mb_substr($originalText, $padStart, $firstStart - $padStart)) . mb_substr($content, 4); } // Add ellipsis if we're not at the end if ($lastEnd < $maxEnd) { $content .= '...'; } return $content; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/SearchOptions.php
app/Search/SearchOptions.php
<?php namespace BookStack\Search; use BookStack\Search\Options\ExactSearchOption; use BookStack\Search\Options\FilterSearchOption; use BookStack\Search\Options\SearchOption; use BookStack\Search\Options\TagSearchOption; use BookStack\Search\Options\TermSearchOption; use Illuminate\Http\Request; class SearchOptions { /** @var SearchOptionSet<TermSearchOption> */ public SearchOptionSet $searches; /** @var SearchOptionSet<ExactSearchOption> */ public SearchOptionSet $exacts; /** @var SearchOptionSet<TagSearchOption> */ public SearchOptionSet $tags; /** @var SearchOptionSet<FilterSearchOption> */ public SearchOptionSet $filters; public function __construct() { $this->searches = new SearchOptionSet(); $this->exacts = new SearchOptionSet(); $this->tags = new SearchOptionSet(); $this->filters = new SearchOptionSet(); } /** * Create a new instance from a search string. */ public static function fromString(string $search): self { $instance = new self(); $instance->addOptionsFromString($search); $instance->limitOptions(); return $instance; } /** * Create a new instance from a request. * Will look for a classic string term and use that * Otherwise we'll use the details from an advanced search form. */ public static function fromRequest(Request $request): self { if (!$request->has('search') && !$request->has('term')) { return static::fromString(''); } if ($request->has('term')) { return static::fromString($request->get('term')); } $instance = new SearchOptions(); $inputs = $request->only(['search', 'types', 'filters', 'exact', 'tags', 'extras']); $parsedStandardTerms = static::parseStandardTermString($inputs['search'] ?? ''); $inputExacts = array_filter($inputs['exact'] ?? []); $instance->searches = SearchOptionSet::fromValueArray(array_filter($parsedStandardTerms['terms']), TermSearchOption::class); $instance->exacts = SearchOptionSet::fromValueArray(array_filter($parsedStandardTerms['exacts']), ExactSearchOption::class); $instance->exacts = $instance->exacts->merge(SearchOptionSet::fromValueArray($inputExacts, ExactSearchOption::class)); $instance->tags = SearchOptionSet::fromValueArray(array_filter($inputs['tags'] ?? []), TagSearchOption::class); $cleanedFilters = []; foreach (($inputs['filters'] ?? []) as $filterKey => $filterVal) { if (empty($filterVal)) { continue; } $cleanedFilterVal = $filterVal === 'true' ? '' : $filterVal; $cleanedFilters[] = new FilterSearchOption($cleanedFilterVal, $filterKey); } if (isset($inputs['types']) && count($inputs['types']) < 4) { $cleanedFilters[] = new FilterSearchOption(implode('|', $inputs['types']), 'type'); } $instance->filters = new SearchOptionSet($cleanedFilters); // Parse and merge in extras if provided if (!empty($inputs['extras'])) { $extras = static::fromString($inputs['extras']); $instance->searches = $instance->searches->merge($extras->searches); $instance->exacts = $instance->exacts->merge($extras->exacts); $instance->tags = $instance->tags->merge($extras->tags); $instance->filters = $instance->filters->merge($extras->filters); } $instance->limitOptions(); return $instance; } /** * Decode a search string and add its contents to this instance. */ protected function addOptionsFromString(string $searchString): void { /** @var array<string, SearchOption[]> $terms */ $terms = [ 'exacts' => [], 'tags' => [], 'filters' => [], ]; $patterns = [ 'exacts' => '/-?"((?:\\\\.|[^"\\\\])*)"/', 'tags' => '/-?\[(.*?)\]/', 'filters' => '/-?\{(.*?)\}/', ]; $constructors = [ 'exacts' => fn(string $value, bool $negated) => new ExactSearchOption($value, $negated), 'tags' => fn(string $value, bool $negated) => new TagSearchOption($value, $negated), 'filters' => fn(string $value, bool $negated) => FilterSearchOption::fromContentString($value, $negated), ]; // Parse special terms foreach ($patterns as $termType => $pattern) { $matches = []; preg_match_all($pattern, $searchString, $matches); if (count($matches) > 0) { foreach ($matches[1] as $index => $value) { $negated = str_starts_with($matches[0][$index], '-'); $terms[$termType][] = $constructors[$termType]($value, $negated); } $searchString = preg_replace($pattern, '', $searchString); } } // Unescape exacts and backslash escapes foreach ($terms['exacts'] as $exact) { $exact->value = static::decodeEscapes($exact->value); } // Parse standard terms $parsedStandardTerms = static::parseStandardTermString($searchString); $this->searches = $this->searches ->merge(SearchOptionSet::fromValueArray($parsedStandardTerms['terms'], TermSearchOption::class)) ->filterEmpty(); $this->exacts = $this->exacts ->merge(new SearchOptionSet($terms['exacts'])) ->merge(SearchOptionSet::fromValueArray($parsedStandardTerms['exacts'], ExactSearchOption::class)) ->filterEmpty(); // Add tags & filters $this->tags = $this->tags->merge(new SearchOptionSet($terms['tags'])); $this->filters = $this->filters->merge(new SearchOptionSet($terms['filters'])); } /** * Limit the amount of search options to reasonable levels. * Provides higher limits to logged-in users since that signals a slightly * higher level of trust. */ protected function limitOptions(): void { $userLoggedIn = !user()->isGuest(); $searchLimit = $userLoggedIn ? 10 : 5; $exactLimit = $userLoggedIn ? 4 : 2; $tagLimit = $userLoggedIn ? 8 : 4; $filterLimit = $userLoggedIn ? 10 : 5; $this->searches = $this->searches->limit($searchLimit); $this->exacts = $this->exacts->limit($exactLimit); $this->tags = $this->tags->limit($tagLimit); $this->filters = $this->filters->limit($filterLimit); } /** * Decode backslash escaping within the input string. */ protected static function decodeEscapes(string $input): string { $decoded = ""; $escaping = false; foreach (str_split($input) as $char) { if ($escaping) { $decoded .= $char; $escaping = false; } else if ($char === '\\') { $escaping = true; } else { $decoded .= $char; } } return $decoded; } /** * Parse a standard search term string into individual search terms and * convert any required terms to exact matches. This is done since some * characters will never be in the standard index, since we use them as * delimiters, and therefore we convert a term to be exact if it * contains one of those delimiter characters. * * @return array{terms: array<string>, exacts: array<string>} */ protected static function parseStandardTermString(string $termString): array { $terms = explode(' ', $termString); $indexDelimiters = implode('', array_diff(str_split(SearchIndex::$delimiters), str_split(SearchIndex::$softDelimiters))); $parsed = [ 'terms' => [], 'exacts' => [], ]; foreach ($terms as $searchTerm) { if ($searchTerm === '') { continue; } $becomeExact = (strpbrk($searchTerm, $indexDelimiters) !== false); $parsed[$becomeExact ? 'exacts' : 'terms'][] = $searchTerm; } return $parsed; } /** * Set the value of a specific filter in the search options. */ public function setFilter(string $filterName, string $filterValue = ''): void { $this->filters = $this->filters->merge( new SearchOptionSet([new FilterSearchOption($filterValue, $filterName)]) ); } /** * Encode this instance to a search string. */ public function toString(): string { $options = [ ...$this->searches->all(), ...$this->exacts->all(), ...$this->tags->all(), ...$this->filters->all(), ]; $parts = array_map(fn(SearchOption $o) => $o->toString(), $options); return implode(' ', $parts); } /** * Get the search options that don't have UI controls provided for. * Provided back as a key => value array with the keys being expected * input names for a search form, and values being the option value. */ public function getAdditionalOptionsString(): string { $options = []; // Handle filters without UI support $userFilters = ['updated_by', 'created_by', 'owned_by']; $unsupportedFilters = ['is_template', 'sort_by']; foreach ($this->filters->all() as $filter) { if (in_array($filter->getKey(), $userFilters, true) && $filter->value !== null && $filter->value !== 'me') { $options[] = $filter; } else if (in_array($filter->getKey(), $unsupportedFilters, true)) { $options[] = $filter; } } // Negated items array_push($options, ...$this->exacts->negated()->all()); array_push($options, ...$this->tags->negated()->all()); array_push($options, ...$this->filters->negated()->all()); return implode(' ', array_map(fn(SearchOption $o) => $o->toString(), $options)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/SearchApiController.php
app/Search/SearchApiController.php
<?php declare(strict_types=1); namespace BookStack\Search; use BookStack\Api\ApiEntityListFormatter; use BookStack\Entities\Models\Entity; use BookStack\Http\ApiController; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; class SearchApiController extends ApiController { protected array $rules = [ 'all' => [ 'query' => ['required'], 'page' => ['integer', 'min:1'], 'count' => ['integer', 'min:1', 'max:100'], ], ]; public function __construct( protected SearchRunner $searchRunner, protected SearchResultsFormatter $resultsFormatter ) { } /** * Run a search query against all main content types (shelves, books, chapters & pages) * in the system. Takes the same input as the main search bar within the BookStack * interface as a 'query' parameter. See https://www.bookstackapp.com/docs/user/searching/ * for a full list of search term options. Results contain a 'type' property to distinguish * between: bookshelf, book, chapter & page. * * The paging parameters and response format emulates a standard listing endpoint * but standard sorting and filtering cannot be done on this endpoint. */ public function all(Request $request): JsonResponse { $this->validate($request, $this->rules['all']); $options = SearchOptions::fromString($request->get('query') ?? ''); $page = intval($request->get('page', '0')) ?: 1; $count = min(intval($request->get('count', '0')) ?: 20, 100); $results = $this->searchRunner->searchEntities($options, 'all', $page, $count); $this->resultsFormatter->format($results['results']->all(), $options); $data = (new ApiEntityListFormatter($results['results']->all())) ->withType()->withTags()->withParents() ->withField('preview_html', function (Entity $entity) { return [ 'name' => (string) $entity->getAttribute('preview_name'), 'content' => (string) $entity->getAttribute('preview_content'), ]; })->format(); return response()->json([ 'data' => $data, 'total' => $results['total'], ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/SearchTerm.php
app/Search/SearchTerm.php
<?php namespace BookStack\Search; use BookStack\App\Model; class SearchTerm extends Model { protected $fillable = ['term', 'entity_id', 'entity_type', 'score']; public $timestamps = false; /** * Get the entity that this term belongs to. * * @return \Illuminate\Database\Eloquent\Relations\MorphTo */ public function entity() { return $this->morphTo('entity'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/SearchOptionSet.php
app/Search/SearchOptionSet.php
<?php namespace BookStack\Search; use BookStack\Search\Options\SearchOption; /** * @template T of SearchOption */ class SearchOptionSet { /** * @var T[] */ protected array $options = []; /** * @param T[] $options */ public function __construct(array $options = []) { $this->options = $options; } public function toValueArray(): array { return array_map(fn(SearchOption $option) => $option->value, $this->options); } public function toValueMap(): array { $map = []; foreach ($this->options as $index => $option) { $key = $option->getKey() ?? $index; $map[$key] = $option->value; } return $map; } public function merge(SearchOptionSet $set): self { return new self(array_merge($this->options, $set->options)); } public function filterEmpty(): self { $filteredOptions = array_values(array_filter($this->options, fn (SearchOption $option) => !empty($option->value))); return new self($filteredOptions); } /** * @param class-string<SearchOption> $class */ public static function fromValueArray(array $values, string $class): self { $options = array_map(fn($val) => new $class($val), $values); return new self($options); } /** * @return T[] */ public function all(): array { return $this->options; } /** * @return self<T> */ public function negated(): self { $values = array_values(array_filter($this->options, fn (SearchOption $option) => $option->negated)); return new self($values); } /** * @return self<T> */ public function nonNegated(): self { $values = array_values(array_filter($this->options, fn (SearchOption $option) => !$option->negated)); return new self($values); } /** * @return self<T> */ public function limit(int $limit): self { return new self(array_slice(array_values($this->options), 0, $limit)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/SearchIndex.php
app/Search/SearchIndex.php
<?php namespace BookStack\Search; use BookStack\Activity\Models\Tag; use BookStack\Entities\EntityProvider; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Util\HtmlDocument; use DOMNode; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Collection; class SearchIndex { /** * A list of delimiter characters used to break-up parsed content into terms for indexing. */ public static string $delimiters = " \n\t.-,!?:;()[]{}<>`'\"«»"; /** * A list of delimiter which could be commonly used within a single term and also indicate a break between terms. * The indexer will index the full term with these delimiters, plus the terms split via these delimiters. */ public static string $softDelimiters = ".-"; public function __construct( protected EntityProvider $entityProvider ) { } /** * Index the given entity. */ public function indexEntity(Entity $entity): void { $this->deleteEntityTerms($entity); $terms = $this->entityToTermDataArray($entity); $this->insertTerms($terms); } /** * Index multiple Entities at once. * * @param Entity[] $entities */ public function indexEntities(array $entities): void { $terms = []; foreach ($entities as $entity) { $entityTerms = $this->entityToTermDataArray($entity); array_push($terms, ...$entityTerms); } $this->insertTerms($terms); } /** * Delete and re-index the terms for all entities in the system. * Can take a callback which is used for reporting progress. * Callback receives three arguments: * - An instance of the model being processed * - The number that have been processed so far. * - The total number of that model to be processed. * * @param callable(Entity, int, int):void|null $progressCallback */ public function indexAllEntities(?callable $progressCallback = null): void { SearchTerm::query()->truncate(); foreach ($this->entityProvider->all() as $entityModel) { $indexContentField = $entityModel instanceof Page ? 'html' : 'description'; $selectFields = ['id', 'name', $indexContentField]; /** @var Builder<Entity> $query */ $query = $entityModel->newQuery(); $total = $query->withTrashed()->count(); $chunkSize = 250; $processed = 0; $chunkCallback = function (Collection $entities) use ($progressCallback, &$processed, $total, $chunkSize, $entityModel) { $this->indexEntities($entities->all()); $processed = min($processed + $chunkSize, $total); if (is_callable($progressCallback)) { $progressCallback($entityModel, $processed, $total); } }; $entityModel->newQuery() ->select($selectFields) ->with(['tags:id,name,value,entity_id,entity_type']) ->chunk($chunkSize, $chunkCallback); } } /** * Delete related Entity search terms. */ public function deleteEntityTerms(Entity $entity): void { $entity->searchTerms()->delete(); } /** * Insert the given terms into the database. * Chunks through the given terms to remain within database limits. * @param array[] $terms */ protected function insertTerms(array $terms): void { $chunkedTerms = array_chunk($terms, 500); foreach ($chunkedTerms as $termChunk) { SearchTerm::query()->insert($termChunk); } } /** * Create a scored term array from the given text, where the keys are the terms * and the values are their scores. * * @return array<string, int> */ protected function generateTermScoreMapFromText(string $text, float $scoreAdjustment = 1): array { $termMap = $this->textToTermCountMap($text); foreach ($termMap as $term => $count) { $termMap[$term] = intval($count * $scoreAdjustment); } return $termMap; } /** * Create a scored term array from the given HTML, where the keys are the terms * and the values are their scores. * * @return array<string, int> */ protected function generateTermScoreMapFromHtml(string $html): array { if (empty($html)) { return []; } $scoresByTerm = []; $elementScoreAdjustmentMap = [ 'h1' => 10, 'h2' => 5, 'h3' => 4, 'h4' => 3, 'h5' => 2, 'h6' => 1.5, ]; $html = str_ireplace(['<br>', '<br />', '<br/>'], "\n", $html); $doc = new HtmlDocument($html); /** @var DOMNode $child */ foreach ($doc->getBodyChildren() as $child) { $nodeName = $child->nodeName; $text = trim($child->textContent); $text = str_replace("\u{00A0}", ' ', $text); $termCounts = $this->textToTermCountMap($text); foreach ($termCounts as $term => $count) { $scoreChange = $count * ($elementScoreAdjustmentMap[$nodeName] ?? 1); $scoresByTerm[$term] = ($scoresByTerm[$term] ?? 0) + $scoreChange; } } return $scoresByTerm; } /** * Create a scored term map from the given set of entity tags. * * @param Tag[] $tags * * @return array<string, int> */ protected function generateTermScoreMapFromTags(array $tags): array { $names = []; $values = []; foreach ($tags as $tag) { $names[] = $tag->name; $values[] = $tag->value; } $nameMap = $this->generateTermScoreMapFromText(implode(' ', $names), 3); $valueMap = $this->generateTermScoreMapFromText(implode(' ', $values), 5); return $this->mergeTermScoreMaps($nameMap, $valueMap); } /** * For the given text, return an array where the keys are the unique term words * and the values are the frequency of that term. * * @return array<string, int> */ protected function textToTermCountMap(string $text): array { $tokenMap = []; // {TextToken => OccurrenceCount} $softDelims = static::$softDelimiters; $tokenizer = new SearchTextTokenizer($text, static::$delimiters); $extendedToken = ''; $extendedLen = 0; $token = $tokenizer->next(); while ($token !== false) { $delim = $tokenizer->previousDelimiter(); if ($delim && str_contains($softDelims, $delim) && $token !== '') { $extendedToken .= $delim . $token; $extendedLen++; } else { if ($extendedLen > 1) { $tokenMap[$extendedToken] = ($tokenMap[$extendedToken] ?? 0) + 1; } $extendedToken = $token; $extendedLen = 1; } if ($token) { $tokenMap[$token] = ($tokenMap[$token] ?? 0) + 1; } $token = $tokenizer->next(); } if ($extendedLen > 1) { $tokenMap[$extendedToken] = ($tokenMap[$extendedToken] ?? 0) + 1; } return $tokenMap; } /** * For the given entity, Generate an array of term data details. * Is the raw term data, not instances of SearchTerm models. * * @return array{term: string, score: float, entity_id: int, entity_type: string}[] */ protected function entityToTermDataArray(Entity $entity): array { $nameTermsMap = $this->generateTermScoreMapFromText($entity->name, 40 * $entity->searchFactor); $tagTermsMap = $this->generateTermScoreMapFromTags($entity->tags->all()); if ($entity instanceof Page) { $bodyTermsMap = $this->generateTermScoreMapFromHtml($entity->html); } else { $bodyTermsMap = $this->generateTermScoreMapFromText($entity->getAttribute('description') ?? '', $entity->searchFactor); } $mergedScoreMap = $this->mergeTermScoreMaps($nameTermsMap, $bodyTermsMap, $tagTermsMap); $dataArray = []; $entityId = $entity->id; $entityType = $entity->getMorphClass(); foreach ($mergedScoreMap as $term => $score) { $dataArray[] = [ 'term' => $term, 'score' => $score, 'entity_type' => $entityType, 'entity_id' => $entityId, ]; } return $dataArray; } /** * For the given term data arrays, Merge their contents by term * while combining any scores. * * @param array<string, int>[] ...$scoreMaps * * @return array<string, int> */ protected function mergeTermScoreMaps(...$scoreMaps): array { $mergedMap = []; foreach ($scoreMaps as $scoreMap) { foreach ($scoreMap as $term => $score) { $mergedMap[$term] = ($mergedMap[$term] ?? 0) + $score; } } return $mergedMap; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/SearchRunner.php
app/Search/SearchRunner.php
<?php namespace BookStack\Search; use BookStack\Entities\EntityProvider; use BookStack\Entities\Models\Entity; use BookStack\Entities\Queries\EntityQueries; use BookStack\Entities\Tools\EntityHydrator; use BookStack\Permissions\PermissionApplicator; use BookStack\Search\Options\TagSearchOption; use BookStack\Users\Models\User; use Illuminate\Database\Connection; use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Query\Builder; use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use WeakMap; class SearchRunner { /** * Retain a cache of score-adjusted terms for specific search options. */ protected WeakMap $termAdjustmentCache; public function __construct( protected EntityProvider $entityProvider, protected PermissionApplicator $permissions, protected EntityQueries $entityQueries, protected EntityHydrator $entityHydrator, ) { $this->termAdjustmentCache = new WeakMap(); } /** * Search all entities in the system. * * @return array{total: int, results: Collection<Entity>} */ public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20): array { $entityTypes = array_keys($this->entityProvider->all()); $entityTypesToSearch = $entityTypes; $filterMap = $searchOpts->filters->toValueMap(); if ($entityType !== 'all') { $entityTypesToSearch = [$entityType]; } elseif (isset($filterMap['type'])) { $entityTypesToSearch = explode('|', $filterMap['type']); } $searchQuery = $this->buildQuery($searchOpts, $entityTypesToSearch); $total = $searchQuery->count(); $results = $this->getPageOfDataFromQuery($searchQuery, $page, $count); return [ 'total' => $total, 'results' => $results->values(), ]; } /** * Search a book for entities. */ public function searchBook(int $bookId, string $searchString): Collection { $opts = SearchOptions::fromString($searchString); $entityTypes = ['page', 'chapter']; $filterMap = $opts->filters->toValueMap(); $entityTypesToSearch = isset($filterMap['type']) ? explode('|', $filterMap['type']) : $entityTypes; $filteredTypes = array_intersect($entityTypesToSearch, $entityTypes); $query = $this->buildQuery($opts, $filteredTypes)->where('book_id', '=', $bookId); return $this->getPageOfDataFromQuery($query, 1, 20)->sortByDesc('score'); } /** * Search a chapter for entities. */ public function searchChapter(int $chapterId, string $searchString): Collection { $opts = SearchOptions::fromString($searchString); $query = $this->buildQuery($opts, ['page'])->where('chapter_id', '=', $chapterId); return $this->getPageOfDataFromQuery($query, 1, 20)->sortByDesc('score'); } /** * Get a page of result data from the given query based on the provided page parameters. */ protected function getPageOfDataFromQuery(EloquentBuilder $query, int $page, int $count): Collection { $entities = $query->clone() ->skip(($page - 1) * $count) ->take($count) ->get(); $hydrated = $this->entityHydrator->hydrate($entities->all(), true, true); return collect($hydrated); } /** * Create a search query for an entity. * @param string[] $entityTypes */ protected function buildQuery(SearchOptions $searchOpts, array $entityTypes): EloquentBuilder { $entityQuery = $this->entityQueries->visibleForList() ->whereIn('type', $entityTypes); // Handle normal search terms $this->applyTermSearch($entityQuery, $searchOpts, $entityTypes); // Handle exact term matching foreach ($searchOpts->exacts->all() as $exact) { $filter = function (EloquentBuilder $query) use ($exact) { $inputTerm = str_replace('\\', '\\\\', $exact->value); $query->where('name', 'like', '%' . $inputTerm . '%') ->orWhere('description', 'like', '%' . $inputTerm . '%') ->orWhere('text', 'like', '%' . $inputTerm . '%'); }; $exact->negated ? $entityQuery->whereNot($filter) : $entityQuery->where($filter); } // Handle tag searches foreach ($searchOpts->tags->all() as $tagOption) { $this->applyTagSearch($entityQuery, $tagOption); } // Handle filters foreach ($searchOpts->filters->all() as $filterOption) { $functionName = Str::camel('filter_' . $filterOption->getKey()); if (method_exists($this, $functionName)) { $this->$functionName($entityQuery, $filterOption->value, $filterOption->negated); } } return $entityQuery; } /** * For the given search query, apply the queries for handling the regular search terms. */ protected function applyTermSearch(EloquentBuilder $entityQuery, SearchOptions $options, array $entityTypes): void { $terms = $options->searches->toValueArray(); if (count($terms) === 0) { return; } $scoredTerms = $this->getTermAdjustments($options); $scoreSelect = $this->selectForScoredTerms($scoredTerms); $subQuery = DB::table('search_terms')->select([ 'entity_id', 'entity_type', DB::raw($scoreSelect['statement']), ]); $subQuery->addBinding($scoreSelect['bindings'], 'select'); $subQuery->where(function (Builder $query) use ($terms) { foreach ($terms as $inputTerm) { $escapedTerm = str_replace('\\', '\\\\', $inputTerm); $query->orWhere('term', 'like', $escapedTerm . '%'); } }); $subQuery->groupBy('entity_type', 'entity_id'); $entityQuery->joinSub($subQuery, 's', function (JoinClause $join) { $join->on('s.entity_id', '=', 'entities.id') ->on('s.entity_type', '=', 'entities.type'); }); $entityQuery->addSelect('s.score'); $entityQuery->orderBy('score', 'desc'); } /** * Create a select statement, with prepared bindings, for the given * set of scored search terms. * * @param array<string, float> $scoredTerms * * @return array{statement: string, bindings: string[]} */ protected function selectForScoredTerms(array $scoredTerms): array { // Within this we walk backwards to create the chain of 'if' statements // so that each previous statement is used in the 'else' condition of // the next (earlier) to be built. We start at '0' to have no score // on no match (Should never actually get to this case). $ifChain = '0'; $bindings = []; foreach ($scoredTerms as $term => $score) { $ifChain = 'IF(term like ?, score * ' . (float) $score . ', ' . $ifChain . ')'; $bindings[] = $term . '%'; } return [ 'statement' => 'SUM(' . $ifChain . ') as score', 'bindings' => array_reverse($bindings), ]; } /** * For the terms in the given search options, query their popularity across all * search terms then provide that back as score adjustment multiplier applicable * for their rarity. Returns an array of float multipliers, keyed by term. * * @return array<string, float> */ protected function getTermAdjustments(SearchOptions $options): array { if (isset($this->termAdjustmentCache[$options])) { return $this->termAdjustmentCache[$options]; } $termQuery = SearchTerm::query()->toBase(); $whenStatements = []; $whenBindings = []; foreach ($options->searches->toValueArray() as $term) { $whenStatements[] = 'WHEN term LIKE ? THEN ?'; $whenBindings[] = $term . '%'; $whenBindings[] = $term; $termQuery->orWhere('term', 'like', $term . '%'); } $case = 'CASE ' . implode(' ', $whenStatements) . ' END'; $termQuery->selectRaw($case . ' as term', $whenBindings); $termQuery->selectRaw('COUNT(*) as count'); $termQuery->groupByRaw($case, $whenBindings); $termCounts = $termQuery->pluck('count', 'term')->toArray(); $adjusted = $this->rawTermCountsToAdjustments($termCounts); $this->termAdjustmentCache[$options] = $adjusted; return $this->termAdjustmentCache[$options]; } /** * Convert counts of terms into a relative-count normalised multiplier. * * @param array<string, int> $termCounts * * @return array<string, float> */ protected function rawTermCountsToAdjustments(array $termCounts): array { if (empty($termCounts)) { return []; } $multipliers = []; $max = max(array_values($termCounts)); foreach ($termCounts as $term => $count) { $percent = round($count / $max, 5); $multipliers[$term] = 1.3 - $percent; } return $multipliers; } /** * Apply a tag search term onto an entity query. */ protected function applyTagSearch(EloquentBuilder $query, TagSearchOption $option): void { $filter = function (EloquentBuilder $query) use ($option): void { $tagParts = $option->getParts(); if (empty($tagParts['operator']) || empty($tagParts['value'])) { $query->where('name', '=', $tagParts['name']); return; } if (!empty($tagParts['name'])) { $query->where('name', '=', $tagParts['name']); } if (is_numeric($tagParts['value']) && $tagParts['operator'] !== 'like') { // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will // search the value as a string which prevents being able to do number-based operations // on the tag values. We ensure it has a numeric value and then cast it just to be sure. /** @var Connection $connection */ $connection = $query->getConnection(); $quotedValue = (float) trim($connection->getPdo()->quote($tagParts['value']), "'"); $query->whereRaw("value {$tagParts['operator']} {$quotedValue}"); } else if ($tagParts['operator'] === 'like') { $query->where('value', $tagParts['operator'], str_replace('\\', '\\\\', $tagParts['value'])); } else { $query->where('value', $tagParts['operator'], $tagParts['value']); } }; $option->negated ? $query->whereDoesntHave('tags', $filter) : $query->whereHas('tags', $filter); } protected function applyNegatableWhere(EloquentBuilder $query, bool $negated, string|callable $column, string|null $operator, mixed $value): void { if ($negated) { $query->whereNot($column, $operator, $value); } else { $query->where($column, $operator, $value); } } /** * Custom entity search filters. */ protected function filterUpdatedAfter(EloquentBuilder $query, string $input, bool $negated): void { $date = date_create($input); $this->applyNegatableWhere($query, $negated, 'updated_at', '>=', $date); } protected function filterUpdatedBefore(EloquentBuilder $query, string $input, bool $negated): void { $date = date_create($input); $this->applyNegatableWhere($query, $negated, 'updated_at', '<', $date); } protected function filterCreatedAfter(EloquentBuilder $query, string $input, bool $negated): void { $date = date_create($input); $this->applyNegatableWhere($query, $negated, 'created_at', '>=', $date); } protected function filterCreatedBefore(EloquentBuilder $query, string $input, bool $negated) { $date = date_create($input); $this->applyNegatableWhere($query, $negated, 'created_at', '<', $date); } protected function filterCreatedBy(EloquentBuilder $query, string $input, bool $negated) { $userSlug = $input === 'me' ? user()->slug : trim($input); $user = User::query()->where('slug', '=', $userSlug)->first(['id']); if ($user) { $this->applyNegatableWhere($query, $negated, 'created_by', '=', $user->id); } } protected function filterUpdatedBy(EloquentBuilder $query, string $input, bool $negated) { $userSlug = $input === 'me' ? user()->slug : trim($input); $user = User::query()->where('slug', '=', $userSlug)->first(['id']); if ($user) { $this->applyNegatableWhere($query, $negated, 'updated_by', '=', $user->id); } } protected function filterOwnedBy(EloquentBuilder $query, string $input, bool $negated) { $userSlug = $input === 'me' ? user()->slug : trim($input); $user = User::query()->where('slug', '=', $userSlug)->first(['id']); if ($user) { $this->applyNegatableWhere($query, $negated, 'owned_by', '=', $user->id); } } protected function filterInName(EloquentBuilder $query, string $input, bool $negated) { $this->applyNegatableWhere($query, $negated, 'name', 'like', '%' . $input . '%'); } protected function filterInTitle(EloquentBuilder $query, string $input, bool $negated) { $this->filterInName($query, $input, $negated); } protected function filterInBody(EloquentBuilder $query, string $input, bool $negated) { $this->applyNegatableWhere($query, $negated, function (EloquentBuilder $query) use ($input) { $query->where('description', 'like', '%' . $input . '%') ->orWhere('text', 'like', '%' . $input . '%'); }, null, null); } protected function filterIsRestricted(EloquentBuilder $query, string $input, bool $negated) { $negated ? $query->whereDoesntHave('permissions') : $query->whereHas('permissions'); } protected function filterViewedByMe(EloquentBuilder $query, string $input, bool $negated) { $filter = function ($query) { $query->where('user_id', '=', user()->id); }; $negated ? $query->whereDoesntHave('views', $filter) : $query->whereHas('views', $filter); } protected function filterNotViewedByMe(EloquentBuilder $query, string $input, bool $negated) { $filter = function ($query) { $query->where('user_id', '=', user()->id); }; $negated ? $query->whereHas('views', $filter) : $query->whereDoesntHave('views', $filter); } protected function filterIsTemplate(EloquentBuilder $query, string $input, bool $negated) { $this->applyNegatableWhere($query, $negated, 'template', '=', true); } protected function filterSortBy(EloquentBuilder $query, string $input, bool $negated) { $functionName = Str::camel('sort_by_' . $input); if (method_exists($this, $functionName)) { $this->$functionName($query, $negated); } } /** * Sorting filter options. */ protected function sortByLastCommented(EloquentBuilder $query, bool $negated) { $commentsTable = DB::getTablePrefix() . 'comments'; $commentQuery = DB::raw('(SELECT c1.commentable_id, c1.commentable_type, c1.created_at as last_commented FROM ' . $commentsTable . ' c1 LEFT JOIN ' . $commentsTable . ' c2 ON (c1.commentable_id = c2.commentable_id AND c1.commentable_type = c2.commentable_type AND c1.created_at < c2.created_at) WHERE c2.created_at IS NULL) as comments'); $query->join($commentQuery, function (JoinClause $join) { $join->on('entities.id', '=', 'comments.commentable_id') ->on('entities.type', '=', 'comments.commentable_type'); })->orderBy('last_commented', $negated ? 'asc' : 'desc'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/SearchController.php
app/Search/SearchController.php
<?php namespace BookStack\Search; use BookStack\Entities\Queries\PageQueries; use BookStack\Entities\Queries\QueryPopular; use BookStack\Entities\Tools\SiblingFetcher; use BookStack\Http\Controller; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator; class SearchController extends Controller { public function __construct( protected SearchRunner $searchRunner, protected PageQueries $pageQueries, ) { } /** * Searches all entities. */ public function search(Request $request, SearchResultsFormatter $formatter) { $searchOpts = SearchOptions::fromRequest($request); $fullSearchString = $searchOpts->toString(); $page = intval($request->get('page', '0')) ?: 1; $count = setting()->getInteger('lists-page-count-search', 18, 1, 1000); $results = $this->searchRunner->searchEntities($searchOpts, 'all', $page, $count); $formatter->format($results['results']->all(), $searchOpts); $paginator = new LengthAwarePaginator($results['results'], $results['total'], $count, $page); $paginator->setPath(url('/search')); $paginator->appends($request->except('page')); $this->setPageTitle(trans('entities.search_for_term', ['term' => $fullSearchString])); return view('search.all', [ 'entities' => $results['results'], 'totalResults' => $results['total'], 'paginator' => $paginator, 'searchTerm' => $fullSearchString, 'options' => $searchOpts, ]); } /** * Searches all entities within a book. */ public function searchBook(Request $request, int $bookId) { $term = $request->get('term', ''); $results = $this->searchRunner->searchBook($bookId, $term); return view('entities.list', ['entities' => $results]); } /** * Searches all entities within a chapter. */ public function searchChapter(Request $request, int $chapterId) { $term = $request->get('term', ''); $results = $this->searchRunner->searchChapter($chapterId, $term); return view('entities.list', ['entities' => $results]); } /** * Search for a list of entities and return a partial HTML response of matching entities. * Returns the most popular entities if no search is provided. */ public function searchForSelector(Request $request, QueryPopular $queryPopular) { $entityTypes = $request->filled('types') ? explode(',', $request->get('types')) : ['page', 'chapter', 'book']; $searchTerm = $request->get('term', false); $permission = $request->get('permission', 'view'); // Search for entities otherwise show most popular if ($searchTerm !== false) { $options = SearchOptions::fromString($searchTerm); $options->setFilter('type', implode('|', $entityTypes)); $entities = $this->searchRunner->searchEntities($options, 'all', 1, 20)['results']; } else { $entities = $queryPopular->run(20, 0, $entityTypes); } return view('search.parts.entity-selector-list', ['entities' => $entities, 'permission' => $permission]); } /** * Search for a list of templates to choose from. */ public function templatesForSelector(Request $request) { $searchTerm = $request->get('term', false); if ($searchTerm !== false) { $searchOptions = SearchOptions::fromString($searchTerm); $searchOptions->setFilter('is_template'); $entities = $this->searchRunner->searchEntities($searchOptions, 'page', 1, 20)['results']; } else { $entities = $this->pageQueries->visibleTemplates() ->where('draft', '=', false) ->orderBy('updated_at', 'desc') ->take(20) ->get(); } return view('search.parts.entity-selector-list', [ 'entities' => $entities, 'permission' => 'view' ]); } /** * Search for a list of entities and return a partial HTML response of matching entities * to be used as a result preview suggestion list for global system searches. */ public function searchSuggestions(Request $request) { $searchTerm = $request->get('term', ''); $entities = $this->searchRunner->searchEntities(SearchOptions::fromString($searchTerm), 'all', 1, 5)['results']; foreach ($entities as $entity) { $entity->setAttribute('preview_content', ''); } return view('search.parts.entity-suggestion-list', [ 'entities' => $entities->slice(0, 5) ]); } /** * Search sibling items in the system. */ public function searchSiblings(Request $request, SiblingFetcher $siblingFetcher) { $type = $request->get('entity_type', null); $id = $request->get('entity_id', null); $entities = $siblingFetcher->fetch($type, $id); return view('entities.list-basic', ['entities' => $entities, 'style' => 'compact']); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/SearchTextTokenizer.php
app/Search/SearchTextTokenizer.php
<?php namespace BookStack\Search; /** * A custom text tokenizer which records & provides insight needed for our search indexing. * We used to use basic strtok() but this class does the following which that lacked: * - Tracks and provides the current/previous delimiter that we've stopped at. * - Returns empty tokens upon parsing a delimiter. */ class SearchTextTokenizer { protected int $currentIndex = 0; protected int $length; protected string $currentDelimiter = ''; protected string $previousDelimiter = ''; public function __construct( protected string $text, protected string $delimiters = ' ' ) { $this->length = strlen($this->text); } /** * Get the current delimiter to be found. */ public function currentDelimiter(): string { return $this->currentDelimiter; } /** * Get the previous delimiter found. */ public function previousDelimiter(): string { return $this->previousDelimiter; } /** * Get the next token between delimiters. * Returns false if there's no further tokens. */ public function next(): string|false { $token = ''; for ($i = $this->currentIndex; $i < $this->length; $i++) { $char = $this->text[$i]; if (str_contains($this->delimiters, $char)) { $this->previousDelimiter = $this->currentDelimiter; $this->currentDelimiter = $char; $this->currentIndex = $i + 1; return $token; } $token .= $char; } if ($token) { $this->currentIndex = $this->length; $this->previousDelimiter = $this->currentDelimiter; $this->currentDelimiter = ''; return $token; } return false; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/Options/SearchOption.php
app/Search/Options/SearchOption.php
<?php namespace BookStack\Search\Options; abstract class SearchOption { public function __construct( public string $value, public bool $negated = false, ) { } /** * Get the key used for this option when used in a map. * Null indicates to use the index of the containing array. */ public function getKey(): string|null { return null; } /** * Get the search string representation for this search option. */ abstract public function toString(): string; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/Options/ExactSearchOption.php
app/Search/Options/ExactSearchOption.php
<?php namespace BookStack\Search\Options; class ExactSearchOption extends SearchOption { public function toString(): string { $escaped = str_replace('\\', '\\\\', $this->value); $escaped = str_replace('"', '\"', $escaped); return ($this->negated ? '-' : '') . '"' . $escaped . '"'; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/Options/FilterSearchOption.php
app/Search/Options/FilterSearchOption.php
<?php namespace BookStack\Search\Options; class FilterSearchOption extends SearchOption { protected string $name; public function __construct( string $value, string $name, bool $negated = false, ) { parent::__construct($value, $negated); $this->name = $name; } public function toString(): string { $valueText = ($this->value ? ':' . $this->value : ''); $filterBrace = '{' . $this->name . $valueText . '}'; return ($this->negated ? '-' : '') . $filterBrace; } public function getKey(): string { return $this->name; } public static function fromContentString(string $value, bool $negated = false): self { $explodedFilter = explode(':', $value, 2); $filterValue = (count($explodedFilter) > 1) ? $explodedFilter[1] : ''; $filterName = $explodedFilter[0]; return new self($filterValue, $filterName, $negated); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/Options/TagSearchOption.php
app/Search/Options/TagSearchOption.php
<?php namespace BookStack\Search\Options; class TagSearchOption extends SearchOption { /** * Acceptable operators to be used within a tag search option. * * @var string[] */ protected array $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!=']; public function toString(): string { return ($this->negated ? '-' : '') . "[{$this->value}]"; } /** * @return array{name: string, operator: string, value: string} */ public function getParts(): array { $operatorRegex = implode('|', array_map(fn($op) => preg_quote($op), $this->queryOperators)); preg_match('/^(.*?)((' . $operatorRegex . ')(.*?))?$/', $this->value, $tagSplit); $extractedOperator = count($tagSplit) > 2 ? $tagSplit[3] : ''; $tagOperator = in_array($extractedOperator, $this->queryOperators) ? $extractedOperator : '='; $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : ''; return [ 'name' => $tagSplit[1], 'operator' => $tagOperator, 'value' => $tagValue, ]; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Search/Options/TermSearchOption.php
app/Search/Options/TermSearchOption.php
<?php namespace BookStack\Search\Options; class TermSearchOption extends SearchOption { public function toString(): string { return $this->value; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/ContentPermissionApiController.php
app/Permissions/ContentPermissionApiController.php
<?php namespace BookStack\Permissions; use BookStack\Entities\EntityProvider; use BookStack\Entities\Models\Entity; use BookStack\Entities\Tools\PermissionsUpdater; use BookStack\Http\ApiController; use Illuminate\Http\Request; class ContentPermissionApiController extends ApiController { public function __construct( protected PermissionsUpdater $permissionsUpdater, protected EntityProvider $entities ) { } protected array $rules = [ 'update' => [ 'owner_id' => ['int'], 'role_permissions' => ['array'], 'role_permissions.*.role_id' => ['required', 'int', 'exists:roles,id'], 'role_permissions.*.view' => ['required', 'boolean'], 'role_permissions.*.create' => ['required', 'boolean'], 'role_permissions.*.update' => ['required', 'boolean'], 'role_permissions.*.delete' => ['required', 'boolean'], 'fallback_permissions' => ['nullable'], 'fallback_permissions.inheriting' => ['required_with:fallback_permissions', 'boolean'], 'fallback_permissions.view' => ['required_if:fallback_permissions.inheriting,false', 'boolean'], 'fallback_permissions.create' => ['required_if:fallback_permissions.inheriting,false', 'boolean'], 'fallback_permissions.update' => ['required_if:fallback_permissions.inheriting,false', 'boolean'], 'fallback_permissions.delete' => ['required_if:fallback_permissions.inheriting,false', 'boolean'], ] ]; /** * Read the configured content-level permissions for the item of the given type and ID. * * 'contentType' should be one of: page, book, chapter, bookshelf. * 'contentId' should be the relevant ID of that item type you'd like to handle permissions for. * * The permissions shown are those that override the default for just the specified item, they do not show the * full evaluated permission for a role, nor do they reflect permissions inherited from other items in the hierarchy. * Fallback permission values may be `null` when inheriting is active. */ public function read(string $contentType, string $contentId) { $entity = $this->entities->get($contentType) ->newQuery()->scopes(['visible'])->findOrFail($contentId); $this->checkOwnablePermission(Permission::RestrictionsManage, $entity); return response()->json($this->formattedPermissionDataForEntity($entity)); } /** * Update the configured content-level permission overrides for the item of the given type and ID. * 'contentType' should be one of: page, book, chapter, bookshelf. * * 'contentId' should be the relevant ID of that item type you'd like to handle permissions for. * Providing an empty `role_permissions` array will remove any existing configured role permissions, * so you may want to fetch existing permissions beforehand if just adding/removing a single item. * You should completely omit the `owner_id`, `role_permissions` and/or the `fallback_permissions` properties * from your request data if you don't wish to update details within those categories. */ public function update(Request $request, string $contentType, string $contentId) { $entity = $this->entities->get($contentType) ->newQuery()->scopes(['visible'])->findOrFail($contentId); $this->checkOwnablePermission(Permission::RestrictionsManage, $entity); $data = $this->validate($request, $this->rules()['update']); $this->permissionsUpdater->updateFromApiRequestData($entity, $data); return response()->json($this->formattedPermissionDataForEntity($entity)); } protected function formattedPermissionDataForEntity(Entity $entity): array { $rolePermissions = $entity->permissions() ->where('role_id', '!=', 0) ->with(['role:id,display_name']) ->get(); $fallback = $entity->permissions()->where('role_id', '=', 0)->first(); $fallbackData = [ 'inheriting' => is_null($fallback), 'view' => $fallback->view ?? null, 'create' => $fallback->create ?? null, 'update' => $fallback->update ?? null, 'delete' => $fallback->delete ?? null, ]; return [ 'owner' => $entity->ownedBy()->first(), 'role_permissions' => $rolePermissions, 'fallback_permissions' => $fallbackData, ]; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/PermissionFormData.php
app/Permissions/PermissionFormData.php
<?php namespace BookStack\Permissions; use BookStack\Entities\Models\Entity; use BookStack\Permissions\Models\EntityPermission; use BookStack\Users\Models\Role; class PermissionFormData { protected Entity $entity; public function __construct(Entity $entity) { $this->entity = $entity; } /** * Get the permissions with assigned roles. */ public function permissionsWithRoles(): array { return $this->entity->permissions() ->with('role') ->where('role_id', '!=', 0) ->get() ->sortBy('role.display_name') ->all(); } /** * Get the roles that don't yet have specific permissions for the * entity we're managing permissions for. */ public function rolesNotAssigned(): array { $assigned = $this->entity->permissions()->pluck('role_id'); return Role::query() ->where('system_name', '!=', 'admin') ->whereNotIn('id', $assigned) ->orderBy('display_name', 'asc') ->get() ->all(); } /** * Get the entity permission for the "Everyone Else" option. */ public function everyoneElseEntityPermission(): EntityPermission { /** @var ?EntityPermission $permission */ $permission = $this->entity->permissions() ->where('role_id', '=', 0) ->first(); return $permission ?? (new EntityPermission()); } /** * Get the "Everyone Else" role entry. */ public function everyoneElseRole(): Role { return (new Role())->forceFill([ 'id' => 0, 'display_name' => trans('entities.permissions_role_everyone_else'), 'description' => trans('entities.permissions_role_everyone_else_desc'), ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/PermissionApplicator.php
app/Permissions/PermissionApplicator.php
<?php namespace BookStack\Permissions; use BookStack\App\Model; use BookStack\Entities\EntityProvider; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Permissions\Models\EntityPermission; use BookStack\Users\Models\OwnableInterface; use BookStack\Users\Models\User; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\Query\JoinClause; use InvalidArgumentException; class PermissionApplicator { public function __construct( protected ?User $user = null ) { } /** * Checks if an entity has a restriction set upon it. */ public function checkOwnableUserAccess(Model&OwnableInterface $ownable, string|Permission $permission): bool { $permissionName = is_string($permission) ? $permission : $permission->value; $explodedPermission = explode('-', $permissionName); $action = $explodedPermission[1] ?? $explodedPermission[0]; $fullPermission = count($explodedPermission) > 1 ? $permissionName : $ownable->getMorphClass() . '-' . $permissionName; $user = $this->currentUser(); $userRoleIds = $this->getCurrentUserRoleIds(); $allRolePermission = $user->can($fullPermission . '-all'); $ownRolePermission = $user->can($fullPermission . '-own'); $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment']; $ownerField = $ownable->getOwnerFieldName(); $ownableFieldVal = $ownable->getAttribute($ownerField); $isOwner = $user->id === $ownableFieldVal; $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission); // Handle non-entity-specific jointPermissions if (in_array($explodedPermission[0], $nonJointPermissions)) { return $hasRolePermission; } if (!($ownable instanceof Entity)) { return false; } $hasApplicableEntityPermissions = $this->hasEntityPermission($ownable, $userRoleIds, $action); return is_null($hasApplicableEntityPermissions) ? $hasRolePermission : $hasApplicableEntityPermissions; } /** * Check if there are permissions that are applicable for the given entity item, action and roles. * Returns null when no entity permissions are in force. */ protected function hasEntityPermission(Entity $entity, array $userRoleIds, string $action): ?bool { $this->ensureValidEntityAction($action); return (new EntityPermissionEvaluator($action))->evaluateEntityForUser($entity, $userRoleIds); } /** * Checks if a user has the given permission for any items in the system. * Can be passed an entity instance to filter on a specific type. */ public function checkUserHasEntityPermissionOnAny(string|Permission $action, string $entityClass = ''): bool { $permissionName = is_string($action) ? $action : $action->value; $this->ensureValidEntityAction($permissionName); $permissionQuery = EntityPermission::query() ->where($permissionName, '=', true) ->whereIn('role_id', $this->getCurrentUserRoleIds()); if (!empty($entityClass)) { /** @var Entity $entityInstance */ $entityInstance = app()->make($entityClass); $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass()); } $hasPermission = $permissionQuery->count() > 0; return $hasPermission; } /** * Limit the given entity query so that the query will only * return items that the user has view permission for. */ public function restrictEntityQuery(Builder $query): Builder { return $query->where(function (Builder $parentQuery) { $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) { $permissionQuery->select(['entity_id', 'entity_type']) ->selectRaw('max(owner_id) as owner_id') ->selectRaw('max(status) as status') ->whereIn('role_id', $this->getCurrentUserRoleIds()) ->groupBy(['entity_type', 'entity_id']) ->havingRaw('(status IN (1, 3) or (owner_id = ? and status != 2))', [$this->currentUser()->id]); }); }); } /** * Extend the given page query to ensure draft items are not visible * unless created by the given user. */ public function restrictDraftsOnPageQuery(Builder $query): Builder { return $query->where(function (Builder $query) { $query->where('draft', '=', false) ->orWhere(function (Builder $query) { $query->where('draft', '=', true) ->where('owned_by', '=', $this->currentUser()->id); }); }); } /** * Filter items that have entities set as a polymorphic relation. * For simplicity, this will not return results attached to draft pages. * Draft pages should never really have related items though. */ public function restrictEntityRelationQuery(Builder $query, string $tableName, string $entityIdColumn, string $entityTypeColumn): Builder { $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn]; $pageMorphClass = (new Page())->getMorphClass(); return $this->restrictEntityQuery($query) ->where(function ($query) use ($tableDetails, $pageMorphClass) { /** @var Builder $query */ $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass) ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) { $query->select('page_id')->from('entity_page_data') ->whereColumn('entity_page_data.page_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn']) ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass) ->where('entity_page_data.draft', '=', false); }); }); } /** * Filter out items that have related entity relations where * the entity is marked as deleted. */ public function filterDeletedFromEntityRelationQuery(Builder $query, string $tableName, string $entityIdColumn, string $entityTypeColumn): Builder { $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn]; $entityProvider = new EntityProvider(); $joinQuery = function ($query) use ($entityProvider) { $first = true; foreach ($entityProvider->all() as $entity) { /** @var Builder $query */ $entityQuery = function ($query) use ($entity) { $query->select(['id', 'deleted_at']) ->selectRaw("'{$entity->getMorphClass()}' as type") ->from($entity->getTable()) ->whereNotNull('deleted_at'); }; if ($first) { $entityQuery($query); $first = false; } else { $query->union($entityQuery); } } }; return $query->leftJoinSub($joinQuery, 'deletions', function (JoinClause $join) use ($tableDetails) { $join->on($tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'], '=', 'deletions.id') ->on($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', 'deletions.type'); })->whereNull('deletions.deleted_at'); } /** * Add conditions to a query for a model that's a relation of a page, so only the model results * on visible pages are returned by the query. * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up. */ public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder { $fullPageIdColumn = $tableName . '.' . $pageIdColumn; return $this->restrictEntityQuery($query) ->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) { $query->select('id')->from('entities') ->leftJoin('entity_page_data', 'entities.id', '=', 'entity_page_data.page_id') ->whereColumn('entities.id', '=', $fullPageIdColumn) ->where('entities.type', '=', 'page') ->where(function (QueryBuilder $query) { $query->where('entity_page_data.draft', '=', false) ->orWhere(function (QueryBuilder $query) { $query->where('entity_page_data.draft', '=', true) ->where('entities.created_by', '=', $this->currentUser()->id); }); }); }); } /** * Get the current user. */ protected function currentUser(): User { return $this->user ?? user(); } /** * Get the roles for the current logged-in user. * * @return int[] */ protected function getCurrentUserRoleIds(): array { return $this->currentUser()->roles->pluck('id')->values()->all(); } /** * Ensure the given action is a valid and expected entity action. * Throws an exception if invalid otherwise does nothing. * @throws InvalidArgumentException */ protected function ensureValidEntityAction(string $action): void { $allowed = Permission::genericForEntity(); foreach ($allowed as $permission) { if ($permission->value === $action) { return; } } throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/PermissionsRepo.php
app/Permissions/PermissionsRepo.php
<?php namespace BookStack\Permissions; use BookStack\Activity\ActivityType; use BookStack\Exceptions\PermissionsException; use BookStack\Facades\Activity; use BookStack\Permissions\Models\RolePermission; use BookStack\Users\Models\Role; use BookStack\Util\DatabaseTransaction; use Exception; use Illuminate\Database\Eloquent\Collection; class PermissionsRepo { protected array $systemRoles = ['admin', 'public']; public function __construct( protected JointPermissionBuilder $permissionBuilder ) { } /** * Get all the user roles from the system. */ public function getAllRoles(): Collection { return Role::query()->get(); } /** * Get all the roles except for the provided one. */ public function getAllRolesExcept(Role $role): Collection { return Role::query()->where('id', '!=', $role->id)->get(); } /** * Get a role via its ID. */ public function getRoleById(int $id): Role { return Role::query()->findOrFail($id); } /** * Save a new role into the system. */ public function saveNewRole(array $roleData): Role { return (new DatabaseTransaction(function () use ($roleData) { $role = new Role($roleData); $role->mfa_enforced = boolval($roleData['mfa_enforced'] ?? false); $role->save(); $permissions = $roleData['permissions'] ?? []; $this->assignRolePermissions($role, $permissions); $this->permissionBuilder->rebuildForRole($role); Activity::add(ActivityType::ROLE_CREATE, $role); return $role; }))->run(); } /** * Updates an existing role. * Ensures the Admin system role always has core permissions. */ public function updateRole($roleId, array $roleData): Role { $role = $this->getRoleById($roleId); return (new DatabaseTransaction(function () use ($role, $roleData) { if (isset($roleData['permissions'])) { $this->assignRolePermissions($role, $roleData['permissions']); } $role->fill($roleData); $role->save(); $this->permissionBuilder->rebuildForRole($role); Activity::add(ActivityType::ROLE_UPDATE, $role); return $role; }))->run(); } /** * Assign a list of permission names to the given role. */ protected function assignRolePermissions(Role $role, array $permissionNameArray = []): void { $permissions = []; $permissionNameArray = array_values($permissionNameArray); // Ensure the admin system role retains vital system permissions if ($role->system_name === 'admin') { $permissionNameArray = array_unique(array_merge($permissionNameArray, [ 'users-manage', 'user-roles-manage', 'restrictions-manage-all', 'restrictions-manage-own', 'settings-manage', ])); } if (!empty($permissionNameArray)) { $permissions = RolePermission::query() ->whereIn('name', $permissionNameArray) ->pluck('id') ->toArray(); } $role->permissions()->sync($permissions); } /** * Delete a role from the system. * Check it's not an admin role or set as default before deleting. * If a migration Role ID is specified, the users assigned to the current role * will be added to the role of the specified id. * * @throws PermissionsException * @throws Exception */ public function deleteRole(int $roleId, int $migrateRoleId = 0): void { $role = $this->getRoleById($roleId); // Prevent deleting admin role or default registration role. if ($role->system_name && in_array($role->system_name, $this->systemRoles)) { throw new PermissionsException(trans('errors.role_system_cannot_be_deleted')); } elseif ($role->id === intval(setting('registration-role'))) { throw new PermissionsException(trans('errors.role_registration_default_cannot_delete')); } (new DatabaseTransaction(function () use ($migrateRoleId, $role) { if ($migrateRoleId !== 0) { $newRole = Role::query()->find($migrateRoleId); if ($newRole) { $users = $role->users()->pluck('id')->toArray(); $newRole->users()->sync($users); } } $role->entityPermissions()->delete(); $role->jointPermissions()->delete(); Activity::add(ActivityType::ROLE_DELETE, $role); $role->delete(); }))->run(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/PermissionStatus.php
app/Permissions/PermissionStatus.php
<?php namespace BookStack\Permissions; class PermissionStatus { const IMPLICIT_DENY = 0; const IMPLICIT_ALLOW = 1; const EXPLICIT_DENY = 2; const EXPLICIT_ALLOW = 3; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/SimpleEntityData.php
app/Permissions/SimpleEntityData.php
<?php namespace BookStack\Permissions; use BookStack\Entities\Models\Entity; class SimpleEntityData { public int $id; public string $type; public int $owned_by; public ?int $book_id; public ?int $chapter_id; public static function fromEntity(Entity $entity): self { $attrs = $entity->getAttributes(); $simple = new self(); $simple->id = $attrs['id']; $simple->type = $entity->getMorphClass(); $simple->owned_by = $attrs['owned_by'] ?? 0; $simple->book_id = $attrs['book_id'] ?? null; $simple->chapter_id = $attrs['chapter_id'] ?? null; return $simple; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/MassEntityPermissionEvaluator.php
app/Permissions/MassEntityPermissionEvaluator.php
<?php namespace BookStack\Permissions; use BookStack\Permissions\Models\EntityPermission; class MassEntityPermissionEvaluator extends EntityPermissionEvaluator { /** * @var SimpleEntityData[] */ protected array $entitiesInvolved; protected array $permissionMapCache; public function __construct(array $entitiesInvolved, string $action) { $this->entitiesInvolved = $entitiesInvolved; parent::__construct($action); } public function evaluateEntityForRole(SimpleEntityData $entity, int $roleId): ?int { $typeIdChain = $this->gatherEntityChainTypeIds($entity); $relevantPermissions = $this->getPermissionMapByTypeIdForChainAndRole($typeIdChain, $roleId); $permitsByType = $this->collapseAndCategorisePermissions($typeIdChain, $relevantPermissions); return $this->evaluatePermitsByType($permitsByType); } /** * @param string[] $typeIdChain * @return array<string, EntityPermission[]> */ protected function getPermissionMapByTypeIdForChainAndRole(array $typeIdChain, int $roleId): array { $allPermissions = $this->getPermissionMapByTypeIdAndRoleForAllInvolved(); $relevantPermissions = []; // Filter down permissions to just those for current typeId // and current roleID or fallback permissions. foreach ($typeIdChain as $typeId) { $relevantPermissions[$typeId] = [ ...($allPermissions[$typeId][$roleId] ?? []), ...($allPermissions[$typeId][0] ?? []) ]; } return $relevantPermissions; } /** * @return array<string, array<int, EntityPermission[]>> */ protected function getPermissionMapByTypeIdAndRoleForAllInvolved(): array { if (isset($this->permissionMapCache)) { return $this->permissionMapCache; } $entityTypeIdChain = []; foreach ($this->entitiesInvolved as $entity) { $entityTypeIdChain[] = $entity->type . ':' . $entity->id; } $permissionMap = $this->getPermissionsMapByTypeId($entityTypeIdChain, []); // Manipulate permission map to also be keyed by roleId. foreach ($permissionMap as $typeId => $permissions) { $permissionMap[$typeId] = []; foreach ($permissions as $permission) { $roleId = $permission->getRawAttribute('role_id'); if (!isset($permissionMap[$typeId][$roleId])) { $permissionMap[$typeId][$roleId] = []; } $permissionMap[$typeId][$roleId][] = $permission; } } $this->permissionMapCache = $permissionMap; return $this->permissionMapCache; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/EntityPermissionEvaluator.php
app/Permissions/EntityPermissionEvaluator.php
<?php namespace BookStack\Permissions; use BookStack\Entities\Models\Entity; use BookStack\Permissions\Models\EntityPermission; use BookStack\Users\Models\Role; use Illuminate\Database\Eloquent\Builder; class EntityPermissionEvaluator { public function __construct( protected string $action ) { } public function evaluateEntityForUser(Entity $entity, array $userRoleIds): ?bool { if ($this->isUserSystemAdmin($userRoleIds)) { return true; } $typeIdChain = $this->gatherEntityChainTypeIds(SimpleEntityData::fromEntity($entity)); $relevantPermissions = $this->getPermissionsMapByTypeId($typeIdChain, [...$userRoleIds, 0]); $permitsByType = $this->collapseAndCategorisePermissions($typeIdChain, $relevantPermissions); $status = $this->evaluatePermitsByType($permitsByType); return is_null($status) ? null : $status === PermissionStatus::IMPLICIT_ALLOW || $status === PermissionStatus::EXPLICIT_ALLOW; } /** * @param array<string, array<int, string>> $permitsByType */ protected function evaluatePermitsByType(array $permitsByType): ?int { // Return grant or reject from role-level if exists if (count($permitsByType['role']) > 0) { return max($permitsByType['role']) ? PermissionStatus::EXPLICIT_ALLOW : PermissionStatus::EXPLICIT_DENY; } // Return fallback permission if exists if (count($permitsByType['fallback']) > 0) { return $permitsByType['fallback'][0] ? PermissionStatus::IMPLICIT_ALLOW : PermissionStatus::IMPLICIT_DENY; } return null; } /** * @param string[] $typeIdChain * @param array<string, EntityPermission[]> $permissionMapByTypeId * @return array<string, array<int, string>> */ protected function collapseAndCategorisePermissions(array $typeIdChain, array $permissionMapByTypeId): array { $permitsByType = ['fallback' => [], 'role' => []]; foreach ($typeIdChain as $typeId) { $permissions = $permissionMapByTypeId[$typeId] ?? []; foreach ($permissions as $permission) { $roleId = $permission->role_id; $type = $roleId === 0 ? 'fallback' : 'role'; if (!isset($permitsByType[$type][$roleId])) { $permitsByType[$type][$roleId] = $permission->{$this->action}; } } if (isset($permitsByType['fallback'][0])) { break; } } return $permitsByType; } /** * @param string[] $typeIdChain * @return array<string, EntityPermission[]> */ protected function getPermissionsMapByTypeId(array $typeIdChain, array $filterRoleIds): array { $idsByType = []; foreach ($typeIdChain as $typeId) { [$type, $id] = explode(':', $typeId); if (!isset($idsByType[$type])) { $idsByType[$type] = []; } $idsByType[$type][] = $id; } $relevantPermissions = []; foreach ($idsByType as $type => $ids) { $idsChunked = array_chunk($ids, 10000); foreach ($idsChunked as $idChunk) { $permissions = $this->getPermissionsForEntityIdsOfType($type, $idChunk, $filterRoleIds); array_push($relevantPermissions, ...$permissions); } } $map = []; foreach ($relevantPermissions as $permission) { $key = $permission->entity_type . ':' . $permission->entity_id; if (!isset($map[$key])) { $map[$key] = []; } $map[$key][] = $permission; } return $map; } /** * @param string[] $ids * @param int[] $filterRoleIds * @return EntityPermission[] */ protected function getPermissionsForEntityIdsOfType(string $type, array $ids, array $filterRoleIds): array { $query = EntityPermission::query() ->where('entity_type', '=', $type) ->whereIn('entity_id', $ids); if (!empty($filterRoleIds)) { $query->where(function (Builder $query) use ($filterRoleIds) { $query->whereIn('role_id', [...$filterRoleIds, 0]); }); } return $query->get(['entity_id', 'entity_type', 'role_id', $this->action])->all(); } /** * @return string[] */ protected function gatherEntityChainTypeIds(SimpleEntityData $entity): array { // The array order here is very important due to the fact we walk up the chain // elsewhere in the class. Earlier items in the chain have higher priority. $chain = [$entity->type . ':' . $entity->id]; if ($entity->type === 'page' && $entity->chapter_id) { $chain[] = 'chapter:' . $entity->chapter_id; } if ($entity->type === 'page' || $entity->type === 'chapter') { $chain[] = 'book:' . $entity->book_id; } return $chain; } protected function isUserSystemAdmin($userRoleIds): bool { $adminRoleId = Role::getSystemRole('admin')->id; return in_array($adminRoleId, $userRoleIds); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/Permission.php
app/Permissions/Permission.php
<?php namespace BookStack\Permissions; /** * Enum to represent the permissions which may be used in checks. * These generally align with RolePermission names, although some are abstract or truncated as some checks * are performed across a range of different items which may be subject to inheritance and other complications. * * We use and still allow the string values in usage to allow for compatibility with scenarios where * users have customised their instance with additional permissions via the theme system. * This enum primarily exists for alignment within the codebase. * * Permissions with all/own suffixes may also be represented as a higher-level alias without the own/all * suffix, which are used and assessed in the permission system logic. */ enum Permission: string { // Generic Actions // Used for more abstract entity permission checks case View = 'view'; case Create = 'create'; case Update = 'update'; case Delete = 'delete'; // System Permissions case AccessApi = 'access-api'; case ContentExport = 'content-export'; case ContentImport = 'content-import'; case EditorChange = 'editor-change'; case ReceiveNotifications = 'receive-notifications'; case RestrictionsManage = 'restrictions-manage'; case RestrictionsManageAll = 'restrictions-manage-all'; case RestrictionsManageOwn = 'restrictions-manage-own'; case SettingsManage = 'settings-manage'; case TemplatesManage = 'templates-manage'; case UserRolesManage = 'user-roles-manage'; case UsersManage = 'users-manage'; // Non-entity content permissions case AttachmentCreate = 'attachment-create'; case AttachmentCreateAll = 'attachment-create-all'; case AttachmentCreateOwn = 'attachment-create-own'; case AttachmentDelete = 'attachment-delete'; case AttachmentDeleteAll = 'attachment-delete-all'; case AttachmentDeleteOwn = 'attachment-delete-own'; case AttachmentUpdate = 'attachment-update'; case AttachmentUpdateAll = 'attachment-update-all'; case AttachmentUpdateOwn = 'attachment-update-own'; case CommentCreateAll = 'comment-create-all'; case CommentDelete = 'comment-delete'; case CommentDeleteAll = 'comment-delete-all'; case CommentDeleteOwn = 'comment-delete-own'; case CommentUpdate = 'comment-update'; case CommentUpdateAll = 'comment-update-all'; case CommentUpdateOwn = 'comment-update-own'; case ImageCreateAll = 'image-create-all'; case ImageCreateOwn = 'image-create-own'; case ImageDelete = 'image-delete'; case ImageDeleteAll = 'image-delete-all'; case ImageDeleteOwn = 'image-delete-own'; case ImageUpdate = 'image-update'; case ImageUpdateAll = 'image-update-all'; case ImageUpdateOwn = 'image-update-own'; // Entity content permissions case BookCreate = 'book-create'; case BookCreateAll = 'book-create-all'; case BookCreateOwn = 'book-create-own'; case BookDelete = 'book-delete'; case BookDeleteAll = 'book-delete-all'; case BookDeleteOwn = 'book-delete-own'; case BookUpdate = 'book-update'; case BookUpdateAll = 'book-update-all'; case BookUpdateOwn = 'book-update-own'; case BookView = 'book-view'; case BookViewAll = 'book-view-all'; case BookViewOwn = 'book-view-own'; case BookshelfCreate = 'bookshelf-create'; case BookshelfCreateAll = 'bookshelf-create-all'; case BookshelfCreateOwn = 'bookshelf-create-own'; case BookshelfDelete = 'bookshelf-delete'; case BookshelfDeleteAll = 'bookshelf-delete-all'; case BookshelfDeleteOwn = 'bookshelf-delete-own'; case BookshelfUpdate = 'bookshelf-update'; case BookshelfUpdateAll = 'bookshelf-update-all'; case BookshelfUpdateOwn = 'bookshelf-update-own'; case BookshelfView = 'bookshelf-view'; case BookshelfViewAll = 'bookshelf-view-all'; case BookshelfViewOwn = 'bookshelf-view-own'; case ChapterCreate = 'chapter-create'; case ChapterCreateAll = 'chapter-create-all'; case ChapterCreateOwn = 'chapter-create-own'; case ChapterDelete = 'chapter-delete'; case ChapterDeleteAll = 'chapter-delete-all'; case ChapterDeleteOwn = 'chapter-delete-own'; case ChapterUpdate = 'chapter-update'; case ChapterUpdateAll = 'chapter-update-all'; case ChapterUpdateOwn = 'chapter-update-own'; case ChapterView = 'chapter-view'; case ChapterViewAll = 'chapter-view-all'; case ChapterViewOwn = 'chapter-view-own'; case PageCreate = 'page-create'; case PageCreateAll = 'page-create-all'; case PageCreateOwn = 'page-create-own'; case PageDelete = 'page-delete'; case PageDeleteAll = 'page-delete-all'; case PageDeleteOwn = 'page-delete-own'; case PageUpdate = 'page-update'; case PageUpdateAll = 'page-update-all'; case PageUpdateOwn = 'page-update-own'; case PageView = 'page-view'; case PageViewAll = 'page-view-all'; case PageViewOwn = 'page-view-own'; /** * Get the generic permissions which may be queried for entities. */ public static function genericForEntity(): array { return [ self::View, self::Create, self::Update, self::Delete, ]; } /** * Return the application permission-check middleware-string for this permission. * Uses registered CheckUserHasPermission middleware. */ public function middleware(): string { return 'can:' . $this->value; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/JointPermissionBuilder.php
app/Permissions/JointPermissionBuilder.php
<?php namespace BookStack\Permissions; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Entities\Queries\EntityQueries; use BookStack\Permissions\Models\JointPermission; use BookStack\Users\Models\Role; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Support\Facades\DB; /** * Joint permissions provide a pre-query "cached" table of view permissions for all core entity * types for all roles in the system. This class generates out that table for different scenarios. */ class JointPermissionBuilder { public function __construct( protected EntityQueries $queries, ) { } /** * Re-generate all entity permission from scratch. */ public function rebuildForAll(): void { JointPermission::query()->truncate(); // Get all roles (Should be the most limited dimension) $roles = Role::query()->with('permissions')->get()->all(); // Chunk through all books $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) { $this->buildJointPermissionsForBooks($books, $roles); }); // Chunk through all bookshelves $this->queries->shelves->start()->withTrashed()->select(['id', 'owned_by']) ->chunk(50, function (EloquentCollection $shelves) use ($roles) { $this->createManyJointPermissions($shelves->all(), $roles); }); } /** * Rebuild the entity jointPermissions for a particular entity. */ public function rebuildForEntity(Entity $entity): void { $entities = [$entity]; if ($entity instanceof Book) { $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get(); $this->buildJointPermissionsForBooks($books, Role::query()->with('permissions')->get()->all(), true); return; } /** @var BookChild $entity */ if ($entity->book) { $entities[] = $entity->book; } if ($entity instanceof Page && $entity->chapter_id) { $entities[] = $entity->chapter; } if ($entity instanceof Chapter) { foreach ($entity->pages as $page) { $entities[] = $page; } } $this->buildJointPermissionsForEntities($entities); } /** * Build the entity jointPermissions for a particular role. */ public function rebuildForRole(Role $role) { $roles = [$role]; $role->jointPermissions()->delete(); $role->load('permissions'); // Chunk through all books $this->bookFetchQuery()->chunk(10, function ($books) use ($roles) { $this->buildJointPermissionsForBooks($books, $roles); }); // Chunk through all bookshelves $this->queries->shelves->start()->select(['id', 'owned_by']) ->chunk(100, function ($shelves) use ($roles) { $this->createManyJointPermissions($shelves->all(), $roles); }); } /** * Get a query for fetching a book with its children. */ protected function bookFetchQuery(): Builder { return $this->queries->books->start()->withTrashed() ->select(['id', 'owned_by'])->with([ 'chapters' => function ($query) { $query->withTrashed()->select(['id', 'owned_by', 'book_id']); }, 'pages' => function ($query) { $query->withTrashed()->select(['id', 'owned_by', 'book_id', 'chapter_id']); }, ]); } /** * Build joint permissions for the given book and role combinations. */ protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false): void { $entities = clone $books; /** @var Book $book */ foreach ($books->all() as $book) { foreach ($book->getRelation('chapters') as $chapter) { $entities->push($chapter); } foreach ($book->getRelation('pages') as $page) { $entities->push($page); } } if ($deleteOld) { $this->deleteManyJointPermissionsForEntities($entities->all()); } $this->createManyJointPermissions($entities->all(), $roles); } /** * Rebuild the entity jointPermissions for a collection of entities. */ protected function buildJointPermissionsForEntities(array $entities): void { $roles = Role::query()->get()->values()->all(); $this->deleteManyJointPermissionsForEntities($entities); $this->createManyJointPermissions($entities, $roles); } /** * Delete all the entity jointPermissions for a list of entities. * * @param Entity[] $entities */ protected function deleteManyJointPermissionsForEntities(array $entities): void { $simpleEntities = $this->entitiesToSimpleEntities($entities); $idsByType = $this->entitiesToTypeIdMap($simpleEntities); foreach ($idsByType as $type => $ids) { foreach (array_chunk($ids, 1000) as $idChunk) { DB::table('joint_permissions') ->where('entity_type', '=', $type) ->whereIn('entity_id', $idChunk) ->delete(); } } } /** * @param Entity[] $entities * * @return SimpleEntityData[] */ protected function entitiesToSimpleEntities(array $entities): array { $simpleEntities = []; foreach ($entities as $entity) { $simple = SimpleEntityData::fromEntity($entity); $simpleEntities[] = $simple; } return $simpleEntities; } /** * Create & Save entity jointPermissions for many entities and roles. * * @param Entity[] $originalEntities * @param Role[] $roles */ protected function createManyJointPermissions(array $originalEntities, array $roles): void { $entities = $this->entitiesToSimpleEntities($originalEntities); $jointPermissions = []; // Fetch related entity permissions $permissions = new MassEntityPermissionEvaluator($entities, 'view'); // Create a mapping of role permissions $rolePermissionMap = []; foreach ($roles as $role) { foreach ($role->permissions as $permission) { $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true; } } // Create Joint Permission Data foreach ($entities as $entity) { foreach ($roles as $role) { $jp = $this->createJointPermissionData( $entity, $role->getRawAttribute('id'), $permissions, $rolePermissionMap, $role->system_name === 'admin' ); $jointPermissions[] = $jp; } } foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) { DB::table('joint_permissions')->insert($jointPermissionChunk); } } /** * From the given entity list, provide back a mapping of entity types to * the ids of that given type. The type used is the DB morph class. * * @param SimpleEntityData[] $entities * * @return array<string, int[]> */ protected function entitiesToTypeIdMap(array $entities): array { $idsByType = []; foreach ($entities as $entity) { if (!isset($idsByType[$entity->type])) { $idsByType[$entity->type] = []; } $idsByType[$entity->type][] = $entity->id; } return $idsByType; } /** * Create entity permission data for an entity and role * for a particular action. */ protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, MassEntityPermissionEvaluator $permissionMap, array $rolePermissionMap, bool $isAdminRole): array { // Ensure system admin role retains permissions if ($isAdminRole) { return $this->createJointPermissionDataArray($entity, $roleId, PermissionStatus::EXPLICIT_ALLOW, true); } // Return evaluated entity permission status if it has an affect. $entityPermissionStatus = $permissionMap->evaluateEntityForRole($entity, $roleId); if ($entityPermissionStatus !== null) { return $this->createJointPermissionDataArray($entity, $roleId, $entityPermissionStatus, false); } // Otherwise default to the role-level permissions $permissionPrefix = $entity->type . '-view'; $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']); $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']); $status = $roleHasPermission ? PermissionStatus::IMPLICIT_ALLOW : PermissionStatus::IMPLICIT_DENY; return $this->createJointPermissionDataArray($entity, $roleId, $status, $roleHasPermissionOwn); } /** * Create an array of data with the information of an entity jointPermissions. * Used to build data for bulk insertion. */ protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, int $permissionStatus, bool $hasPermissionOwn): array { $ownPermissionActive = ($hasPermissionOwn && $permissionStatus !== PermissionStatus::EXPLICIT_DENY && $entity->owned_by); return [ 'entity_id' => $entity->id, 'entity_type' => $entity->type, 'role_id' => $roleId, 'status' => $permissionStatus, 'owner_id' => $ownPermissionActive ? $entity->owned_by : null, ]; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/PermissionsController.php
app/Permissions/PermissionsController.php
<?php namespace BookStack\Permissions; use BookStack\Entities\Queries\EntityQueries; use BookStack\Entities\Tools\PermissionsUpdater; use BookStack\Http\Controller; use BookStack\Permissions\Models\EntityPermission; use BookStack\Users\Models\Role; use BookStack\Util\DatabaseTransaction; use Illuminate\Http\Request; class PermissionsController extends Controller { public function __construct( protected PermissionsUpdater $permissionsUpdater, protected EntityQueries $queries, ) { } /** * Show the permissions view for a page. */ public function showForPage(string $bookSlug, string $pageSlug) { $page = $this->queries->pages->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $this->checkOwnablePermission(Permission::RestrictionsManage, $page); $this->setPageTitle(trans('entities.pages_permissions')); return view('pages.permissions', [ 'page' => $page, 'data' => new PermissionFormData($page), ]); } /** * Set the permissions for a page. */ public function updateForPage(Request $request, string $bookSlug, string $pageSlug) { $page = $this->queries->pages->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $this->checkOwnablePermission(Permission::RestrictionsManage, $page); (new DatabaseTransaction(function () use ($page, $request) { $this->permissionsUpdater->updateFromPermissionsForm($page, $request); }))->run(); $this->showSuccessNotification(trans('entities.pages_permissions_success')); return redirect($page->getUrl()); } /** * Show the permissions view for a chapter. */ public function showForChapter(string $bookSlug, string $chapterSlug) { $chapter = $this->queries->chapters->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $this->checkOwnablePermission(Permission::RestrictionsManage, $chapter); $this->setPageTitle(trans('entities.chapters_permissions')); return view('chapters.permissions', [ 'chapter' => $chapter, 'data' => new PermissionFormData($chapter), ]); } /** * Set the permissions for a chapter. */ public function updateForChapter(Request $request, string $bookSlug, string $chapterSlug) { $chapter = $this->queries->chapters->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $this->checkOwnablePermission(Permission::RestrictionsManage, $chapter); (new DatabaseTransaction(function () use ($chapter, $request) { $this->permissionsUpdater->updateFromPermissionsForm($chapter, $request); }))->run(); $this->showSuccessNotification(trans('entities.chapters_permissions_success')); return redirect($chapter->getUrl()); } /** * Show the permissions view for a book. */ public function showForBook(string $slug) { $book = $this->queries->books->findVisibleBySlugOrFail($slug); $this->checkOwnablePermission(Permission::RestrictionsManage, $book); $this->setPageTitle(trans('entities.books_permissions')); return view('books.permissions', [ 'book' => $book, 'data' => new PermissionFormData($book), ]); } /** * Set the permissions for a book. */ public function updateForBook(Request $request, string $slug) { $book = $this->queries->books->findVisibleBySlugOrFail($slug); $this->checkOwnablePermission(Permission::RestrictionsManage, $book); (new DatabaseTransaction(function () use ($book, $request) { $this->permissionsUpdater->updateFromPermissionsForm($book, $request); }))->run(); $this->showSuccessNotification(trans('entities.books_permissions_updated')); return redirect($book->getUrl()); } /** * Show the permissions view for a shelf. */ public function showForShelf(string $slug) { $shelf = $this->queries->shelves->findVisibleBySlugOrFail($slug); $this->checkOwnablePermission(Permission::RestrictionsManage, $shelf); $this->setPageTitle(trans('entities.shelves_permissions')); return view('shelves.permissions', [ 'shelf' => $shelf, 'data' => new PermissionFormData($shelf), ]); } /** * Set the permissions for a shelf. */ public function updateForShelf(Request $request, string $slug) { $shelf = $this->queries->shelves->findVisibleBySlugOrFail($slug); $this->checkOwnablePermission(Permission::RestrictionsManage, $shelf); (new DatabaseTransaction(function () use ($shelf, $request) { $this->permissionsUpdater->updateFromPermissionsForm($shelf, $request); }))->run(); $this->showSuccessNotification(trans('entities.shelves_permissions_updated')); return redirect($shelf->getUrl()); } /** * Copy the permissions of a bookshelf to the child books. */ public function copyShelfPermissionsToBooks(string $slug) { $shelf = $this->queries->shelves->findVisibleBySlugOrFail($slug); $this->checkOwnablePermission(Permission::RestrictionsManage, $shelf); $updateCount = (new DatabaseTransaction(function () use ($shelf) { return $this->permissionsUpdater->updateBookPermissionsFromShelf($shelf); }))->run(); $this->showSuccessNotification(trans('entities.shelves_copy_permission_success', ['count' => $updateCount])); return redirect($shelf->getUrl()); } /** * Get an empty entity permissions form row for the given role. */ public function formRowForRole(string $entityType, string $roleId) { $this->checkPermissionOr(Permission::RestrictionsManageAll, fn() => userCan(Permission::RestrictionsManageOwn)); $role = Role::query()->findOrFail($roleId); return view('form.entity-permissions-row', [ 'role' => $role, 'permission' => new EntityPermission(), 'entityType' => $entityType, 'inheriting' => false, ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/Models/JointPermission.php
app/Permissions/Models/JointPermission.php
<?php namespace BookStack\Permissions\Models; use BookStack\App\Model; use BookStack\Entities\Models\Entity; use BookStack\Users\Models\Role; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\MorphOne; class JointPermission extends Model { protected $primaryKey = null; public $timestamps = false; /** * Get the role that this points to. */ public function role(): BelongsTo { return $this->belongsTo(Role::class); } /** * Get the entity this points to. */ public function entity(): MorphOne { return $this->morphOne(Entity::class, 'entity'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/Models/RolePermission.php
app/Permissions/Models/RolePermission.php
<?php namespace BookStack\Permissions\Models; use BookStack\App\Model; use BookStack\Users\Models\Role; use Illuminate\Database\Eloquent\Relations\BelongsToMany; /** * @property int $id * @property string $name */ class RolePermission extends Model { /** * The roles that belong to the permission. */ public function roles(): BelongsToMany { return $this->belongsToMany(Role::class, 'permission_role', 'permission_id', 'role_id'); } /** * Get the permission object by name. */ public static function getByName(string $name): ?RolePermission { return static::where('name', '=', $name)->first(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Permissions/Models/EntityPermission.php
app/Permissions/Models/EntityPermission.php
<?php namespace BookStack\Permissions\Models; use BookStack\App\Model; use BookStack\Users\Models\Role; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * @property int $id * @property int $role_id * @property int $entity_id * @property string $entity_type * @property boolean $view * @property boolean $create * @property boolean $update * @property boolean $delete */ class EntityPermission extends Model { protected $fillable = ['role_id', 'view', 'create', 'update', 'delete']; public $timestamps = false; protected $hidden = ['entity_id', 'entity_type', 'id']; protected $casts = [ 'view' => 'boolean', 'create' => 'boolean', 'read' => 'boolean', 'update' => 'boolean', 'delete' => 'boolean', ]; /** * Get the role assigned to this entity permission. */ public function role(): BelongsTo { return $this->belongsTo(Role::class); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/PdfGenerator.php
app/Exports/PdfGenerator.php
<?php namespace BookStack\Exports; use BookStack\Exceptions\PdfExportException; use Dompdf\Dompdf; use Knp\Snappy\Pdf as SnappyPdf; use Symfony\Component\Process\Exception\ProcessTimedOutException; use Symfony\Component\Process\Process; class PdfGenerator { const ENGINE_DOMPDF = 'dompdf'; const ENGINE_WKHTML = 'wkhtml'; const ENGINE_COMMAND = 'command'; /** * Generate PDF content from the given HTML content. * @throws PdfExportException */ public function fromHtml(string $html): string { return match ($this->getActiveEngine()) { self::ENGINE_COMMAND => $this->renderUsingCommand($html), self::ENGINE_WKHTML => $this->renderUsingWkhtml($html), default => $this->renderUsingDomPdf($html) }; } /** * Get the currently active PDF engine. * Returns the value of an `ENGINE_` const on this class. */ public function getActiveEngine(): string { if (config('exports.pdf_command')) { return self::ENGINE_COMMAND; } if ($this->getWkhtmlBinaryPath() && config('app.allow_untrusted_server_fetching') === true) { return self::ENGINE_WKHTML; } return self::ENGINE_DOMPDF; } protected function getWkhtmlBinaryPath(): string { $wkhtmlBinaryPath = config('exports.snappy.pdf_binary'); if (file_exists(base_path('wkhtmltopdf'))) { $wkhtmlBinaryPath = base_path('wkhtmltopdf'); } return $wkhtmlBinaryPath ?: ''; } protected function renderUsingDomPdf(string $html): string { $options = config('exports.dompdf'); $domPdf = new Dompdf($options); $domPdf->setBasePath(base_path('public')); $domPdf->loadHTML($this->convertEntities($html)); $domPdf->render(); return (string) $domPdf->output(); } /** * @throws PdfExportException */ protected function renderUsingCommand(string $html): string { $command = config('exports.pdf_command'); $inputHtml = tempnam(sys_get_temp_dir(), 'bs-pdfgen-html-'); $outputPdf = tempnam(sys_get_temp_dir(), 'bs-pdfgen-output-'); $replacementsByPlaceholder = [ '{input_html_path}' => $inputHtml, '{output_pdf_path}' => $outputPdf, ]; foreach ($replacementsByPlaceholder as $placeholder => $replacement) { $command = str_replace($placeholder, escapeshellarg($replacement), $command); } file_put_contents($inputHtml, $html); $timeout = intval(config('exports.pdf_command_timeout')); $process = Process::fromShellCommandline($command); $process->setTimeout($timeout); $cleanup = function () use ($inputHtml, $outputPdf) { foreach ([$inputHtml, $outputPdf] as $file) { if (file_exists($file)) { unlink($file); } } }; try { $process->run(); } catch (ProcessTimedOutException $e) { $cleanup(); throw new PdfExportException("PDF Export via command failed due to timeout at {$timeout} second(s)"); } if (!$process->isSuccessful()) { $cleanup(); throw new PdfExportException("PDF Export via command failed with exit code {$process->getExitCode()}, stdout: {$process->getOutput()}, stderr: {$process->getErrorOutput()}"); } $pdfContents = file_get_contents($outputPdf); $cleanup(); if ($pdfContents === false) { throw new PdfExportException("PDF Export via command failed, unable to read PDF output file"); } else if (empty($pdfContents)) { throw new PdfExportException("PDF Export via command failed, PDF output file is empty"); } return $pdfContents; } protected function renderUsingWkhtml(string $html): string { $snappy = new SnappyPdf($this->getWkhtmlBinaryPath()); $options = config('exports.snappy.options'); return $snappy->getOutputFromHtml($html, $options); } /** * Taken from https://github.com/barryvdh/laravel-dompdf/blob/v2.1.1/src/PDF.php * Copyright (c) 2021 barryvdh, MIT License * https://github.com/barryvdh/laravel-dompdf/blob/v2.1.1/LICENSE */ protected function convertEntities(string $subject): string { $entities = [ '€' => '&euro;', '£' => '&pound;', ]; foreach ($entities as $search => $replace) { $subject = str_replace($search, $replace, $subject); } return $subject; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ExportFormatter.php
app/Exports/ExportFormatter.php
<?php namespace BookStack\Exports; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use BookStack\Entities\Tools\BookContents; use BookStack\Entities\Tools\Markdown\HtmlToMarkdown; use BookStack\Entities\Tools\PageContent; use BookStack\Uploads\ImageService; use BookStack\Util\CspService; use BookStack\Util\HtmlDocument; use DOMElement; use Exception; use Throwable; class ExportFormatter { public function __construct( protected ImageService $imageService, protected PdfGenerator $pdfGenerator, protected CspService $cspService ) { } /** * Convert a page to a self-contained HTML file. * Includes required CSS & image content. Images are base64 encoded into the HTML. * * @throws Throwable */ public function pageToContainedHtml(Page $page): string { $page->html = (new PageContent($page))->render(); $pageHtml = view('exports.page', [ 'page' => $page, 'format' => 'html', 'cspContent' => $this->cspService->getCspMetaTagValue(), 'locale' => user()->getLocale(), ])->render(); return $this->containHtml($pageHtml); } /** * Convert a chapter to a self-contained HTML file. * * @throws Throwable */ public function chapterToContainedHtml(Chapter $chapter): string { $pages = $chapter->getVisiblePages(); $pages->each(function ($page) { $page->html = (new PageContent($page))->render(); }); $html = view('exports.chapter', [ 'chapter' => $chapter, 'pages' => $pages, 'format' => 'html', 'cspContent' => $this->cspService->getCspMetaTagValue(), 'locale' => user()->getLocale(), ])->render(); return $this->containHtml($html); } /** * Convert a book to a self-contained HTML file. * * @throws Throwable */ public function bookToContainedHtml(Book $book): string { $bookTree = (new BookContents($book))->getTree(false, true); $html = view('exports.book', [ 'book' => $book, 'bookChildren' => $bookTree, 'format' => 'html', 'cspContent' => $this->cspService->getCspMetaTagValue(), 'locale' => user()->getLocale(), ])->render(); return $this->containHtml($html); } /** * Convert a page to a PDF file. * * @throws Throwable */ public function pageToPdf(Page $page): string { $page->html = (new PageContent($page))->render(); $html = view('exports.page', [ 'page' => $page, 'format' => 'pdf', 'engine' => $this->pdfGenerator->getActiveEngine(), 'locale' => user()->getLocale(), ])->render(); return $this->htmlToPdf($html); } /** * Convert a chapter to a PDF file. * * @throws Throwable */ public function chapterToPdf(Chapter $chapter): string { $pages = $chapter->getVisiblePages(); $pages->each(function ($page) { $page->html = (new PageContent($page))->render(); }); $html = view('exports.chapter', [ 'chapter' => $chapter, 'pages' => $pages, 'format' => 'pdf', 'engine' => $this->pdfGenerator->getActiveEngine(), 'locale' => user()->getLocale(), ])->render(); return $this->htmlToPdf($html); } /** * Convert a book to a PDF file. * * @throws Throwable */ public function bookToPdf(Book $book): string { $bookTree = (new BookContents($book))->getTree(false, true); $html = view('exports.book', [ 'book' => $book, 'bookChildren' => $bookTree, 'format' => 'pdf', 'engine' => $this->pdfGenerator->getActiveEngine(), 'locale' => user()->getLocale(), ])->render(); return $this->htmlToPdf($html); } /** * Convert normal web-page HTML to a PDF. * * @throws Exception */ protected function htmlToPdf(string $html): string { $html = $this->containHtml($html); $doc = new HtmlDocument(); $doc->loadCompleteHtml($html); $this->replaceIframesWithLinks($doc); $this->openDetailElements($doc); $cleanedHtml = $doc->getHtml(); return $this->pdfGenerator->fromHtml($cleanedHtml); } /** * Within the given HTML content, Open any detail blocks. */ protected function openDetailElements(HtmlDocument $doc): void { $details = $doc->queryXPath('//details'); /** @var DOMElement $detail */ foreach ($details as $detail) { $detail->setAttribute('open', 'open'); } } /** * Within the given HTML document, replace any iframe elements * with anchor links within paragraph blocks. */ protected function replaceIframesWithLinks(HtmlDocument $doc): void { $iframes = $doc->queryXPath('//iframe'); /** @var DOMElement $iframe */ foreach ($iframes as $iframe) { $link = $iframe->getAttribute('src'); if (str_starts_with($link, '//')) { $link = 'https:' . $link; } $anchor = $doc->createElement('a', $link); $anchor->setAttribute('href', $link); $paragraph = $doc->createElement('p'); $paragraph->appendChild($anchor); $iframe->parentNode->replaceChild($paragraph, $iframe); } } /** * Bundle of the contents of a html file to be self-contained. * * @throws Exception */ protected function containHtml(string $htmlContent): string { $imageTagsOutput = []; preg_match_all("/\<img.*?src\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $imageTagsOutput); // Replace image src with base64 encoded image strings if (isset($imageTagsOutput[0]) && count($imageTagsOutput[0]) > 0) { foreach ($imageTagsOutput[0] as $index => $imgMatch) { $oldImgTagString = $imgMatch; $srcString = $imageTagsOutput[2][$index]; $imageEncoded = $this->imageService->imageUrlToBase64($srcString); if ($imageEncoded === null) { $imageEncoded = $srcString; } $newImgTagString = str_replace($srcString, $imageEncoded, $oldImgTagString); $htmlContent = str_replace($oldImgTagString, $newImgTagString, $htmlContent); } } $linksOutput = []; preg_match_all("/\<a.*href\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $linksOutput); // Update relative links to be absolute, with instance url if (isset($linksOutput[0]) && count($linksOutput[0]) > 0) { foreach ($linksOutput[0] as $index => $linkMatch) { $oldLinkString = $linkMatch; $srcString = $linksOutput[2][$index]; if (!str_starts_with(trim($srcString), 'http')) { $newSrcString = url($srcString); $newLinkString = str_replace($srcString, $newSrcString, $oldLinkString); $htmlContent = str_replace($oldLinkString, $newLinkString, $htmlContent); } } } return $htmlContent; } /** * Converts the page contents into simple plain text. * This method filters any bad looking content to provide a nice final output. */ public function pageToPlainText(Page $page, bool $pageRendered = false, bool $fromParent = false): string { $html = $pageRendered ? $page->html : (new PageContent($page))->render(); // Add proceeding spaces before tags so spaces remain between // text within elements after stripping tags. $html = str_replace('<', " <", $html); $text = trim(strip_tags($html)); // Replace multiple spaces with single spaces $text = preg_replace('/ {2,}/', ' ', $text); // Reduce multiple horrid whitespace characters. $text = preg_replace('/(\x0A|\xA0|\x0A|\r|\n){2,}/su', "\n\n", $text); $text = html_entity_decode($text); // Add title $text = $page->name . ($fromParent ? "\n" : "\n\n") . $text; return $text; } /** * Convert a chapter into a plain text string. */ public function chapterToPlainText(Chapter $chapter): string { $text = $chapter->name . "\n" . $chapter->description; $text = trim($text) . "\n\n"; $parts = []; foreach ($chapter->getVisiblePages() as $page) { $parts[] = $this->pageToPlainText($page, false, true); } return $text . implode("\n\n", $parts); } /** * Convert a book into a plain text string. */ public function bookToPlainText(Book $book): string { $bookTree = (new BookContents($book))->getTree(false, true); $text = $book->name . "\n" . $book->descriptionInfo()->getPlain(); $text = rtrim($text) . "\n\n"; $parts = []; foreach ($bookTree as $bookChild) { if ($bookChild->isA('chapter')) { $parts[] = $this->chapterToPlainText($bookChild); } else { $parts[] = $this->pageToPlainText($bookChild, true, true); } } return $text . implode("\n\n", $parts); } /** * Convert a page to a Markdown file. */ public function pageToMarkdown(Page $page): string { if ($page->markdown) { return '# ' . $page->name . "\n\n" . $page->markdown; } return '# ' . $page->name . "\n\n" . (new HtmlToMarkdown($page->html))->convert(); } /** * Convert a chapter to a Markdown file. */ public function chapterToMarkdown(Chapter $chapter): string { $text = '# ' . $chapter->name . "\n\n"; $description = (new HtmlToMarkdown($chapter->descriptionInfo()->getHtml()))->convert(); if ($description) { $text .= $description . "\n\n"; } foreach ($chapter->pages as $page) { $text .= $this->pageToMarkdown($page) . "\n\n"; } return trim($text); } /** * Convert a book into a plain text string. */ public function bookToMarkdown(Book $book): string { $bookTree = (new BookContents($book))->getTree(false, true); $text = '# ' . $book->name . "\n\n"; $description = (new HtmlToMarkdown($book->descriptionInfo()->getHtml()))->convert(); if ($description) { $text .= $description . "\n\n"; } foreach ($bookTree as $bookChild) { if ($bookChild instanceof Chapter) { $text .= $this->chapterToMarkdown($bookChild) . "\n\n"; } else { $text .= $this->pageToMarkdown($bookChild) . "\n\n"; } } return trim($text); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ImportRepo.php
app/Exports/ImportRepo.php
<?php namespace BookStack\Exports; use BookStack\Activity\ActivityType; use BookStack\Entities\Models\Entity; use BookStack\Entities\Queries\EntityQueries; use BookStack\Exceptions\FileUploadException; use BookStack\Exceptions\ZipExportException; use BookStack\Exceptions\ZipImportException; use BookStack\Exceptions\ZipValidationException; use BookStack\Exports\ZipExports\Models\ZipExportBook; use BookStack\Exports\ZipExports\Models\ZipExportChapter; use BookStack\Exports\ZipExports\Models\ZipExportPage; use BookStack\Exports\ZipExports\ZipExportReader; use BookStack\Exports\ZipExports\ZipExportValidator; use BookStack\Exports\ZipExports\ZipImportRunner; use BookStack\Facades\Activity; use BookStack\Permissions\Permission; use BookStack\Uploads\FileStorage; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\DB; use Symfony\Component\HttpFoundation\File\UploadedFile; class ImportRepo { public function __construct( protected FileStorage $storage, protected ZipImportRunner $importer, protected EntityQueries $entityQueries, ) { } /** * @return Collection<Import> */ public function getVisibleImports(): Collection { return $this->queryVisible()->get(); } /** * @return Builder<Import> */ public function queryVisible(): Builder { $query = Import::query(); if (!userCan(Permission::SettingsManage)) { $query->where('created_by', user()->id); } return $query; } public function findVisible(int $id): Import { $query = Import::query(); if (!userCan(Permission::SettingsManage)) { $query->where('created_by', user()->id); } return $query->findOrFail($id); } /** * @throws FileUploadException * @throws ZipValidationException * @throws ZipExportException */ public function storeFromUpload(UploadedFile $file): Import { $zipPath = $file->getRealPath(); $reader = new ZipExportReader($zipPath); $errors = (new ZipExportValidator($reader))->validate(); if ($errors) { throw new ZipValidationException($errors); } $exportModel = $reader->decodeDataToExportModel(); $import = new Import(); $import->type = match (get_class($exportModel)) { ZipExportPage::class => 'page', ZipExportChapter::class => 'chapter', ZipExportBook::class => 'book', }; $import->name = $exportModel->name; $import->created_by = user()->id; $import->size = filesize($zipPath); $exportModel->metadataOnly(); $import->metadata = json_encode($exportModel); $path = $this->storage->uploadFile( $file, 'uploads/files/imports/', '', 'zip' ); $import->path = $path; $import->save(); Activity::add(ActivityType::IMPORT_CREATE, $import); return $import; } /** * @throws ZipImportException */ public function runImport(Import $import, ?string $parent = null): Entity { $parentModel = null; if ($import->type === 'page' || $import->type === 'chapter') { $parentModel = $parent ? $this->entityQueries->findVisibleByStringIdentifier($parent) : null; } DB::beginTransaction(); try { $model = $this->importer->run($import, $parentModel); } catch (ZipImportException $e) { DB::rollBack(); $this->importer->revertStoredFiles(); throw $e; } DB::commit(); $this->deleteImport($import); Activity::add(ActivityType::IMPORT_RUN, $import); return $model; } public function deleteImport(Import $import): void { $this->storage->delete($import->path); $import->delete(); Activity::add(ActivityType::IMPORT_DELETE, $import); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/Import.php
app/Exports/Import.php
<?php namespace BookStack\Exports; use BookStack\Activity\Models\Loggable; use BookStack\Exports\ZipExports\Models\ZipExportBook; use BookStack\Exports\ZipExports\Models\ZipExportChapter; use BookStack\Exports\ZipExports\Models\ZipExportPage; use BookStack\Users\Models\User; use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * @property int $id * @property string $path * @property string $name * @property int $size - ZIP size in bytes * @property string $type * @property string $metadata * @property int $created_by * @property Carbon $created_at * @property Carbon $updated_at * @property User $createdBy */ class Import extends Model implements Loggable { use HasFactory; protected $hidden = ['metadata']; public function getSizeString(): string { $mb = round($this->size / 1000000, 2); return "{$mb} MB"; } /** * Get the URL to view/continue this import. */ public function getUrl(string $path = ''): string { $path = ltrim($path, '/'); return url("/import/{$this->id}" . ($path ? '/' . $path : '')); } public function logDescriptor(): string { return "({$this->id}) {$this->name}"; } public function createdBy(): BelongsTo { return $this->belongsTo(User::class, 'created_by'); } public function decodeMetadata(): ZipExportBook|ZipExportChapter|ZipExportPage|null { $metadataArray = json_decode($this->metadata, true); return match ($this->type) { 'book' => ZipExportBook::fromArray($metadataArray), 'chapter' => ZipExportChapter::fromArray($metadataArray), 'page' => ZipExportPage::fromArray($metadataArray), default => null, }; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/Controllers/PageExportController.php
app/Exports/Controllers/PageExportController.php
<?php namespace BookStack\Exports\Controllers; use BookStack\Entities\Queries\PageQueries; use BookStack\Entities\Tools\PageContent; use BookStack\Exceptions\NotFoundException; use BookStack\Exports\ExportFormatter; use BookStack\Exports\ZipExports\ZipExportBuilder; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use Throwable; class PageExportController extends Controller { public function __construct( protected PageQueries $queries, protected ExportFormatter $exportFormatter, ) { $this->middleware(Permission::ContentExport->middleware()); $this->middleware('throttle:exports'); } /** * Exports a page to a PDF. * https://github.com/barryvdh/laravel-dompdf. * * @throws NotFoundException * @throws Throwable */ public function pdf(string $bookSlug, string $pageSlug) { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $page->html = (new PageContent($page))->render(); $pdfContent = $this->exportFormatter->pageToPdf($page); return $this->download()->directly($pdfContent, $pageSlug . '.pdf'); } /** * Export a page to a self-contained HTML file. * * @throws NotFoundException * @throws Throwable */ public function html(string $bookSlug, string $pageSlug) { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $page->html = (new PageContent($page))->render(); $containedHtml = $this->exportFormatter->pageToContainedHtml($page); return $this->download()->directly($containedHtml, $pageSlug . '.html'); } /** * Export a page to a simple plaintext .txt file. * * @throws NotFoundException */ public function plainText(string $bookSlug, string $pageSlug) { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $pageText = $this->exportFormatter->pageToPlainText($page); return $this->download()->directly($pageText, $pageSlug . '.txt'); } /** * Export a page to a simple markdown .md file. * * @throws NotFoundException */ public function markdown(string $bookSlug, string $pageSlug) { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $pageText = $this->exportFormatter->pageToMarkdown($page); return $this->download()->directly($pageText, $pageSlug . '.md'); } /** * Export a page to a contained ZIP export file. * @throws NotFoundException */ public function zip(string $bookSlug, string $pageSlug, ZipExportBuilder $builder) { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $zip = $builder->buildForPage($page); return $this->download()->streamedFileDirectly($zip, $pageSlug . '.zip', true); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/Controllers/ImportApiController.php
app/Exports/Controllers/ImportApiController.php
<?php declare(strict_types=1); namespace BookStack\Exports\Controllers; use BookStack\Exceptions\ZipImportException; use BookStack\Exceptions\ZipValidationException; use BookStack\Exports\ImportRepo; use BookStack\Http\ApiController; use BookStack\Permissions\Permission; use BookStack\Uploads\AttachmentService; use Illuminate\Http\Request; use Illuminate\Http\JsonResponse; use Illuminate\Http\Response; class ImportApiController extends ApiController { public function __construct( protected ImportRepo $imports, ) { $this->middleware(Permission::ContentImport->middleware()); } /** * List existing ZIP imports visible to the user. * Requires permission to import content. */ public function list(): JsonResponse { $query = $this->imports->queryVisible(); return $this->apiListingResponse($query, [ 'id', 'name', 'size', 'type', 'created_by', 'created_at', 'updated_at' ]); } /** * Start a new import from a ZIP file. * This does not actually run the import since that is performed via the "run" endpoint. * This uploads, validates and stores the ZIP file so it's ready to be imported. * * This "file" parameter must be a BookStack-compatible ZIP file, and this must be * sent via a 'multipart/form-data' type request. * * Requires permission to import content. */ public function create(Request $request): JsonResponse { $this->validate($request, $this->rules()['create']); $file = $request->file('file'); try { $import = $this->imports->storeFromUpload($file); } catch (ZipValidationException $exception) { $message = "ZIP upload failed with the following validation errors: \n" . $this->formatErrors($exception->errors); return $this->jsonError($message, 422); } return response()->json($import); } /** * Read details of a pending ZIP import. * The "details" property contains high-level metadata regarding the ZIP import content, * and the structure of this will change depending on import "type". * Requires permission to import content. */ public function read(int $id): JsonResponse { $import = $this->imports->findVisible($id); $import->setAttribute('details', $import->decodeMetadata()); return response()->json($import); } /** * Run the import process for an uploaded ZIP import. * The "parent_id" and "parent_type" parameters are required when the import type is "chapter" or "page". * On success, this endpoint returns the imported item. * Requires permission to import content. */ public function run(int $id, Request $request): JsonResponse { $import = $this->imports->findVisible($id); $parent = null; $rules = $this->rules()['run']; if ($import->type === 'page' || $import->type === 'chapter') { $rules['parent_type'][] = 'required'; $rules['parent_id'][] = 'required'; $data = $this->validate($request, $rules); $parent = "{$data['parent_type']}:{$data['parent_id']}"; } try { $entity = $this->imports->runImport($import, $parent); } catch (ZipImportException $exception) { $message = "ZIP import failed with the following errors: \n" . $this->formatErrors($exception->errors); return $this->jsonError($message); } return response()->json($entity->withoutRelations()); } /** * Delete a pending ZIP import from the system. * Requires permission to import content. */ public function delete(int $id): Response { $import = $this->imports->findVisible($id); $this->imports->deleteImport($import); return response('', 204); } protected function rules(): array { return [ 'create' => [ 'file' => ['required', ...AttachmentService::getFileValidationRules()], ], 'run' => [ 'parent_type' => ['string', 'in:book,chapter'], 'parent_id' => ['int'], ], ]; } protected function formatErrors(array $errors): string { $parts = []; foreach ($errors as $key => $error) { if (is_string($key)) { $parts[] = "[{$key}] {$error}"; } else { $parts[] = $error; } } return implode("\n", $parts); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/Controllers/ChapterExportApiController.php
app/Exports/Controllers/ChapterExportApiController.php
<?php namespace BookStack\Exports\Controllers; use BookStack\Entities\Queries\ChapterQueries; use BookStack\Exports\ExportFormatter; use BookStack\Exports\ZipExports\ZipExportBuilder; use BookStack\Http\ApiController; use BookStack\Permissions\Permission; use Throwable; class ChapterExportApiController extends ApiController { public function __construct( protected ExportFormatter $exportFormatter, protected ChapterQueries $queries, ) { $this->middleware(Permission::ContentExport->middleware()); } /** * Export a chapter as a PDF file. * * @throws Throwable */ public function exportPdf(int $id) { $chapter = $this->queries->findVisibleByIdOrFail($id); $pdfContent = $this->exportFormatter->chapterToPdf($chapter); return $this->download()->directly($pdfContent, $chapter->slug . '.pdf'); } /** * Export a chapter as a contained HTML file. * * @throws Throwable */ public function exportHtml(int $id) { $chapter = $this->queries->findVisibleByIdOrFail($id); $htmlContent = $this->exportFormatter->chapterToContainedHtml($chapter); return $this->download()->directly($htmlContent, $chapter->slug . '.html'); } /** * Export a chapter as a plain text file. */ public function exportPlainText(int $id) { $chapter = $this->queries->findVisibleByIdOrFail($id); $textContent = $this->exportFormatter->chapterToPlainText($chapter); return $this->download()->directly($textContent, $chapter->slug . '.txt'); } /** * Export a chapter as a markdown file. */ public function exportMarkdown(int $id) { $chapter = $this->queries->findVisibleByIdOrFail($id); $markdown = $this->exportFormatter->chapterToMarkdown($chapter); return $this->download()->directly($markdown, $chapter->slug . '.md'); } /** * Export a chapter as a contained ZIP file. */ public function exportZip(int $id, ZipExportBuilder $builder) { $chapter = $this->queries->findVisibleByIdOrFail($id); $zip = $builder->buildForChapter($chapter); return $this->download()->streamedFileDirectly($zip, $chapter->slug . '.zip', true); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/Controllers/BookExportApiController.php
app/Exports/Controllers/BookExportApiController.php
<?php namespace BookStack\Exports\Controllers; use BookStack\Entities\Queries\BookQueries; use BookStack\Exports\ExportFormatter; use BookStack\Exports\ZipExports\ZipExportBuilder; use BookStack\Http\ApiController; use BookStack\Permissions\Permission; use Throwable; class BookExportApiController extends ApiController { public function __construct( protected ExportFormatter $exportFormatter, protected BookQueries $queries, ) { $this->middleware(Permission::ContentExport->middleware()); } /** * Export a book as a PDF file. * * @throws Throwable */ public function exportPdf(int $id) { $book = $this->queries->findVisibleByIdOrFail($id); $pdfContent = $this->exportFormatter->bookToPdf($book); return $this->download()->directly($pdfContent, $book->slug . '.pdf'); } /** * Export a book as a contained HTML file. * * @throws Throwable */ public function exportHtml(int $id) { $book = $this->queries->findVisibleByIdOrFail($id); $htmlContent = $this->exportFormatter->bookToContainedHtml($book); return $this->download()->directly($htmlContent, $book->slug . '.html'); } /** * Export a book as a plain text file. */ public function exportPlainText(int $id) { $book = $this->queries->findVisibleByIdOrFail($id); $textContent = $this->exportFormatter->bookToPlainText($book); return $this->download()->directly($textContent, $book->slug . '.txt'); } /** * Export a book as a markdown file. */ public function exportMarkdown(int $id) { $book = $this->queries->findVisibleByIdOrFail($id); $markdown = $this->exportFormatter->bookToMarkdown($book); return $this->download()->directly($markdown, $book->slug . '.md'); } /** * Export a book as a contained ZIP export file. */ public function exportZip(int $id, ZipExportBuilder $builder) { $book = $this->queries->findVisibleByIdOrFail($id); $zip = $builder->buildForBook($book); return $this->download()->streamedFileDirectly($zip, $book->slug . '.zip', true); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/Controllers/ImportController.php
app/Exports/Controllers/ImportController.php
<?php declare(strict_types=1); namespace BookStack\Exports\Controllers; use BookStack\Exceptions\ZipImportException; use BookStack\Exceptions\ZipValidationException; use BookStack\Exports\ImportRepo; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use BookStack\Uploads\AttachmentService; use Illuminate\Http\Request; class ImportController extends Controller { public function __construct( protected ImportRepo $imports, ) { $this->middleware(Permission::ContentImport->middleware()); } /** * Show the view to start a new import, and also list out the existing * in progress imports that are visible to the user. */ public function start() { $imports = $this->imports->getVisibleImports(); $this->setPageTitle(trans('entities.import')); return view('exports.import', [ 'imports' => $imports, 'zipErrors' => session()->pull('validation_errors') ?? [], ]); } /** * Upload, validate and store an import file. */ public function upload(Request $request) { $this->validate($request, [ 'file' => ['required', ...AttachmentService::getFileValidationRules()] ]); $file = $request->file('file'); try { $import = $this->imports->storeFromUpload($file); } catch (ZipValidationException $exception) { return redirect('/import')->with('validation_errors', $exception->errors); } return redirect($import->getUrl()); } /** * Show a pending import, with a form to allow progressing * with the import process. */ public function show(int $id) { $import = $this->imports->findVisible($id); $this->setPageTitle(trans('entities.import_continue')); return view('exports.import-show', [ 'import' => $import, 'data' => $import->decodeMetadata(), ]); } /** * Run the import process against an uploaded import ZIP. */ public function run(int $id, Request $request) { $import = $this->imports->findVisible($id); $parent = null; if ($import->type === 'page' || $import->type === 'chapter') { session()->setPreviousUrl($import->getUrl()); $data = $this->validate($request, [ 'parent' => ['required', 'string'], ]); $parent = $data['parent']; } try { $entity = $this->imports->runImport($import, $parent); } catch (ZipImportException $exception) { session()->forget(['success', 'warning']); $this->showErrorNotification(trans('errors.import_zip_failed_notification')); return redirect($import->getUrl())->with('import_errors', $exception->errors); } return redirect($entity->getUrl()); } /** * Delete an active pending import from the filesystem and database. */ public function delete(int $id) { $import = $this->imports->findVisible($id); $this->imports->deleteImport($import); return redirect('/import'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/Controllers/ChapterExportController.php
app/Exports/Controllers/ChapterExportController.php
<?php namespace BookStack\Exports\Controllers; use BookStack\Entities\Queries\ChapterQueries; use BookStack\Exceptions\NotFoundException; use BookStack\Exports\ExportFormatter; use BookStack\Exports\ZipExports\ZipExportBuilder; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use Throwable; class ChapterExportController extends Controller { public function __construct( protected ChapterQueries $queries, protected ExportFormatter $exportFormatter, ) { $this->middleware(Permission::ContentExport->middleware()); $this->middleware('throttle:exports'); } /** * Exports a chapter to pdf. * * @throws NotFoundException * @throws Throwable */ public function pdf(string $bookSlug, string $chapterSlug) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $pdfContent = $this->exportFormatter->chapterToPdf($chapter); return $this->download()->directly($pdfContent, $chapterSlug . '.pdf'); } /** * Export a chapter to a self-contained HTML file. * * @throws NotFoundException * @throws Throwable */ public function html(string $bookSlug, string $chapterSlug) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $containedHtml = $this->exportFormatter->chapterToContainedHtml($chapter); return $this->download()->directly($containedHtml, $chapterSlug . '.html'); } /** * Export a chapter to a simple plaintext .txt file. * * @throws NotFoundException */ public function plainText(string $bookSlug, string $chapterSlug) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $chapterText = $this->exportFormatter->chapterToPlainText($chapter); return $this->download()->directly($chapterText, $chapterSlug . '.txt'); } /** * Export a chapter to a simple markdown file. * * @throws NotFoundException */ public function markdown(string $bookSlug, string $chapterSlug) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $chapterText = $this->exportFormatter->chapterToMarkdown($chapter); return $this->download()->directly($chapterText, $chapterSlug . '.md'); } /** * Export a book to a contained ZIP export file. * @throws NotFoundException */ public function zip(string $bookSlug, string $chapterSlug, ZipExportBuilder $builder) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $zip = $builder->buildForChapter($chapter); return $this->download()->streamedFileDirectly($zip, $chapterSlug . '.zip', true); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/Controllers/PageExportApiController.php
app/Exports/Controllers/PageExportApiController.php
<?php namespace BookStack\Exports\Controllers; use BookStack\Entities\Queries\PageQueries; use BookStack\Exports\ExportFormatter; use BookStack\Exports\ZipExports\ZipExportBuilder; use BookStack\Http\ApiController; use BookStack\Permissions\Permission; use Throwable; class PageExportApiController extends ApiController { public function __construct( protected ExportFormatter $exportFormatter, protected PageQueries $queries, ) { $this->middleware(Permission::ContentExport->middleware()); } /** * Export a page as a PDF file. * * @throws Throwable */ public function exportPdf(int $id) { $page = $this->queries->findVisibleByIdOrFail($id); $pdfContent = $this->exportFormatter->pageToPdf($page); return $this->download()->directly($pdfContent, $page->slug . '.pdf'); } /** * Export a page as a contained HTML file. * * @throws Throwable */ public function exportHtml(int $id) { $page = $this->queries->findVisibleByIdOrFail($id); $htmlContent = $this->exportFormatter->pageToContainedHtml($page); return $this->download()->directly($htmlContent, $page->slug . '.html'); } /** * Export a page as a plain text file. */ public function exportPlainText(int $id) { $page = $this->queries->findVisibleByIdOrFail($id); $textContent = $this->exportFormatter->pageToPlainText($page); return $this->download()->directly($textContent, $page->slug . '.txt'); } /** * Export a page as a markdown file. */ public function exportMarkdown(int $id) { $page = $this->queries->findVisibleByIdOrFail($id); $markdown = $this->exportFormatter->pageToMarkdown($page); return $this->download()->directly($markdown, $page->slug . '.md'); } /** * Export a page as a contained ZIP file. */ public function exportZip(int $id, ZipExportBuilder $builder) { $page = $this->queries->findVisibleByIdOrFail($id); $zip = $builder->buildForPage($page); return $this->download()->streamedFileDirectly($zip, $page->slug . '.zip', true); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/Controllers/BookExportController.php
app/Exports/Controllers/BookExportController.php
<?php namespace BookStack\Exports\Controllers; use BookStack\Entities\Queries\BookQueries; use BookStack\Exceptions\NotFoundException; use BookStack\Exports\ExportFormatter; use BookStack\Exports\ZipExports\ZipExportBuilder; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use Throwable; class BookExportController extends Controller { public function __construct( protected BookQueries $queries, protected ExportFormatter $exportFormatter, ) { $this->middleware(Permission::ContentExport->middleware()); $this->middleware('throttle:exports'); } /** * Export a book as a PDF file. * * @throws Throwable */ public function pdf(string $bookSlug) { $book = $this->queries->findVisibleBySlugOrFail($bookSlug); $pdfContent = $this->exportFormatter->bookToPdf($book); return $this->download()->directly($pdfContent, $bookSlug . '.pdf'); } /** * Export a book as a contained HTML file. * * @throws Throwable */ public function html(string $bookSlug) { $book = $this->queries->findVisibleBySlugOrFail($bookSlug); $htmlContent = $this->exportFormatter->bookToContainedHtml($book); return $this->download()->directly($htmlContent, $bookSlug . '.html'); } /** * Export a book as a plain text file. */ public function plainText(string $bookSlug) { $book = $this->queries->findVisibleBySlugOrFail($bookSlug); $textContent = $this->exportFormatter->bookToPlainText($book); return $this->download()->directly($textContent, $bookSlug . '.txt'); } /** * Export a book as a markdown file. */ public function markdown(string $bookSlug) { $book = $this->queries->findVisibleBySlugOrFail($bookSlug); $textContent = $this->exportFormatter->bookToMarkdown($book); return $this->download()->directly($textContent, $bookSlug . '.md'); } /** * Export a book to a contained ZIP export file. * @throws NotFoundException */ public function zip(string $bookSlug, ZipExportBuilder $builder) { $book = $this->queries->findVisibleBySlugOrFail($bookSlug); $zip = $builder->buildForBook($book); return $this->download()->streamedFileDirectly($zip, $bookSlug . '.zip', true); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/ZipExportReferences.php
app/Exports/ZipExports/ZipExportReferences.php
<?php namespace BookStack\Exports\ZipExports; use BookStack\App\Model; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use BookStack\Exports\ZipExports\Models\ZipExportAttachment; use BookStack\Exports\ZipExports\Models\ZipExportBook; use BookStack\Exports\ZipExports\Models\ZipExportChapter; use BookStack\Exports\ZipExports\Models\ZipExportImage; use BookStack\Exports\ZipExports\Models\ZipExportModel; use BookStack\Exports\ZipExports\Models\ZipExportPage; use BookStack\Permissions\Permission; use BookStack\Uploads\Attachment; use BookStack\Uploads\Image; use BookStack\Uploads\ImageService; class ZipExportReferences { /** @var array<int, ZipExportPage> */ protected array $pages = []; /** @var array<int, ZipExportChapter> */ protected array $chapters = []; /** @var array<int, ZipExportBook> */ protected array $books = []; /** @var array<int, ZipExportAttachment> */ protected array $attachments = []; /** @var array<int, ZipExportImage> */ protected array $images = []; public function __construct( protected ZipReferenceParser $parser, protected ImageService $imageService, ) { } public function addPage(ZipExportPage $page): void { if ($page->id) { $this->pages[$page->id] = $page; } foreach ($page->attachments as $attachment) { if ($attachment->id) { $this->attachments[$attachment->id] = $attachment; } } } public function addChapter(ZipExportChapter $chapter): void { if ($chapter->id) { $this->chapters[$chapter->id] = $chapter; } foreach ($chapter->pages as $page) { $this->addPage($page); } } public function addBook(ZipExportBook $book): void { if ($book->id) { $this->books[$book->id] = $book; } foreach ($book->pages as $page) { $this->addPage($page); } foreach ($book->chapters as $chapter) { $this->addChapter($chapter); } } public function buildReferences(ZipExportFiles $files): void { $createHandler = function (ZipExportModel $zipModel) use ($files) { return function (Model $model) use ($files, $zipModel) { return $this->handleModelReference($model, $zipModel, $files); }; }; // Parse page content first foreach ($this->pages as $page) { $handler = $createHandler($page); $page->html = $this->parser->parseLinks($page->html ?? '', $handler); if ($page->markdown) { $page->markdown = $this->parser->parseLinks($page->markdown, $handler); } } // Parse chapter description HTML foreach ($this->chapters as $chapter) { if ($chapter->description_html) { $handler = $createHandler($chapter); $chapter->description_html = $this->parser->parseLinks($chapter->description_html, $handler); } } // Parse book description HTML foreach ($this->books as $book) { if ($book->description_html) { $handler = $createHandler($book); $book->description_html = $this->parser->parseLinks($book->description_html, $handler); } } } protected function handleModelReference(Model $model, ZipExportModel $exportModel, ZipExportFiles $files): ?string { // Handle attachment references // No permission check needed here since they would only already exist in this // reference context if already allowed via their entity access. if ($model instanceof Attachment) { if (isset($this->attachments[$model->id])) { return "[[bsexport:attachment:{$model->id}]]"; } return null; } // Handle image references if ($model instanceof Image) { // Only handle gallery and drawio images if ($model->type !== 'gallery' && $model->type !== 'drawio') { return null; } // Handle simple links outside of page content if (!($exportModel instanceof ZipExportPage) && isset($this->images[$model->id])) { return "[[bsexport:image:{$model->id}]]"; } // Get the page which we'll reference this image upon $page = $model->getPage(); $pageExportModel = null; if ($page && isset($this->pages[$page->id])) { $pageExportModel = $this->pages[$page->id]; } elseif ($exportModel instanceof ZipExportPage) { $pageExportModel = $exportModel; } // Add the image to the export if it's accessible or just return the existing reference if already added if (isset($this->images[$model->id]) || ($pageExportModel && $this->imageService->imageAccessible($model))) { if (!isset($this->images[$model->id])) { $exportImage = ZipExportImage::fromModel($model, $files); $this->images[$model->id] = $exportImage; $pageExportModel->images[] = $exportImage; } return "[[bsexport:image:{$model->id}]]"; } return null; } // Handle entity references if ($model instanceof Book && isset($this->books[$model->id])) { return "[[bsexport:book:{$model->id}]]"; } else if ($model instanceof Chapter && isset($this->chapters[$model->id])) { return "[[bsexport:chapter:{$model->id}]]"; } else if ($model instanceof Page && isset($this->pages[$model->id])) { return "[[bsexport:page:{$model->id}]]"; } return null; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/ZipExportValidator.php
app/Exports/ZipExports/ZipExportValidator.php
<?php namespace BookStack\Exports\ZipExports; use BookStack\Exceptions\ZipExportException; use BookStack\Exports\ZipExports\Models\ZipExportBook; use BookStack\Exports\ZipExports\Models\ZipExportChapter; use BookStack\Exports\ZipExports\Models\ZipExportPage; class ZipExportValidator { public function __construct( protected ZipExportReader $reader, ) { } public function validate(): array { try { $importData = $this->reader->readData(); } catch (ZipExportException $exception) { return ['format' => $exception->getMessage()]; } $helper = new ZipValidationHelper($this->reader); if (isset($importData['book'])) { $modelErrors = ZipExportBook::validate($helper, $importData['book']); $keyPrefix = 'book'; } else if (isset($importData['chapter'])) { $modelErrors = ZipExportChapter::validate($helper, $importData['chapter']); $keyPrefix = 'chapter'; } else if (isset($importData['page'])) { $modelErrors = ZipExportPage::validate($helper, $importData['page']); $keyPrefix = 'page'; } else { return ['format' => trans('errors.import_zip_no_data')]; } return $this->flattenModelErrors($modelErrors, $keyPrefix); } protected function flattenModelErrors(array $errors, string $keyPrefix): array { $flattened = []; foreach ($errors as $key => $error) { if (is_array($error)) { $flattened = array_merge($flattened, $this->flattenModelErrors($error, $keyPrefix . '.' . $key)); } else { $flattened[$keyPrefix . '.' . $key] = $error; } } return $flattened; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false