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/Entities/Tools/ParentChanger.php
app/Entities/Tools/ParentChanger.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\Chapter; use BookStack\References\ReferenceUpdater; class ParentChanger { public function __construct( protected SlugGenerator $slugGenerator, protected ReferenceUpdater $referenceUpdater ) { } /** * Change the parent book of a chapter or page. */ public function changeBook(BookChild $child, int $newBookId): void { $oldUrl = $child->getUrl(); $child->book_id = $newBookId; $child->unsetRelation('book'); $this->slugGenerator->regenerateForEntity($child); $child->save(); if ($oldUrl !== $child->getUrl()) { $this->referenceUpdater->updateEntityReferences($child, $oldUrl); } // Update all child pages if a chapter if ($child instanceof Chapter) { foreach ($child->pages()->withTrashed()->get() as $page) { $this->changeBook($page, $newBookId); } } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/PageEditorData.php
app/Entities/Tools/PageEditorData.php
<?php namespace BookStack\Entities\Tools; use BookStack\Activity\Tools\CommentTree; use BookStack\Entities\Models\Page; use BookStack\Entities\Queries\EntityQueries; use BookStack\Entities\Tools\Markdown\HtmlToMarkdown; use BookStack\Entities\Tools\Markdown\MarkdownToHtml; use BookStack\Permissions\Permission; class PageEditorData { protected array $viewData; protected array $warnings; public function __construct( protected Page $page, protected EntityQueries $queries, protected string $requestedEditor ) { $this->viewData = $this->build(); } public function getViewData(): array { return $this->viewData; } public function getWarnings(): array { return $this->warnings; } protected function build(): array { $page = clone $this->page; $isDraft = boolval($this->page->draft); $templates = $this->queries->pages->visibleTemplates() ->orderBy('name', 'asc') ->take(10) ->paginate() ->withPath('/templates'); $draftsEnabled = auth()->check(); $isDraftRevision = false; $this->warnings = []; $editActivity = new PageEditActivity($page); if ($editActivity->hasActiveEditing()) { $this->warnings[] = $editActivity->activeEditingMessage(); } // Check for a current draft version for this user $userDraft = $this->queries->revisions->findLatestCurrentUserDraftsForPageId($page->id); if (!is_null($userDraft)) { $page->forceFill($userDraft->only(['name', 'html', 'markdown'])); $isDraftRevision = true; $this->warnings[] = $editActivity->getEditingActiveDraftMessage($userDraft); } $editorType = $this->getEditorType($page); $this->updateContentForEditor($page, $editorType); return [ 'page' => $page, 'book' => $page->book, 'isDraft' => $isDraft, 'isDraftRevision' => $isDraftRevision, 'draftsEnabled' => $draftsEnabled, 'templates' => $templates, 'editor' => $editorType, 'comments' => new CommentTree($page), ]; } protected function updateContentForEditor(Page $page, PageEditorType $editorType): void { $isHtml = !empty($page->html) && empty($page->markdown); // HTML to markdown-clean conversion if ($editorType === PageEditorType::Markdown && $isHtml && $this->requestedEditor === 'markdown-clean') { $page->markdown = (new HtmlToMarkdown($page->html))->convert(); } // Markdown to HTML conversion if we don't have HTML if ($editorType->isHtmlBased() && !$isHtml) { $page->html = (new MarkdownToHtml($page->markdown))->convert(); } } /** * Get the type of editor to show for editing the given page. * Defaults based upon the current content of the page otherwise will fall back * to system default but will take a requested type (if provided) if permissions allow. */ protected function getEditorType(Page $page): PageEditorType { $editorType = PageEditorType::forPage($page) ?: PageEditorType::getSystemDefault(); // Use the requested editor if valid and if we have permission $requestedType = PageEditorType::fromRequestValue($this->requestedEditor); if ($requestedType && userCan(Permission::EditorChange)) { $editorType = $requestedType; } return $editorType; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/PageIncludeTag.php
app/Entities/Tools/PageIncludeTag.php
<?php namespace BookStack\Entities\Tools; use DOMNode; class PageIncludeTag { public function __construct( public string $tagContent, public DOMNode $domNode, ) { } /** * Get the page ID that this tag references. */ public function getPageId(): int { return intval(trim(explode('#', $this->tagContent, 2)[0])); } /** * Get the section ID that this tag references (if any) */ public function getSectionId(): string { return trim(explode('#', $this->tagContent, 2)[1] ?? ''); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/HierarchyTransformer.php
app/Entities/Tools/HierarchyTransformer.php
<?php namespace BookStack\Entities\Tools; use BookStack\Activity\ActivityType; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use BookStack\Entities\Repos\BookRepo; use BookStack\Entities\Repos\BookshelfRepo; use BookStack\Facades\Activity; class HierarchyTransformer { public function __construct( protected BookRepo $bookRepo, protected BookshelfRepo $shelfRepo, protected Cloner $cloner, protected TrashCan $trashCan, protected ParentChanger $parentChanger, ) { } /** * Transform a chapter into a book. * Does not check permissions, check before calling. */ public function transformChapterToBook(Chapter $chapter): Book { $inputData = $this->cloner->entityToInputData($chapter); $book = $this->bookRepo->create($inputData); $this->cloner->copyEntityPermissions($chapter, $book); /** @var Page $page */ foreach ($chapter->pages as $page) { $page->chapter_id = 0; $page->save(); $this->parentChanger->changeBook($page, $book->id); } $this->trashCan->destroyEntity($chapter); Activity::add(ActivityType::BOOK_CREATE_FROM_CHAPTER, $book); return $book; } /** * Transform a book into a shelf. * Does not check permissions, check before calling. */ public function transformBookToShelf(Book $book): Bookshelf { $inputData = $this->cloner->entityToInputData($book); $shelf = $this->shelfRepo->create($inputData, []); $this->cloner->copyEntityPermissions($book, $shelf); $shelfBookSyncData = []; /** @var Chapter $chapter */ foreach ($book->chapters as $index => $chapter) { $newBook = $this->transformChapterToBook($chapter); $shelfBookSyncData[$newBook->id] = ['order' => $index]; if (!$newBook->hasPermissions()) { $this->cloner->copyEntityPermissions($shelf, $newBook); } } if ($book->directPages->count() > 0) { $book->name .= ' ' . trans('entities.pages'); $shelfBookSyncData[$book->id] = ['order' => count($shelfBookSyncData) + 1]; $book->save(); } else { $this->trashCan->destroyEntity($book); } $shelf->books()->sync($shelfBookSyncData); Activity::add(ActivityType::BOOKSHELF_CREATE_FROM_BOOK, $shelf); return $shelf; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/SlugHistory.php
app/Entities/Tools/SlugHistory.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\EntityTable; use BookStack\Entities\Models\SlugHistory as SlugHistoryModel; use BookStack\Permissions\PermissionApplicator; use Illuminate\Support\Facades\DB; class SlugHistory { public function __construct( protected PermissionApplicator $permissions, ) { } /** * Record the current slugs for the given entity. */ public function recordForEntity(Entity $entity): void { if (!$entity->id || !$entity->slug) { return; } $parentSlug = null; if ($entity instanceof BookChild) { $parentSlug = $entity->book()->first()?->slug; } $latest = $this->getLatestEntryForEntity($entity); if ($latest && $latest->slug === $entity->slug && $latest->parent_slug === $parentSlug) { return; } $info = [ 'sluggable_type' => $entity->getMorphClass(), 'sluggable_id' => $entity->id, 'slug' => $entity->slug, 'parent_slug' => $parentSlug, ]; $entry = new SlugHistoryModel(); $entry->forceFill($info); $entry->save(); if ($entity instanceof Book) { $this->recordForBookChildren($entity); } } protected function recordForBookChildren(Book $book): void { $query = EntityTable::query() ->select(['type', 'id', 'slug', DB::raw("'{$book->slug}' as parent_slug"), DB::raw('now() as created_at'), DB::raw('now() as updated_at')]) ->where('book_id', '=', $book->id) ->whereNotNull('book_id'); SlugHistoryModel::query()->insertUsing( ['sluggable_type', 'sluggable_id', 'slug', 'parent_slug', 'created_at', 'updated_at'], $query ); } /** * Find the latest visible entry for an entity which uses the given slug(s) in the history. */ public function lookupEntityIdUsingSlugs(string $type, string $slug, string $parentSlug = ''): ?int { $query = SlugHistoryModel::query() ->where('sluggable_type', '=', $type) ->where('slug', '=', $slug); if ($parentSlug) { $query->where('parent_slug', '=', $parentSlug); } $query = $this->permissions->restrictEntityRelationQuery($query, 'slug_history', 'sluggable_id', 'sluggable_type'); /** @var SlugHistoryModel|null $result */ $result = $query->orderBy('created_at', 'desc')->first(); return $result?->sluggable_id; } protected function getLatestEntryForEntity(Entity $entity): SlugHistoryModel|null { return SlugHistoryModel::query() ->where('sluggable_type', '=', $entity->getMorphClass()) ->where('sluggable_id', '=', $entity->id) ->orderBy('created_at', 'desc') ->first(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/NextPreviousContentLocator.php
app/Entities/Tools/NextPreviousContentLocator.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\Entity; use Illuminate\Support\Collection; /** * Finds the next or previous content of a book element (page or chapter). */ class NextPreviousContentLocator { protected $relativeBookItem; protected $flatTree; protected $currentIndex = null; /** * NextPreviousContentLocator constructor. */ public function __construct(BookChild $relativeBookItem, Collection $bookTree) { $this->relativeBookItem = $relativeBookItem; $this->flatTree = $this->treeToFlatOrderedCollection($bookTree); $this->currentIndex = $this->getCurrentIndex(); } /** * Get the next logical entity within the book hierarchy. */ public function getNext(): ?Entity { return $this->flatTree->get($this->currentIndex + 1); } /** * Get the next logical entity within the book hierarchy. */ public function getPrevious(): ?Entity { return $this->flatTree->get($this->currentIndex - 1); } /** * Get the index of the current relative item. */ protected function getCurrentIndex(): ?int { $index = $this->flatTree->search(function (Entity $entity) { return get_class($entity) === get_class($this->relativeBookItem) && $entity->id === $this->relativeBookItem->id; }); return $index === false ? null : $index; } /** * Convert a book tree collection to a flattened version * where all items follow the expected order of user flow. */ protected function treeToFlatOrderedCollection(Collection $bookTree): Collection { $flatOrdered = collect(); /** @var Entity $item */ foreach ($bookTree->all() as $item) { $flatOrdered->push($item); $childPages = $item->getAttribute('visible_pages') ?? []; $flatOrdered = $flatOrdered->concat($childPages); } return $flatOrdered; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/EntityDefaultTemplate.php
app/Entities/Tools/EntityDefaultTemplate.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use BookStack\Entities\Queries\PageQueries; class EntityDefaultTemplate { public function __construct( protected Book|Chapter $entity, ) { } /** * Set the default template ID for this entity. */ public function setFromId(int $templateId): void { $changing = $templateId !== intval($this->entity->default_template_id); if (!$changing) { return; } if ($templateId === 0) { $this->entity->default_template_id = null; return; } $pageQueries = app()->make(PageQueries::class); $templateExists = $pageQueries->visibleTemplates() ->where('id', '=', $templateId) ->exists(); $this->entity->default_template_id = $templateExists ? $templateId : null; } /** * Get the default template for this entity (if visible). */ public function get(): Page|null { if (!$this->entity->default_template_id) { return null; } $pageQueries = app()->make(PageQueries::class); $page = $pageQueries->visibleTemplates(true) ->where('id', '=', $this->entity->default_template_id) ->first(); if ($page instanceof Page) { return $page; } return null; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/TrashCan.php
app/Entities/Tools/TrashCan.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\EntityProvider; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\EntityContainerData; use BookStack\Entities\Models\HasCoverInterface; use BookStack\Entities\Models\Deletion; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Entities\Queries\EntityQueries; use BookStack\Exceptions\NotifyException; use BookStack\Facades\Activity; use BookStack\Uploads\AttachmentService; use BookStack\Uploads\Image; use BookStack\Uploads\ImageService; use BookStack\Util\DatabaseTransaction; use Exception; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Carbon; class TrashCan { public function __construct( protected EntityQueries $queries, ) { } /** * Send a shelf to the recycle bin. * * @throws NotifyException */ public function softDestroyShelf(Bookshelf $shelf) { $this->ensureDeletable($shelf); Deletion::createForEntity($shelf); $shelf->delete(); } /** * Send a book to the recycle bin. * * @throws Exception */ public function softDestroyBook(Book $book) { $this->ensureDeletable($book); Deletion::createForEntity($book); foreach ($book->pages as $page) { $this->softDestroyPage($page, false); } foreach ($book->chapters as $chapter) { $this->softDestroyChapter($chapter, false); } $book->delete(); } /** * Send a chapter to the recycle bin. * * @throws Exception */ public function softDestroyChapter(Chapter $chapter, bool $recordDelete = true) { if ($recordDelete) { $this->ensureDeletable($chapter); Deletion::createForEntity($chapter); } if (count($chapter->pages) > 0) { foreach ($chapter->pages as $page) { $this->softDestroyPage($page, false); } } $chapter->delete(); } /** * Send a page to the recycle bin. * * @throws Exception */ public function softDestroyPage(Page $page, bool $recordDelete = true) { if ($recordDelete) { $this->ensureDeletable($page); Deletion::createForEntity($page); } $page->delete(); } /** * Ensure the given entity is deletable. * Is not for permissions, but logical conditions within the application. * Will throw if not deletable. * * @throws NotifyException */ protected function ensureDeletable(Entity $entity): void { $customHomeId = intval(explode(':', setting('app-homepage', '0:'))[0]); $customHomeActive = setting('app-homepage-type') === 'page'; $removeCustomHome = false; // Check custom homepage usage for pages if ($entity instanceof Page && $entity->id === $customHomeId) { if ($customHomeActive) { throw new NotifyException(trans('errors.page_custom_home_deletion'), $entity->getUrl()); } $removeCustomHome = true; } // Check custom homepage usage within chapters or books if ($entity instanceof Chapter || $entity instanceof Book) { if ($entity->pages()->where('id', '=', $customHomeId)->exists()) { if ($customHomeActive) { throw new NotifyException(trans('errors.page_custom_home_deletion'), $entity->getUrl()); } $removeCustomHome = true; } } if ($removeCustomHome) { setting()->remove('app-homepage'); } } /** * Remove a bookshelf from the system. * * @throws Exception */ protected function destroyShelf(Bookshelf $shelf): int { $this->destroyCommonRelations($shelf); $shelf->books()->detach(); $shelf->forceDelete(); return 1; } /** * Remove a book from the system. * Destroys any child chapters and pages. * * @throws Exception */ protected function destroyBook(Book $book): int { $count = 0; $pages = $book->pages()->withTrashed()->get(); foreach ($pages as $page) { $this->destroyPage($page); $count++; } $chapters = $book->chapters()->withTrashed()->get(); foreach ($chapters as $chapter) { $this->destroyChapter($chapter); $count++; } $this->destroyCommonRelations($book); $book->shelves()->detach(); $book->forceDelete(); return $count + 1; } /** * Remove a chapter from the system. * Destroys all pages within. * * @throws Exception */ protected function destroyChapter(Chapter $chapter): int { $count = 0; $pages = $chapter->pages()->withTrashed()->get(); foreach ($pages as $page) { $this->destroyPage($page); $count++; } $this->destroyCommonRelations($chapter); $chapter->forceDelete(); return $count + 1; } /** * Remove a page from the system. * * @throws Exception */ protected function destroyPage(Page $page): int { $this->destroyCommonRelations($page); $page->allRevisions()->delete(); // Delete Attached Files $attachmentService = app()->make(AttachmentService::class); foreach ($page->attachments as $attachment) { $attachmentService->deleteFile($attachment); } // Remove use as a template EntityContainerData::query() ->where('default_template_id', '=', $page->id) ->update(['default_template_id' => null]); // Nullify uploaded image relations Image::query() ->whereIn('type', ['gallery', 'drawio']) ->where('uploaded_to', '=', $page->id) ->update(['uploaded_to' => null]); $page->forceDelete(); return 1; } /** * Get the total counts of those that have been trashed * but not yet fully deleted (In recycle bin). */ public function getTrashedCounts(): array { $counts = []; foreach ((new EntityProvider())->all() as $key => $instance) { /** @var Builder<Entity> $query */ $query = $instance->newQuery(); $counts[$key] = $query->onlyTrashed()->count(); } return $counts; } /** * Destroy all items that have pending deletions. * * @throws Exception */ public function empty(): int { $deletions = Deletion::all(); $deleteCount = 0; foreach ($deletions as $deletion) { $deleteCount += $this->destroyFromDeletion($deletion); } return $deleteCount; } /** * Destroy an element from the given deletion model. * * @throws Exception */ public function destroyFromDeletion(Deletion $deletion): int { // We directly load the deletable element here just to ensure it still // exists in the event it has already been destroyed during this request. $entity = $deletion->deletable()->first(); $count = 0; if ($entity instanceof Entity) { $count = $this->destroyEntity($entity); } $deletion->delete(); return $count; } /** * Restore the content within the given deletion. * * @throws Exception */ public function restoreFromDeletion(Deletion $deletion): int { $shouldRestore = true; $restoreCount = 0; if ($deletion->deletable instanceof Entity) { $parent = $deletion->deletable->getParent(); if ($parent && $parent->trashed()) { $shouldRestore = false; } } if ($deletion->deletable instanceof Entity && $shouldRestore) { $restoreCount = $this->restoreEntity($deletion->deletable); } $deletion->delete(); return $restoreCount; } /** * Automatically clear old content from the recycle bin * depending on the configured lifetime. * Returns the total number of deleted elements. * * @throws Exception */ public function autoClearOld(): int { $lifetime = intval(config('app.recycle_bin_lifetime')); if ($lifetime < 0) { return 0; } $clearBeforeDate = Carbon::now()->addSeconds(10)->subDays($lifetime); $deleteCount = 0; $deletionsToRemove = Deletion::query()->where('created_at', '<', $clearBeforeDate)->get(); foreach ($deletionsToRemove as $deletion) { $deleteCount += $this->destroyFromDeletion($deletion); } return $deleteCount; } /** * Restore an entity so it is essentially un-deleted. * Deletions on restored child elements will be removed during this restoration. */ protected function restoreEntity(Entity $entity): int { $count = 1; $entity->restore(); $restoreAction = function ($entity) use (&$count) { if ($entity->deletions_count > 0) { $entity->deletions()->delete(); } $entity->restore(); $count++; }; if ($entity instanceof Chapter || $entity instanceof Book) { $entity->pages()->withTrashed()->withCount('deletions')->get()->each($restoreAction); } if ($entity instanceof Book) { $entity->chapters()->withTrashed()->withCount('deletions')->get()->each($restoreAction); } return $count; } /** * Destroy the given entity. * Returns the number of total entities destroyed in the operation. * * @throws Exception */ public function destroyEntity(Entity $entity): int { $result = (new DatabaseTransaction(function () use ($entity) { if ($entity instanceof Page) { return $this->destroyPage($entity); } else if ($entity instanceof Chapter) { return $this->destroyChapter($entity); } else if ($entity instanceof Book) { return $this->destroyBook($entity); } else if ($entity instanceof Bookshelf) { return $this->destroyShelf($entity); } return null; }))->run(); return $result ?? 0; } /** * Update entity relations to remove or update outstanding connections. */ protected function destroyCommonRelations(Entity $entity): void { Activity::removeEntity($entity); $entity->views()->delete(); $entity->permissions()->delete(); $entity->tags()->delete(); $entity->comments()->delete(); $entity->jointPermissions()->delete(); $entity->searchTerms()->delete(); $entity->deletions()->delete(); $entity->favourites()->delete(); $entity->watches()->delete(); $entity->referencesTo()->delete(); $entity->referencesFrom()->delete(); $entity->slugHistory()->delete(); if ($entity instanceof HasCoverInterface && $entity->coverInfo()->exists()) { $imageService = app()->make(ImageService::class); $imageService->destroy($entity->coverInfo()->getImage()); } $entity->relatedData()->delete(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/SlugGenerator.php
app/Entities/Tools/SlugGenerator.php
<?php namespace BookStack\Entities\Tools; use BookStack\App\Model; use BookStack\App\SluggableInterface; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\Entity; use BookStack\Users\Models\User; use Illuminate\Support\Str; class SlugGenerator { /** * Generate a fresh slug for the given item. * The slug will be generated so that it doesn't conflict within the same parent item. */ public function generate(SluggableInterface&Model $model, string $slugSource): string { $slug = $this->formatNameAsSlug($slugSource); while ($this->slugInUse($slug, $model)) { $slug .= '-' . Str::random(3); } return $slug; } /** * Regenerate the slug for the given entity. */ public function regenerateForEntity(Entity $entity): string { $entity->slug = $this->generate($entity, $entity->name); return $entity->slug; } /** * Regenerate the slug for a user. */ public function regenerateForUser(User $user): string { $user->slug = $this->generate($user, $user->name); return $user->slug; } /** * Format a name as a URL slug. */ protected function formatNameAsSlug(string $name): string { $slug = Str::slug($name); if ($slug === '') { $slug = substr(md5(rand(1, 500)), 0, 5); } return $slug; } /** * Check if a slug is already in-use for this * type of model within the same parent. */ protected function slugInUse(string $slug, SluggableInterface&Model $model): bool { $query = $model->newQuery()->where('slug', '=', $slug); if ($model instanceof BookChild) { $query->where('book_id', '=', $model->book_id); } if ($model->id) { $query->where('id', '!=', $model->id); } return $query->count() > 0; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/PageEditorType.php
app/Entities/Tools/PageEditorType.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\Models\Page; enum PageEditorType: string { case WysiwygTinymce = 'wysiwyg'; case WysiwygLexical = 'wysiwyg2024'; case Markdown = 'markdown'; public function isHtmlBased(): bool { return match ($this) { self::WysiwygTinymce, self::WysiwygLexical => true, self::Markdown => false, }; } public static function fromRequestValue(string $value): static|null { $editor = explode('-', $value)[0]; return static::tryFrom($editor); } public static function forPage(Page $page): static|null { return static::tryFrom($page->editor); } public static function getSystemDefault(): static { $setting = setting('app-editor'); return static::tryFrom($setting) ?? static::WysiwygTinymce; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/ShelfContext.php
app/Entities/Tools/ShelfContext.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Queries\BookshelfQueries; class ShelfContext { protected string $KEY_SHELF_CONTEXT_ID = 'context_bookshelf_id'; public function __construct( protected BookshelfQueries $shelfQueries, ) { } /** * Get the current bookshelf context for the given book. */ public function getContextualShelfForBook(Book $book): ?Bookshelf { $contextBookshelfId = session()->get($this->KEY_SHELF_CONTEXT_ID, null); if (!is_int($contextBookshelfId)) { return null; } $shelf = $this->shelfQueries->findVisibleById($contextBookshelfId); $shelfContainsBook = $shelf && $shelf->contains($book); return $shelfContainsBook ? $shelf : null; } /** * Store the current contextual shelf ID. */ public function setShelfContext(int $shelfId): void { session()->put($this->KEY_SHELF_CONTEXT_ID, $shelfId); } /** * Clear the session stored shelf context id. */ public function clearShelfContext(): void { session()->forget($this->KEY_SHELF_CONTEXT_ID); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/EntityHtmlDescription.php
app/Entities/Tools/EntityHtmlDescription.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Models\Chapter; use BookStack\Util\HtmlContentFilter; class EntityHtmlDescription { protected string $html = ''; protected string $plain = ''; public function __construct( protected Book|Chapter|Bookshelf $entity, ) { $this->html = $this->entity->description_html ?? ''; $this->plain = $this->entity->description ?? ''; } /** * Update the description from HTML code. * Optionally takes plaintext to use for the model also. */ public function set(string $html, string|null $plaintext = null): void { $this->html = $html; $this->entity->description_html = $this->html; if ($plaintext !== null) { $this->plain = $plaintext; $this->entity->description = $this->plain; } if (empty($html) && !empty($plaintext)) { $this->html = $this->getHtml(); $this->entity->description_html = $this->html; } } /** * Get the description as HTML. * Optionally returns the raw HTML if requested. */ public function getHtml(bool $raw = false): string { $html = $this->html ?: '<p>' . nl2br(e($this->plain)) . '</p>'; if ($raw) { return $html; } return HtmlContentFilter::removeScriptsFromHtmlString($html); } public function getPlain(): string { return $this->plain; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/PageEditActivity.php
app/Entities/Tools/PageEditActivity.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\Models\Page; use BookStack\Entities\Models\PageRevision; use BookStack\Util\DateFormatter; use Carbon\Carbon; use Illuminate\Database\Eloquent\Builder; class PageEditActivity { public function __construct( protected Page $page ) { } /** * Check if there's active editing being performed on this page. */ public function hasActiveEditing(): bool { return $this->activePageEditingQuery(60)->count() > 0; } /** * Get a notification message concerning the editing activity on the page. */ public function activeEditingMessage(): string { $pageDraftEdits = $this->activePageEditingQuery(60)->get(); $count = $pageDraftEdits->count(); $userMessage = trans('entities.pages_draft_edit_active.start_a', ['count' => $count]); if ($count === 1) { /** @var PageRevision $firstDraft */ $firstDraft = $pageDraftEdits->first(); $userMessage = trans('entities.pages_draft_edit_active.start_b', ['userName' => $firstDraft->createdBy->name ?? '']); } $timeMessage = trans('entities.pages_draft_edit_active.time_b', ['minCount' => 60]); return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]); } /** * Get any editor clash warning messages to show for the given draft revision. * * @return string[] */ public function getWarningMessagesForDraft(Page|PageRevision $draft): array { $warnings = []; if ($this->hasActiveEditing()) { $warnings[] = $this->activeEditingMessage(); } if ($draft instanceof PageRevision && $this->hasPageBeenUpdatedSinceDraftCreated($draft)) { $warnings[] = trans('entities.pages_draft_page_changed_since_creation'); } return $warnings; } /** * Check if the page has been updated since the draft has been saved. */ protected function hasPageBeenUpdatedSinceDraftCreated(PageRevision $draft): bool { return $draft->page->updated_at->timestamp > $draft->created_at->timestamp; } /** * Get the message to show when the user will be editing one of their drafts. */ public function getEditingActiveDraftMessage(PageRevision $draft): string { $formatter = resolve(DateFormatter::class); $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $formatter->relative($draft->updated_at)]); if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) { return $message; } return $message . "\n" . trans('entities.pages_draft_edited_notification'); } /** * A query to check for active update drafts on a particular page * within the last given many minutes. */ protected function activePageEditingQuery(int $withinMinutes): Builder { $checkTime = Carbon::now()->subMinutes($withinMinutes); $query = PageRevision::query() ->where('type', '=', 'update_draft') ->where('page_id', '=', $this->page->id) ->where('updated_at', '>', $this->page->updated_at) ->where('created_by', '!=', user()->id) ->where('updated_at', '>=', $checkTime) ->with('createdBy'); return $query; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/Cloner.php
app/Entities/Tools/Cloner.php
<?php namespace BookStack\Entities\Tools; use BookStack\Activity\Models\Tag; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\HasCoverInterface; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Entities\Repos\BookRepo; use BookStack\Entities\Repos\ChapterRepo; use BookStack\Entities\Repos\PageRepo; use BookStack\Permissions\Permission; use BookStack\References\ReferenceChangeContext; use BookStack\References\ReferenceUpdater; use BookStack\Uploads\Image; use BookStack\Uploads\ImageService; use Illuminate\Http\UploadedFile; class Cloner { protected ReferenceChangeContext $referenceChangeContext; public function __construct( protected PageRepo $pageRepo, protected ChapterRepo $chapterRepo, protected BookRepo $bookRepo, protected ImageService $imageService, protected ReferenceUpdater $referenceUpdater, ) { $this->referenceChangeContext = new ReferenceChangeContext(); } /** * Clone the given page into the given parent using the provided name. */ public function clonePage(Page $original, Entity $parent, string $newName): Page { $context = $this->newReferenceChangeContext(); $page = $this->createPageClone($original, $parent, $newName); $this->referenceUpdater->changeReferencesUsingContext($context); return $page; } protected function createPageClone(Page $original, Entity $parent, string $newName): Page { $copyPage = $this->pageRepo->getNewDraftPage($parent); $pageData = $this->entityToInputData($original); $pageData['name'] = $newName; $newPage = $this->pageRepo->publishDraft($copyPage, $pageData); $this->referenceChangeContext->add($original, $newPage); return $newPage; } /** * Clone the given page into the given parent using the provided name. * Clones all child pages. */ public function cloneChapter(Chapter $original, Book $parent, string $newName): Chapter { $context = $this->newReferenceChangeContext(); $chapter = $this->createChapterClone($original, $parent, $newName); $this->referenceUpdater->changeReferencesUsingContext($context); return $chapter; } protected function createChapterClone(Chapter $original, Book $parent, string $newName): Chapter { $chapterDetails = $this->entityToInputData($original); $chapterDetails['name'] = $newName; $copyChapter = $this->chapterRepo->create($chapterDetails, $parent); if (userCan(Permission::PageCreate, $copyChapter)) { /** @var Page $page */ foreach ($original->getVisiblePages() as $page) { $this->createPageClone($page, $copyChapter, $page->name); } } $this->referenceChangeContext->add($original, $copyChapter); return $copyChapter; } /** * Clone the given book. * Clones all child chapters and pages. */ public function cloneBook(Book $original, string $newName): Book { $context = $this->newReferenceChangeContext(); $book = $this->createBookClone($original, $newName); $this->referenceUpdater->changeReferencesUsingContext($context); return $book; } protected function createBookClone(Book $original, string $newName): Book { $bookDetails = $this->entityToInputData($original); $bookDetails['name'] = $newName; // Clone book $copyBook = $this->bookRepo->create($bookDetails); // Clone contents $directChildren = $original->getDirectVisibleChildren(); foreach ($directChildren as $child) { if ($child instanceof Chapter && userCan(Permission::ChapterCreate, $copyBook)) { $this->createChapterClone($child, $copyBook, $child->name); } if ($child instanceof Page && !$child->draft && userCan(Permission::PageCreate, $copyBook)) { $this->createPageClone($child, $copyBook, $child->name); } } // Clone bookshelf relationships /** @var Bookshelf $shelf */ foreach ($original->shelves as $shelf) { if (userCan(Permission::BookshelfUpdate, $shelf)) { $shelf->appendBook($copyBook); } } $this->referenceChangeContext->add($original, $copyBook); return $copyBook; } /** * Convert an entity to a raw data array of input data. * * @return array<string, mixed> */ public function entityToInputData(Entity $entity): array { $inputData = $entity->getAttributes(); $inputData['tags'] = $this->entityTagsToInputArray($entity); // Add a cover to the data if existing on the original entity if ($entity instanceof HasCoverInterface) { $cover = $entity->coverInfo()->getImage(); if ($cover) { $inputData['image'] = $this->imageToUploadedFile($cover); } } return $inputData; } /** * Copy the permission settings from the source entity to the target entity. */ public function copyEntityPermissions(Entity $sourceEntity, Entity $targetEntity): void { $permissions = $sourceEntity->permissions()->get(['role_id', 'view', 'create', 'update', 'delete'])->toArray(); $targetEntity->permissions()->delete(); $targetEntity->permissions()->createMany($permissions); $targetEntity->rebuildPermissions(); } /** * Convert an image instance to an UploadedFile instance to mimic * a file being uploaded. */ protected function imageToUploadedFile(Image $image): ?UploadedFile { $imgData = $this->imageService->getImageData($image); $tmpImgFilePath = tempnam(sys_get_temp_dir(), 'bs_cover_clone_'); file_put_contents($tmpImgFilePath, $imgData); return new UploadedFile($tmpImgFilePath, basename($image->path)); } /** * Convert the tags on the given entity to the raw format * that's used for incoming request data. */ protected function entityTagsToInputArray(Entity $entity): array { $tags = []; /** @var Tag $tag */ foreach ($entity->tags as $tag) { $tags[] = ['name' => $tag->name, 'value' => $tag->value]; } return $tags; } protected function newReferenceChangeContext(): ReferenceChangeContext { $this->referenceChangeContext = new ReferenceChangeContext(); return $this->referenceChangeContext; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/PermissionsUpdater.php
app/Entities/Tools/PermissionsUpdater.php
<?php namespace BookStack\Entities\Tools; use BookStack\Activity\ActivityType; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Models\Entity; use BookStack\Facades\Activity; use BookStack\Permissions\Models\EntityPermission; use BookStack\Permissions\Permission; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Illuminate\Http\Request; class PermissionsUpdater { /** * Update an entities permissions from a permission form submit request. */ public function updateFromPermissionsForm(Entity $entity, Request $request): void { $permissions = $request->get('permissions', null); $ownerId = $request->get('owned_by', null); $entity->permissions()->delete(); if (!is_null($permissions)) { $entityPermissionData = $this->formatPermissionsFromRequestToEntityPermissions($permissions); $entity->permissions()->createMany($entityPermissionData); } if (!is_null($ownerId)) { $this->updateOwnerFromId($entity, intval($ownerId)); } $entity->save(); $entity->rebuildPermissions(); Activity::add(ActivityType::PERMISSIONS_UPDATE, $entity); } /** * Update permissions from API request data. */ public function updateFromApiRequestData(Entity $entity, array $data): void { if (isset($data['role_permissions'])) { $entity->permissions()->where('role_id', '!=', 0)->delete(); $rolePermissionData = $this->formatPermissionsFromApiRequestToEntityPermissions($data['role_permissions'] ?? [], false); $entity->permissions()->createMany($rolePermissionData); } if (array_key_exists('fallback_permissions', $data)) { $entity->permissions()->where('role_id', '=', 0)->delete(); } if (isset($data['fallback_permissions']['inheriting']) && $data['fallback_permissions']['inheriting'] !== true) { $fallbackData = $data['fallback_permissions']; $fallbackData['role_id'] = 0; $rolePermissionData = $this->formatPermissionsFromApiRequestToEntityPermissions([$fallbackData], true); $entity->permissions()->createMany($rolePermissionData); } if (isset($data['owner_id'])) { $this->updateOwnerFromId($entity, intval($data['owner_id'])); } $entity->save(); $entity->rebuildPermissions(); Activity::add(ActivityType::PERMISSIONS_UPDATE, $entity); } /** * Update the owner of the given entity. * Checks the user exists in the system first. * Does not save the model, just updates it. */ protected function updateOwnerFromId(Entity $entity, int $newOwnerId): void { $newOwner = User::query()->find($newOwnerId); if (!is_null($newOwner)) { $entity->owned_by = $newOwner->id; } } /** * Format permissions provided from a permission form to be EntityPermission data. */ protected function formatPermissionsFromRequestToEntityPermissions(array $permissions): array { $formatted = []; foreach ($permissions as $roleId => $info) { $entityPermissionData = ['role_id' => $roleId]; foreach (Permission::genericForEntity() as $permission) { $permName = $permission->value; $entityPermissionData[$permName] = (($info[$permName] ?? false) === "true"); } $formatted[] = $entityPermissionData; } return $this->filterEntityPermissionDataUponRole($formatted, true); } protected function formatPermissionsFromApiRequestToEntityPermissions(array $permissions, bool $allowFallback): array { $formatted = []; foreach ($permissions as $requestPermissionData) { $entityPermissionData = ['role_id' => $requestPermissionData['role_id']]; foreach (Permission::genericForEntity() as $permission) { $permName = $permission->value; $entityPermissionData[$permName] = boolval($requestPermissionData[$permName] ?? false); } $formatted[] = $entityPermissionData; } return $this->filterEntityPermissionDataUponRole($formatted, $allowFallback); } protected function filterEntityPermissionDataUponRole(array $entityPermissionData, bool $allowFallback): array { $roleIds = []; foreach ($entityPermissionData as $permissionEntry) { $roleIds[] = intval($permissionEntry['role_id']); } $actualRoleIds = array_unique(array_values(array_filter($roleIds))); $rolesById = Role::query()->whereIn('id', $actualRoleIds)->get('id')->keyBy('id'); return array_values(array_filter($entityPermissionData, function ($data) use ($rolesById, $allowFallback) { if (intval($data['role_id']) === 0) { return $allowFallback; } return $rolesById->has($data['role_id']); })); } /** * Copy down the permissions of the given shelf to all child books. */ public function updateBookPermissionsFromShelf(Bookshelf $shelf, $checkUserPermissions = true): int { $shelfPermissions = $shelf->permissions()->get(['role_id', 'view', 'create', 'update', 'delete'])->toArray(); $shelfBooks = $shelf->books()->get(['id', 'owned_by']); $updatedBookCount = 0; /** @var Book $book */ foreach ($shelfBooks as $book) { if ($checkUserPermissions && !userCan(Permission::RestrictionsManage, $book)) { continue; } $book->permissions()->delete(); $book->permissions()->createMany($shelfPermissions); $book->rebuildPermissions(); $updatedBookCount++; } return $updatedBookCount; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/SiblingFetcher.php
app/Entities/Tools/SiblingFetcher.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\EntityProvider; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Page; use BookStack\Entities\Queries\EntityQueries; use Illuminate\Support\Collection; class SiblingFetcher { public function __construct( protected EntityQueries $queries, protected ShelfContext $shelfContext, ) { } /** * Search among the siblings of the entity of given type and id. */ public function fetch(string $entityType, int $entityId): Collection { $entity = (new EntityProvider())->get($entityType)->visible()->findOrFail($entityId); $entities = []; // Page in chapter if ($entity instanceof Page && $entity->chapter) { $entities = $entity->chapter->getVisiblePages(); } // Page in book or chapter if (($entity instanceof Page && !$entity->chapter) || $entity instanceof Chapter) { $entities = $entity->book->getDirectVisibleChildren(); } // Book // Gets just the books in a shelf if shelf is in context if ($entity instanceof Book) { $contextShelf = $this->shelfContext->getContextualShelfForBook($entity); if ($contextShelf) { $entities = $contextShelf->visibleBooks()->get(); } else { $entities = $this->queries->books->visibleForList()->orderBy('name', 'asc')->get(); } } // Shelf if ($entity instanceof Bookshelf) { $entities = $this->queries->shelves->visibleForList()->orderBy('name', 'asc')->get(); } return $entities; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/PageContent.php
app/Entities/Tools/PageContent.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\Models\Page; use BookStack\Entities\Queries\PageQueries; use BookStack\Entities\Tools\Markdown\MarkdownToHtml; use BookStack\Exceptions\ImageUploadException; use BookStack\Facades\Theme; use BookStack\Permissions\Permission; use BookStack\Theming\ThemeEvents; use BookStack\Uploads\ImageRepo; use BookStack\Uploads\ImageService; use BookStack\Users\Models\User; use BookStack\Util\HtmlContentFilter; use BookStack\Util\HtmlDocument; use BookStack\Util\WebSafeMimeSniffer; use Closure; use DOMElement; use DOMNode; use DOMNodeList; use Illuminate\Support\Str; class PageContent { protected PageQueries $pageQueries; public function __construct( protected Page $page ) { $this->pageQueries = app()->make(PageQueries::class); } /** * Update the content of the page with new provided HTML. */ public function setNewHTML(string $html, User $updater): void { $html = $this->extractBase64ImagesFromHtml($html, $updater); $this->page->html = $this->formatHtml($html); $this->page->text = $this->toPlainText(); $this->page->markdown = ''; } /** * Update the content of the page with new provided Markdown content. */ public function setNewMarkdown(string $markdown, User $updater): void { $markdown = $this->extractBase64ImagesFromMarkdown($markdown, $updater); $this->page->markdown = $markdown; $html = (new MarkdownToHtml($markdown))->convert(); $this->page->html = $this->formatHtml($html); $this->page->text = $this->toPlainText(); } /** * Convert all base64 image data to saved images. */ protected function extractBase64ImagesFromHtml(string $htmlText, User $updater): string { if (empty($htmlText) || !str_contains($htmlText, 'data:image')) { return $htmlText; } $doc = new HtmlDocument($htmlText); // Get all img elements with image data blobs $imageNodes = $doc->queryXPath('//img[contains(@src, \'data:image\')]'); /** @var DOMElement $imageNode */ foreach ($imageNodes as $imageNode) { $imageSrc = $imageNode->getAttribute('src'); $newUrl = $this->base64ImageUriToUploadedImageUrl($imageSrc, $updater); $imageNode->setAttribute('src', $newUrl); } return $doc->getBodyInnerHtml(); } /** * Convert all inline base64 content to uploaded image files. * Regex is used to locate the start of data-uri definitions then * manual looping over content is done to parse the whole data uri. * Attempting to capture the whole data uri using regex can cause PHP * PCRE limits to be hit with larger, multi-MB, files. */ protected function extractBase64ImagesFromMarkdown(string $markdown, User $updater): string { $matches = []; $contentLength = strlen($markdown); $replacements = []; preg_match_all('/!\[.*?]\(.*?(data:image\/.{1,6};base64,)/', $markdown, $matches, PREG_OFFSET_CAPTURE); foreach ($matches[1] as $base64MatchPair) { [$dataUri, $index] = $base64MatchPair; for ($i = strlen($dataUri) + $index; $i < $contentLength; $i++) { $char = $markdown[$i]; if ($char === ')' || $char === ' ' || $char === "\n" || $char === '"') { break; } $dataUri .= $char; } $newUrl = $this->base64ImageUriToUploadedImageUrl($dataUri, $updater); $replacements[] = [$dataUri, $newUrl]; } foreach ($replacements as [$dataUri, $newUrl]) { $markdown = str_replace($dataUri, $newUrl, $markdown); } return $markdown; } /** * Parse the given base64 image URI and return the URL to the created image instance. * Returns an empty string if the parsed URI is invalid or causes an error upon upload. */ protected function base64ImageUriToUploadedImageUrl(string $uri, User $updater): string { $imageRepo = app()->make(ImageRepo::class); $imageInfo = $this->parseBase64ImageUri($uri); // Validate user has permission to create images if (!$updater->can(Permission::ImageCreateAll)) { return ''; } // Validate extension and content if (empty($imageInfo['data']) || !ImageService::isExtensionSupported($imageInfo['extension'])) { return ''; } // Validate content looks like an image via sniffing mime type $mimeSniffer = new WebSafeMimeSniffer(); $mime = $mimeSniffer->sniff($imageInfo['data']); if (!str_starts_with($mime, 'image/')) { return ''; } // Validate that the content is not over our upload limit $uploadLimitBytes = (config('app.upload_limit') * 1000000); if (strlen($imageInfo['data']) > $uploadLimitBytes) { return ''; } // Save image from data with a random name $imageName = 'embedded-image-' . Str::random(8) . '.' . $imageInfo['extension']; try { $image = $imageRepo->saveNewFromData($imageName, $imageInfo['data'], 'gallery', $this->page->id); } catch (ImageUploadException $exception) { return ''; } return $image->url; } /** * Parse a base64 image URI into the data and extension. * * @return array{extension: string, data: string} */ protected function parseBase64ImageUri(string $uri): array { [$dataDefinition, $base64ImageData] = explode(',', $uri, 2); $extension = strtolower(preg_split('/[\/;]/', $dataDefinition)[1] ?? ''); return [ 'extension' => $extension, 'data' => base64_decode($base64ImageData) ?: '', ]; } /** * Formats a page's html to be tagged correctly within the system. */ protected function formatHtml(string $htmlText): string { if (empty($htmlText)) { return $htmlText; } $doc = new HtmlDocument($htmlText); // Map to hold used ID references $idMap = []; // Map to hold changing ID references $changeMap = []; $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap); $this->updateLinks($doc, $changeMap); // Generate inner html as a string & perform required string-level tweaks $html = $doc->getBodyInnerHtml(); $html = str_replace(' ', '&nbsp;', $html); return $html; } /** * For the given DOMNode, traverse its children recursively and update IDs * where required (Top-level, headers & elements with IDs). * Will update the provided $changeMap array with changes made, where keys are the old * ids and the corresponding values are the new ids. */ protected function updateIdsRecursively(DOMNode $element, int $depth, array &$idMap, array &$changeMap): void { /* @var DOMNode $child */ foreach ($element->childNodes as $child) { if ($child instanceof DOMElement && ($depth === 0 || in_array($child->nodeName, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) || $child->getAttribute('id'))) { [$oldId, $newId] = $this->setUniqueId($child, $idMap); if ($newId && $newId !== $oldId && !isset($idMap[$oldId])) { $changeMap[$oldId] = $newId; } } if ($child->hasChildNodes()) { $this->updateIdsRecursively($child, $depth + 1, $idMap, $changeMap); } } } /** * Update the all links in the given xpath to apply requires changes within the * given $changeMap array. */ protected function updateLinks(HtmlDocument $doc, array $changeMap): void { if (empty($changeMap)) { return; } $links = $doc->queryXPath('//body//*//*[@href]'); /** @var DOMElement $domElem */ foreach ($links as $domElem) { $href = ltrim($domElem->getAttribute('href'), '#'); $newHref = $changeMap[$href] ?? null; if ($newHref) { $domElem->setAttribute('href', '#' . $newHref); } } } /** * Set a unique id on the given DOMElement. * A map for existing ID's should be passed in to check for current existence, * and this will be updated with any new IDs set upon elements. * Returns a pair of strings in the format [old_id, new_id]. */ protected function setUniqueId(DOMNode $element, array &$idMap): array { if (!$element instanceof DOMElement) { return ['', '']; } // Stop if there's an existing valid id that has not already been used. $existingId = $element->getAttribute('id'); if (str_starts_with($existingId, 'bkmrk') && !isset($idMap[$existingId])) { $idMap[$existingId] = true; return [$existingId, $existingId]; } // Create a unique id for the element // Uses the content as a basis to ensure output is the same every time // the same content is passed through. $contentId = 'bkmrk-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20); $newId = urlencode($contentId); $loopIndex = 1; while (isset($idMap[$newId])) { $newId = urlencode($contentId . '-' . $loopIndex); $loopIndex++; } $element->setAttribute('id', $newId); $idMap[$newId] = true; return [$existingId, $newId]; } /** * Get a plain-text visualisation of this page. */ public function toPlainText(): string { $html = $this->render(true); return html_entity_decode(strip_tags($html)); } /** * Render the page for viewing. */ public function render(bool $blankIncludes = false): string { $html = $this->page->html ?? ''; if (empty($html)) { return $html; } $doc = new HtmlDocument($html); $contentProvider = $this->getContentProviderClosure($blankIncludes); $parser = new PageIncludeParser($doc, $contentProvider); $nodesAdded = 1; for ($includeDepth = 0; $includeDepth < 3 && $nodesAdded !== 0; $includeDepth++) { $nodesAdded = $parser->parse(); } if ($includeDepth > 1) { $idMap = []; $changeMap = []; $this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap); } if (!config('app.allow_content_scripts')) { HtmlContentFilter::removeScriptsFromDocument($doc); } return $doc->getBodyInnerHtml(); } /** * Get the closure used to fetch content for page includes. */ protected function getContentProviderClosure(bool $blankIncludes): Closure { $contextPage = $this->page; $queries = $this->pageQueries; return function (PageIncludeTag $tag) use ($blankIncludes, $contextPage, $queries): PageIncludeContent { if ($blankIncludes) { return PageIncludeContent::fromHtmlAndTag('', $tag); } $matchedPage = $queries->findVisibleById($tag->getPageId()); $content = PageIncludeContent::fromHtmlAndTag($matchedPage->html ?? '', $tag); if (Theme::hasListeners(ThemeEvents::PAGE_INCLUDE_PARSE)) { $themeReplacement = Theme::dispatch( ThemeEvents::PAGE_INCLUDE_PARSE, $tag->tagContent, $content->toHtml(), clone $contextPage, $matchedPage ? (clone $matchedPage) : null, ); if ($themeReplacement !== null) { $content = PageIncludeContent::fromInlineHtml(strval($themeReplacement)); } } return $content; }; } /** * Parse the headers on the page to get a navigation menu. */ public function getNavigation(string $htmlContent): array { if (empty($htmlContent)) { return []; } $doc = new HtmlDocument($htmlContent); $headers = $doc->queryXPath('//h1|//h2|//h3|//h4|//h5|//h6'); return $headers->count() === 0 ? [] : $this->headerNodesToLevelList($headers); } /** * Convert a DOMNodeList into an array of readable header attributes * with levels normalised to the lower header level. */ protected function headerNodesToLevelList(DOMNodeList $nodeList): array { $tree = collect($nodeList)->map(function (DOMElement $header) { $text = trim(str_replace("\xc2\xa0", ' ', $header->nodeValue)); $text = mb_substr($text, 0, 100); return [ 'nodeName' => strtolower($header->nodeName), 'level' => intval(str_replace('h', '', $header->nodeName)), 'link' => '#' . $header->getAttribute('id'), 'text' => $text, ]; })->filter(function ($header) { return mb_strlen($header['text']) > 0; }); // Shift headers if only smaller headers have been used $levelChange = ($tree->pluck('level')->min() - 1); $tree = $tree->map(function ($header) use ($levelChange) { $header['level'] -= ($levelChange); return $header; }); return $tree->toArray(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/MixedEntityListLoader.php
app/Entities/Tools/MixedEntityListLoader.php
<?php namespace BookStack\Entities\Tools; use BookStack\App\Model; use BookStack\Entities\Queries\EntityQueries; use Illuminate\Database\Eloquent\Relations\Relation; class MixedEntityListLoader { public function __construct( protected EntityQueries $queries, ) { } /** * Efficiently load in entities for listing onto the given list * where entities are set as a relation via the given name. * This will look for a model id and type via 'name_id' and 'name_type'. * @param Model[] $relations */ public function loadIntoRelations(array $relations, string $relationName, bool $loadParents, bool $withContents = false): void { $idsByType = []; foreach ($relations as $relation) { $type = $relation->getAttribute($relationName . '_type'); $id = $relation->getAttribute($relationName . '_id'); if (!isset($idsByType[$type])) { $idsByType[$type] = []; } $idsByType[$type][] = $id; } $modelMap = $this->idsByTypeToModelMap($idsByType, $loadParents, $withContents); foreach ($relations as $relation) { $type = $relation->getAttribute($relationName . '_type'); $id = $relation->getAttribute($relationName . '_id'); $related = $modelMap[$type][strval($id)] ?? null; if ($related) { $relation->setRelation($relationName, $related); } } } /** * @param array<string, int[]> $idsByType * @return array<string, array<int, Model>> */ protected function idsByTypeToModelMap(array $idsByType, bool $eagerLoadParents, bool $withContents): array { $modelMap = []; foreach ($idsByType as $type => $ids) { $base = $withContents ? $this->queries->visibleForContentForType($type) : $this->queries->visibleForListForType($type); $models = $base->whereIn('id', $ids) ->with($eagerLoadParents ? $this->getRelationsToEagerLoad($type) : []) ->get(); if (count($models) > 0) { $modelMap[$type] = []; } foreach ($models as $model) { $modelMap[$type][strval($model->id)] = $model; } } return $modelMap; } protected function getRelationsToEagerLoad(string $type): array { $toLoad = []; $loadVisible = fn (Relation $query) => $query->scopes('visible'); if ($type === 'chapter' || $type === 'page') { $toLoad['book'] = $loadVisible; } if ($type === 'page') { $toLoad['chapter'] = $loadVisible; } return $toLoad; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/BookContents.php
app/Entities/Tools/BookContents.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Entities\Queries\EntityQueries; use Illuminate\Support\Collection; class BookContents { protected EntityQueries $queries; public function __construct( protected Book $book, ) { $this->queries = app()->make(EntityQueries::class); } /** * Get the current priority of the last item at the top-level of the book. */ public function getLastPriority(): int { $maxPage = $this->book->pages() ->where('draft', '=', false) ->whereDoesntHave('chapter') ->max('priority'); $maxChapter = $this->book->chapters() ->max('priority'); return max($maxChapter, $maxPage, 1); } /** * Get the contents as a sorted collection tree. */ public function getTree(bool $showDrafts = false, bool $renderPages = false): Collection { $pages = $this->getPages($showDrafts, $renderPages); $chapters = $this->book->chapters()->scopes('visible')->get(); $all = collect()->concat($pages)->concat($chapters); $chapterMap = $chapters->keyBy('id'); $lonePages = collect(); $pages->groupBy('chapter_id')->each(function ($pages, $chapter_id) use ($chapterMap, &$lonePages) { $chapter = $chapterMap->get($chapter_id); if ($chapter) { $chapter->setAttribute('visible_pages', collect($pages)->sortBy($this->bookChildSortFunc())); } else { $lonePages = $lonePages->concat($pages); } }); $chapters->whereNull('visible_pages')->each(function (Chapter $chapter) { $chapter->setAttribute('visible_pages', collect([])); }); $all->each(function (Entity $entity) use ($renderPages) { $entity->setRelation('book', $this->book); if ($renderPages && $entity instanceof Page) { $entity->html = (new PageContent($entity))->render(); } }); return collect($chapters)->concat($lonePages)->sortBy($this->bookChildSortFunc()); } /** * Function for providing a sorting score for an entity in relation to the * other items within the book. */ protected function bookChildSortFunc(): callable { return function (Entity $entity) { if ($entity->getAttribute('draft') ?? false) { return -100; } return $entity->getAttribute('priority') ?? 0; }; } /** * Get the visible pages within this book. */ protected function getPages(bool $showDrafts = false, bool $getPageContent = false): Collection { if ($getPageContent) { $query = $this->queries->pages->visibleWithContents(); } else { $query = $this->queries->pages->visibleForList(); } if (!$showDrafts) { $query->where('draft', '=', false); } return $query->where('book_id', '=', $this->book->id)->get(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/EntityCover.php
app/Entities/Tools/EntityCover.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Uploads\Image; use Exception; use Illuminate\Database\Eloquent\Builder; class EntityCover { public function __construct( protected Book|Bookshelf $entity, ) { } protected function imageQuery(): Builder { return Image::query()->where('id', '=', $this->entity->image_id); } /** * Check if a cover image exists for this entity. */ public function exists(): bool { return $this->entity->image_id !== null && $this->imageQuery()->exists(); } /** * Get the assigned cover image model. */ public function getImage(): Image|null { if ($this->entity->image_id === null) { return null; } $cover = $this->imageQuery()->first(); if ($cover instanceof Image) { return $cover; } return null; } /** * Returns a cover image URL, or the given default if none assigned/existing. */ public function getUrl(int $width = 440, int $height = 250, string|null $default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='): string|null { if (!$this->entity->image_id) { return $default; } try { return $this->getImage()?->getThumb($width, $height, false) ?? $default; } catch (Exception $err) { return $default; } } /** * Set the image to use as the cover for this entity. */ public function setImage(Image|null $image): void { if ($image === null) { $this->entity->image_id = null; } else { $this->entity->image_id = $image->id; } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/Markdown/CustomImageConverter.php
app/Entities/Tools/Markdown/CustomImageConverter.php
<?php namespace BookStack\Entities\Tools\Markdown; use League\HTMLToMarkdown\Converter\ImageConverter; use League\HTMLToMarkdown\ElementInterface; class CustomImageConverter extends ImageConverter { public function convert(ElementInterface $element): string { $parent = $element->getParent(); // Remain as HTML if within diagram block. $withinDrawing = $parent && !empty($parent->getAttribute('drawio-diagram')); if ($withinDrawing) { $src = e($element->getAttribute('src')); $alt = e($element->getAttribute('alt')); return "<img src=\"{$src}\" alt=\"{$alt}\"/>"; } return parent::convert($element); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/Markdown/CustomParagraphConverter.php
app/Entities/Tools/Markdown/CustomParagraphConverter.php
<?php namespace BookStack\Entities\Tools\Markdown; use League\HTMLToMarkdown\Converter\ParagraphConverter; use League\HTMLToMarkdown\ElementInterface; class CustomParagraphConverter extends ParagraphConverter { public function convert(ElementInterface $element): string { $class = e($element->getAttribute('class')); if (strpos($class, 'callout') !== false) { return "<{$element->getTagName()} class=\"{$class}\">{$element->getValue()}</{$element->getTagName()}>\n\n"; } return parent::convert($element); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/Markdown/HtmlToMarkdown.php
app/Entities/Tools/Markdown/HtmlToMarkdown.php
<?php namespace BookStack\Entities\Tools\Markdown; use League\HTMLToMarkdown\Converter\BlockquoteConverter; use League\HTMLToMarkdown\Converter\CodeConverter; use League\HTMLToMarkdown\Converter\CommentConverter; use League\HTMLToMarkdown\Converter\EmphasisConverter; use League\HTMLToMarkdown\Converter\HardBreakConverter; use League\HTMLToMarkdown\Converter\HeaderConverter; use League\HTMLToMarkdown\Converter\HorizontalRuleConverter; use League\HTMLToMarkdown\Converter\LinkConverter; use League\HTMLToMarkdown\Converter\ListBlockConverter; use League\HTMLToMarkdown\Converter\ListItemConverter; use League\HTMLToMarkdown\Converter\PreformattedConverter; use League\HTMLToMarkdown\Converter\TextConverter; use League\HTMLToMarkdown\Environment; use League\HTMLToMarkdown\HtmlConverter; class HtmlToMarkdown { protected string $html; public function __construct(string $html) { $this->html = $html; } /** * Run the conversion. */ public function convert(): string { $converter = new HtmlConverter($this->getConverterEnvironment()); $html = $this->prepareHtml($this->html); return $converter->convert($html); } /** * Run any pre-processing to the HTML to clean it up manually before conversion. */ protected function prepareHtml(string $html): string { // Carriage returns can cause whitespace issues in output $html = str_replace("\r\n", "\n", $html); // Attributes on the pre tag can cause issues with conversion return preg_replace('/<pre .*?>/', '<pre>', $html); } /** * Get the HTML to Markdown customized environment. * Extends the default provided environment with some BookStack specific tweaks. */ protected function getConverterEnvironment(): Environment { $environment = new Environment([ 'header_style' => 'atx', // Set to 'atx' to output H1 and H2 headers as # Header1 and ## Header2 'suppress_errors' => true, // Set to false to show warnings when loading malformed HTML 'strip_tags' => false, // Set to true to strip tags that don't have markdown equivalents. N.B. Strips tags, not their content. Useful to clean MS Word HTML output. 'strip_placeholder_links' => false, // Set to true to remove <a> that doesn't have href. 'bold_style' => '**', // DEPRECATED: Set to '__' if you prefer the underlined style 'italic_style' => '*', // DEPRECATED: Set to '_' if you prefer the underlined style 'remove_nodes' => '', // space-separated list of dom nodes that should be removed. example: 'meta style script' 'hard_break' => false, // Set to true to turn <br> into `\n` instead of ` \n` 'list_item_style' => '-', // Set the default character for each <li> in a <ul>. Can be '-', '*', or '+' 'preserve_comments' => false, // Set to true to preserve comments, or set to an array of strings to preserve specific comments 'use_autolinks' => false, // Set to true to use simple link syntax if possible. Will always use []() if set to false 'table_pipe_escape' => '\|', // Replacement string for pipe characters inside markdown table cells 'table_caption_side' => 'top', // Set to 'top' or 'bottom' to show <caption> content before or after table, null to suppress ]); $environment->addConverter(new BlockquoteConverter()); $environment->addConverter(new CodeConverter()); $environment->addConverter(new CommentConverter()); $environment->addConverter(new CustomDivConverter()); $environment->addConverter(new EmphasisConverter()); $environment->addConverter(new HardBreakConverter()); $environment->addConverter(new HeaderConverter()); $environment->addConverter(new HorizontalRuleConverter()); $environment->addConverter(new CustomImageConverter()); $environment->addConverter(new LinkConverter()); $environment->addConverter(new ListBlockConverter()); $environment->addConverter(new ListItemConverter()); $environment->addConverter(new CustomParagraphConverter()); $environment->addConverter(new PreformattedConverter()); $environment->addConverter(new TextConverter()); $environment->addConverter(new CheckboxConverter()); $environment->addConverter(new SpacedTagFallbackConverter()); return $environment; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/Markdown/CustomListItemRenderer.php
app/Entities/Tools/Markdown/CustomListItemRenderer.php
<?php namespace BookStack\Entities\Tools\Markdown; use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; use League\CommonMark\Extension\CommonMark\Renderer\Block\ListItemRenderer; use League\CommonMark\Extension\TaskList\TaskListItemMarker; use League\CommonMark\Node\Block\Paragraph; use League\CommonMark\Node\Node; use League\CommonMark\Renderer\ChildNodeRendererInterface; use League\CommonMark\Renderer\NodeRendererInterface; use League\CommonMark\Util\HtmlElement; class CustomListItemRenderer implements NodeRendererInterface { protected ListItemRenderer $baseRenderer; public function __construct() { $this->baseRenderer = new ListItemRenderer(); } /** * @return HtmlElement|string|null */ public function render(Node $node, ChildNodeRendererInterface $childRenderer) { $listItem = $this->baseRenderer->render($node, $childRenderer); if ($node instanceof ListItem && $this->startsTaskListItem($node) && $listItem instanceof HtmlElement) { $listItem->setAttribute('class', 'task-list-item'); } return $listItem; } private function startsTaskListItem(ListItem $block): bool { $firstChild = $block->firstChild(); return $firstChild instanceof Paragraph && $firstChild->firstChild() instanceof TaskListItemMarker; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/Markdown/CheckboxConverter.php
app/Entities/Tools/Markdown/CheckboxConverter.php
<?php namespace BookStack\Entities\Tools\Markdown; use League\HTMLToMarkdown\Converter\ConverterInterface; use League\HTMLToMarkdown\ElementInterface; class CheckboxConverter implements ConverterInterface { public function convert(ElementInterface $element): string { if (strtolower($element->getAttribute('type')) === 'checkbox') { $isChecked = $element->getAttribute('checked') === 'checked'; return $isChecked ? ' [x] ' : ' [ ] '; } return $element->getValue(); } /** * @return string[] */ public function getSupportedTags(): array { return ['input']; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/Markdown/CustomDivConverter.php
app/Entities/Tools/Markdown/CustomDivConverter.php
<?php namespace BookStack\Entities\Tools\Markdown; use League\HTMLToMarkdown\Converter\DivConverter; use League\HTMLToMarkdown\ElementInterface; class CustomDivConverter extends DivConverter { public function convert(ElementInterface $element): string { // Clean up draw.io diagrams $drawIoDiagram = $element->getAttribute('drawio-diagram'); if ($drawIoDiagram) { return "<div drawio-diagram=\"{$drawIoDiagram}\">{$element->getValue()}</div>\n\n"; } return parent::convert($element); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/Markdown/SpacedTagFallbackConverter.php
app/Entities/Tools/Markdown/SpacedTagFallbackConverter.php
<?php namespace BookStack\Entities\Tools\Markdown; use League\HTMLToMarkdown\Converter\ConverterInterface; use League\HTMLToMarkdown\ElementInterface; /** * For certain defined tags, add additional spacing upon the retained HTML content * to separate it out from anything that may be markdown soon afterwards or within. */ class SpacedTagFallbackConverter implements ConverterInterface { public function convert(ElementInterface $element): string { return \html_entity_decode($element->getChildrenAsString()) . "\n\n"; } public function getSupportedTags(): array { return ['summary', 'iframe']; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/Markdown/MarkdownToHtml.php
app/Entities/Tools/Markdown/MarkdownToHtml.php
<?php namespace BookStack\Entities\Tools\Markdown; use BookStack\Facades\Theme; use BookStack\Theming\ThemeEvents; use League\CommonMark\Environment\Environment; use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; use League\CommonMark\Extension\CommonMark\Node\Block\ListItem; use League\CommonMark\Extension\Table\TableExtension; use League\CommonMark\Extension\TaskList\TaskListExtension; use League\CommonMark\MarkdownConverter; class MarkdownToHtml { protected string $markdown; public function __construct(string $markdown) { $this->markdown = $markdown; } public function convert(): string { $environment = new Environment(); $environment->addExtension(new CommonMarkCoreExtension()); $environment->addExtension(new TableExtension()); $environment->addExtension(new TaskListExtension()); $environment->addExtension(new CustomStrikeThroughExtension()); $environment = Theme::dispatch(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $environment) ?? $environment; $converter = new MarkdownConverter($environment); $environment->addRenderer(ListItem::class, new CustomListItemRenderer(), 10); return $converter->convert($this->markdown)->getContent(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/Markdown/CustomStrikethroughRenderer.php
app/Entities/Tools/Markdown/CustomStrikethroughRenderer.php
<?php namespace BookStack\Entities\Tools\Markdown; use League\CommonMark\Extension\Strikethrough\Strikethrough; use League\CommonMark\Node\Node; use League\CommonMark\Renderer\ChildNodeRendererInterface; use League\CommonMark\Renderer\NodeRendererInterface; use League\CommonMark\Util\HtmlElement; /** * This is a somewhat clone of the League\CommonMark\Extension\Strikethrough\StrikethroughRender * class but modified slightly to use <s> HTML tags instead of <del> in order to * match front-end markdown-it rendering. */ class CustomStrikethroughRenderer implements NodeRendererInterface { public function render(Node $node, ChildNodeRendererInterface $childRenderer) { Strikethrough::assertInstanceOf($node); return new HtmlElement('s', $node->data->get('attributes'), $childRenderer->renderNodes($node->children())); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/Markdown/CustomStrikeThroughExtension.php
app/Entities/Tools/Markdown/CustomStrikeThroughExtension.php
<?php namespace BookStack\Entities\Tools\Markdown; use League\CommonMark\Environment\EnvironmentBuilderInterface; use League\CommonMark\Extension\ExtensionInterface; use League\CommonMark\Extension\Strikethrough\Strikethrough; use League\CommonMark\Extension\Strikethrough\StrikethroughDelimiterProcessor; class CustomStrikeThroughExtension implements ExtensionInterface { public function register(EnvironmentBuilderInterface $environment): void { $environment->addDelimiterProcessor(new StrikethroughDelimiterProcessor()); $environment->addRenderer(Strikethrough::class, new CustomStrikethroughRenderer()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Queries/QueryRecentlyViewed.php
app/Entities/Queries/QueryRecentlyViewed.php
<?php namespace BookStack\Entities\Queries; use BookStack\Activity\Models\View; use BookStack\Entities\Tools\MixedEntityListLoader; use BookStack\Permissions\PermissionApplicator; use Illuminate\Support\Collection; class QueryRecentlyViewed { public function __construct( protected PermissionApplicator $permissions, protected MixedEntityListLoader $listLoader, ) { } public function run(int $count, int $page): Collection { $user = user(); if ($user->isGuest()) { return collect(); } $query = $this->permissions->restrictEntityRelationQuery( View::query(), 'views', 'viewable_id', 'viewable_type' ) ->orderBy('views.updated_at', 'desc') ->where('user_id', '=', user()->id); $views = $query ->skip(($page - 1) * $count) ->take($count) ->get(); $this->listLoader->loadIntoRelations($views->all(), 'viewable', false); return $views->pluck('viewable')->filter(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Queries/ProvidesEntityQueries.php
app/Entities/Queries/ProvidesEntityQueries.php
<?php namespace BookStack\Entities\Queries; use BookStack\Entities\Models\Entity; use Illuminate\Database\Eloquent\Builder; /** * Interface for our classes which provide common queries for our * entity objects. Ideally, all queries for entities should run through * these classes. * Any added methods should return a builder instances to allow extension * via building on the query, unless the method starts with 'find' * in which case an entity object should be returned. * (nullable unless it's a *OrFail method). * * @template TModel of Entity */ interface ProvidesEntityQueries { /** * Start a new query for this entity type. * @return Builder<TModel> */ public function start(): Builder; /** * Find the entity of the given ID or return null if not found. */ public function findVisibleById(int $id): ?Entity; /** * Start a query for items that are visible, with selection * configured for list display of this item. * @return Builder<TModel> */ public function visibleForList(): Builder; /** * Start a query for items that are visible, with selection * configured for using the content of the items found. * @return Builder<TModel> */ public function visibleForContent(): Builder; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Queries/PageRevisionQueries.php
app/Entities/Queries/PageRevisionQueries.php
<?php namespace BookStack\Entities\Queries; use BookStack\Entities\Models\PageRevision; use Illuminate\Database\Eloquent\Builder; class PageRevisionQueries { public function start(): Builder { return PageRevision::query(); } public function findLatestVersionBySlugs(string $bookSlug, string $pageSlug): ?PageRevision { return PageRevision::query() ->whereHas('page', function (Builder $query) { $query->scopes('visible'); }) ->where('slug', '=', $pageSlug) ->where('type', '=', 'version') ->where('book_slug', '=', $bookSlug) ->orderBy('created_at', 'desc') ->first(); } public function findLatestCurrentUserDraftsForPageId(int $pageId): ?PageRevision { /** @var ?PageRevision $revision */ $revision = $this->latestCurrentUserDraftsForPageId($pageId)->first(); return $revision; } public function latestCurrentUserDraftsForPageId(int $pageId): Builder { return $this->start() ->where('created_by', '=', user()->id) ->where('type', 'update_draft') ->where('page_id', '=', $pageId) ->orderBy('created_at', 'desc'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Queries/ChapterQueries.php
app/Entities/Queries/ChapterQueries.php
<?php namespace BookStack\Entities\Queries; use BookStack\Entities\Models\Chapter; use BookStack\Exceptions\NotFoundException; use Illuminate\Database\Eloquent\Builder; /** * @implements ProvidesEntityQueries<Chapter> */ class ChapterQueries implements ProvidesEntityQueries { protected static array $listAttributes = [ 'id', 'slug', 'name', 'description', 'priority', 'book_id', 'created_at', 'updated_at', 'owned_by', ]; public function start(): Builder { return Chapter::query(); } public function findVisibleById(int $id): ?Chapter { return $this->start()->scopes('visible')->find($id); } public function findVisibleByIdOrFail(int $id): Chapter { return $this->start()->scopes('visible')->findOrFail($id); } public function findVisibleBySlugsOrFail(string $bookSlug, string $chapterSlug): Chapter { /** @var ?Chapter $chapter */ $chapter = $this->start() ->scopes('visible') ->with('book') ->whereHas('book', function (Builder $query) use ($bookSlug) { $query->where('slug', '=', $bookSlug); }) ->where('slug', '=', $chapterSlug) ->first(); if (is_null($chapter)) { throw new NotFoundException(trans('errors.chapter_not_found')); } return $chapter; } public function usingSlugs(string $bookSlug, string $chapterSlug): Builder { return $this->start() ->where('slug', '=', $chapterSlug) ->whereHas('book', function (Builder $query) use ($bookSlug) { $query->where('slug', '=', $bookSlug); }); } public function visibleForList(): Builder { return $this->start() ->scopes('visible') ->select(array_merge(static::$listAttributes, ['book_slug' => function ($builder) { $builder->select('slug') ->from('entities as books') ->where('type', '=', 'book') ->whereColumn('books.id', '=', 'entities.book_id'); }])); } public function visibleForContent(): Builder { return $this->start()->scopes('visible'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Queries/QueryPopular.php
app/Entities/Queries/QueryPopular.php
<?php namespace BookStack\Entities\Queries; use BookStack\Activity\Models\View; use BookStack\Entities\EntityProvider; use BookStack\Entities\Tools\MixedEntityListLoader; use BookStack\Permissions\PermissionApplicator; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; class QueryPopular { public function __construct( protected PermissionApplicator $permissions, protected EntityProvider $entityProvider, protected MixedEntityListLoader $listLoader, ) { } public function run(int $count, int $page, array $filterModels): Collection { $query = $this->permissions ->restrictEntityRelationQuery(View::query(), 'views', 'viewable_id', 'viewable_type') ->select('*', 'viewable_id', 'viewable_type', DB::raw('SUM(views) as view_count')) ->groupBy('viewable_id', 'viewable_type') ->orderBy('view_count', 'desc'); if (!empty($filterModels)) { $query->whereIn('viewable_type', $this->entityProvider->getMorphClasses($filterModels)); } $views = $query ->skip($count * ($page - 1)) ->take($count) ->get(); $this->listLoader->loadIntoRelations($views->all(), 'viewable', true); return $views->pluck('viewable')->filter(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Queries/BookshelfQueries.php
app/Entities/Queries/BookshelfQueries.php
<?php namespace BookStack\Entities\Queries; use BookStack\Entities\Models\Bookshelf; use BookStack\Exceptions\NotFoundException; use Illuminate\Database\Eloquent\Builder; /** * @implements ProvidesEntityQueries<Bookshelf> */ class BookshelfQueries implements ProvidesEntityQueries { protected static array $listAttributes = [ 'id', 'slug', 'name', 'description', 'created_at', 'updated_at', 'image_id', 'owned_by', ]; /** * @return Builder<Bookshelf> */ public function start(): Builder { return Bookshelf::query(); } public function findVisibleById(int $id): ?Bookshelf { return $this->start()->scopes('visible')->find($id); } public function findVisibleByIdOrFail(int $id): Bookshelf { $shelf = $this->findVisibleById($id); if (is_null($shelf)) { throw new NotFoundException(trans('errors.bookshelf_not_found')); } return $shelf; } public function findVisibleBySlugOrFail(string $slug): Bookshelf { /** @var ?Bookshelf $shelf */ $shelf = $this->start() ->scopes('visible') ->where('slug', '=', $slug) ->first(); if ($shelf === null) { throw new NotFoundException(trans('errors.bookshelf_not_found')); } return $shelf; } public function visibleForList(): Builder { return $this->start()->scopes('visible')->select(static::$listAttributes); } public function visibleForContent(): Builder { return $this->start()->scopes('visible'); } public function visibleForListWithCover(): Builder { return $this->visibleForList()->with('cover'); } public function recentlyViewedForCurrentUser(): Builder { return $this->visibleForList() ->scopes('withLastView') ->having('last_viewed_at', '>', 0) ->orderBy('last_viewed_at', 'desc'); } public function popularForList(): Builder { return $this->visibleForList() ->scopes('withViewCount') ->having('view_count', '>', 0) ->orderBy('view_count', 'desc'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Queries/BookQueries.php
app/Entities/Queries/BookQueries.php
<?php namespace BookStack\Entities\Queries; use BookStack\Entities\Models\Book; use BookStack\Exceptions\NotFoundException; use Illuminate\Database\Eloquent\Builder; /** * @implements ProvidesEntityQueries<Book> */ class BookQueries implements ProvidesEntityQueries { protected static array $listAttributes = [ 'id', 'slug', 'name', 'description', 'created_at', 'updated_at', 'image_id', 'owned_by', ]; /** * @return Builder<Book> */ public function start(): Builder { return Book::query(); } public function findVisibleById(int $id): ?Book { return $this->start()->scopes('visible')->find($id); } public function findVisibleByIdOrFail(int $id): Book { return $this->start()->scopes('visible')->findOrFail($id); } public function findVisibleBySlugOrFail(string $slug): Book { /** @var ?Book $book */ $book = $this->start() ->scopes('visible') ->where('slug', '=', $slug) ->first(); if ($book === null) { throw new NotFoundException(trans('errors.book_not_found')); } return $book; } public function visibleForList(): Builder { return $this->start()->scopes('visible') ->select(static::$listAttributes); } public function visibleForContent(): Builder { return $this->start()->scopes('visible'); } public function visibleForListWithCover(): Builder { return $this->visibleForList()->with('cover'); } public function recentlyViewedForCurrentUser(): Builder { return $this->visibleForList() ->scopes('withLastView') ->having('last_viewed_at', '>', 0) ->orderBy('last_viewed_at', 'desc'); } public function popularForList(): Builder { return $this->visibleForList() ->scopes('withViewCount') ->having('view_count', '>', 0) ->orderBy('view_count', 'desc'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Queries/PageQueries.php
app/Entities/Queries/PageQueries.php
<?php namespace BookStack\Entities\Queries; use BookStack\Entities\Models\Page; use BookStack\Exceptions\NotFoundException; use Illuminate\Database\Eloquent\Builder; /** * @implements ProvidesEntityQueries<Page> */ class PageQueries implements ProvidesEntityQueries { protected static array $contentAttributes = [ 'name', 'id', 'slug', 'book_id', 'chapter_id', 'draft', 'template', 'html', 'markdown', 'text', 'created_at', 'updated_at', 'priority', 'created_by', 'updated_by', 'owned_by', ]; protected static array $listAttributes = [ 'name', 'id', 'slug', 'book_id', 'chapter_id', 'draft', 'template', 'text', 'created_at', 'updated_at', 'priority', 'owned_by', ]; /** * @return Builder<Page> */ public function start(): Builder { return Page::query(); } public function findVisibleById(int $id): ?Page { return $this->start()->scopes('visible')->find($id); } public function findVisibleByIdOrFail(int $id): Page { $page = $this->findVisibleById($id); if (is_null($page)) { throw new NotFoundException(trans('errors.page_not_found')); } return $page; } public function findVisibleBySlugsOrFail(string $bookSlug, string $pageSlug): Page { /** @var ?Page $page */ $page = $this->start()->with('book') ->scopes('visible') ->whereHas('book', function (Builder $query) use ($bookSlug) { $query->where('slug', '=', $bookSlug); }) ->where('slug', '=', $pageSlug) ->first(); if (is_null($page)) { throw new NotFoundException(trans('errors.page_not_found')); } return $page; } public function usingSlugs(string $bookSlug, string $pageSlug): Builder { return $this->start() ->where('slug', '=', $pageSlug) ->whereHas('book', function (Builder $query) use ($bookSlug) { $query->where('slug', '=', $bookSlug); }); } /** * @return Builder<Page> */ public function visibleForList(): Builder { return $this->start() ->scopes('visible') ->select($this->mergeBookSlugForSelect(static::$listAttributes)); } /** * @return Builder<Page> */ public function visibleForContent(): Builder { return $this->start()->scopes('visible'); } public function visibleForChapterList(int $chapterId): Builder { return $this->visibleForList() ->where('chapter_id', '=', $chapterId) ->orderBy('draft', 'desc') ->orderBy('priority', 'asc'); } public function visibleWithContents(): Builder { return $this->start() ->scopes('visible') ->select($this->mergeBookSlugForSelect(static::$contentAttributes)); } public function currentUserDraftsForList(): Builder { return $this->visibleForList() ->where('draft', '=', true) ->where('created_by', '=', user()->id); } public function visibleTemplates(bool $includeContents = false): Builder { $base = $includeContents ? $this->visibleWithContents() : $this->visibleForList(); return $base->where('template', '=', true); } protected function mergeBookSlugForSelect(array $columns): array { return array_merge($columns, ['book_slug' => function ($builder) { $builder->select('slug') ->from('entities as books') ->where('type', '=', 'book') ->whereColumn('books.id', '=', 'entities.book_id'); }]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Queries/QueryTopFavourites.php
app/Entities/Queries/QueryTopFavourites.php
<?php namespace BookStack\Entities\Queries; use BookStack\Activity\Models\Favourite; use BookStack\Entities\Tools\MixedEntityListLoader; use BookStack\Permissions\PermissionApplicator; use Illuminate\Database\Query\JoinClause; class QueryTopFavourites { public function __construct( protected PermissionApplicator $permissions, protected MixedEntityListLoader $listLoader, ) { } public function run(int $count, int $skip = 0) { $user = user(); if ($user->isGuest()) { return collect(); } $query = $this->permissions ->restrictEntityRelationQuery(Favourite::query(), 'favourites', 'favouritable_id', 'favouritable_type') ->select('favourites.*') ->leftJoin('views', function (JoinClause $join) { $join->on('favourites.favouritable_id', '=', 'views.viewable_id'); $join->on('favourites.favouritable_type', '=', 'views.viewable_type'); $join->where('views.user_id', '=', user()->id); }) ->orderBy('views.views', 'desc') ->where('favourites.user_id', '=', user()->id); $favourites = $query ->skip($skip) ->take($count) ->get(); $this->listLoader->loadIntoRelations($favourites->all(), 'favouritable', false); return $favourites->pluck('favouritable')->filter(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Queries/EntityQueries.php
app/Entities/Queries/EntityQueries.php
<?php namespace BookStack\Entities\Queries; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\EntityTable; use BookStack\Entities\Tools\SlugHistory; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\Query\JoinClause; use Illuminate\Support\Facades\DB; use InvalidArgumentException; class EntityQueries { public function __construct( public BookshelfQueries $shelves, public BookQueries $books, public ChapterQueries $chapters, public PageQueries $pages, public PageRevisionQueries $revisions, protected SlugHistory $slugHistory, ) { } /** * Find an entity via an identifier string in the format: * {type}:{id} * Example: (book:5). */ public function findVisibleByStringIdentifier(string $identifier): ?Entity { $explodedId = explode(':', $identifier); $entityType = $explodedId[0]; $entityId = intval($explodedId[1]); return $this->findVisibleById($entityType, $entityId); } /** * Find an entity by its ID. */ public function findVisibleById(string $type, int $id): ?Entity { $queries = $this->getQueriesForType($type); return $queries->findVisibleById($id); } /** * Find an entity by looking up old slugs in the slug history. */ public function findVisibleByOldSlugs(string $type, string $slug, string $parentSlug = ''): ?Entity { $id = $this->slugHistory->lookupEntityIdUsingSlugs($type, $slug, $parentSlug); if ($id === null) { return null; } return $this->findVisibleById($type, $id); } /** * Start a query across all entity types. * Combines the description/text fields into a single 'description' field. * @return Builder<EntityTable> */ public function visibleForList(): Builder { $rawDescriptionField = DB::raw('COALESCE(description, text) as description'); $bookSlugSelect = function (QueryBuilder $query) { return $query->select('slug')->from('entities as books') ->whereColumn('books.id', '=', 'entities.book_id') ->where('type', '=', 'book'); }; return EntityTable::query()->scopes('visible') ->select(['id', 'type', 'name', 'slug', 'book_id', 'chapter_id', 'created_at', 'updated_at', 'draft', 'book_slug' => $bookSlugSelect, $rawDescriptionField]) ->leftJoin('entity_container_data', function (JoinClause $join) { $join->on('entity_container_data.entity_id', '=', 'entities.id') ->on('entity_container_data.entity_type', '=', 'entities.type'); })->leftJoin('entity_page_data', function (JoinClause $join) { $join->on('entity_page_data.page_id', '=', 'entities.id') ->where('entities.type', '=', 'page'); }); } /** * Start a query of visible entities of the given type, * suitable for listing display. * @return Builder<Entity> */ public function visibleForListForType(string $entityType): Builder { $queries = $this->getQueriesForType($entityType); return $queries->visibleForList(); } /** * Start a query of visible entities of the given type, * suitable for using the contents of the items. * @return Builder<Entity> */ public function visibleForContentForType(string $entityType): Builder { $queries = $this->getQueriesForType($entityType); return $queries->visibleForContent(); } protected function getQueriesForType(string $type): ProvidesEntityQueries { $queries = match ($type) { 'page' => $this->pages, 'chapter' => $this->chapters, 'book' => $this->books, 'bookshelf' => $this->shelves, default => null, }; if (is_null($queries)) { throw new InvalidArgumentException("No entity query class configured for {$type}"); } return $queries; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Repos/RevisionRepo.php
app/Entities/Repos/RevisionRepo.php
<?php namespace BookStack\Entities\Repos; use BookStack\Entities\Models\Page; use BookStack\Entities\Models\PageRevision; use BookStack\Entities\Queries\PageRevisionQueries; class RevisionRepo { public function __construct( protected PageRevisionQueries $queries, ) { } /** * Delete all drafts revisions, for the given page, belonging to the current user. */ public function deleteDraftsForCurrentUser(Page $page): void { $this->queries->latestCurrentUserDraftsForPageId($page->id)->delete(); } /** * Get a user update_draft page revision to update for the given page. * Checks for an existing revision before providing a fresh one. */ public function getNewDraftForCurrentUser(Page $page): PageRevision { $draft = $this->queries->findLatestCurrentUserDraftsForPageId($page->id); if ($draft) { return $draft; } $draft = new PageRevision(); $draft->page_id = $page->id; $draft->slug = $page->slug; $draft->book_slug = $page->book->slug; $draft->created_by = user()->id; $draft->type = 'update_draft'; return $draft; } /** * Store a new revision in the system for the given page. */ public function storeNewForPage(Page $page, ?string $summary = null): PageRevision { $revision = new PageRevision(); $revision->name = $page->name; $revision->html = $page->html; $revision->markdown = $page->markdown; $revision->text = $page->text; $revision->page_id = $page->id; $revision->slug = $page->slug; $revision->book_slug = $page->book->slug; $revision->created_by = user()->id; $revision->created_at = $page->updated_at; $revision->type = 'version'; $revision->summary = $summary; $revision->revision_number = $page->revision_count; $revision->save(); $this->deleteOldRevisions($page); return $revision; } /** * Delete old revisions, for the given page, from the system. */ protected function deleteOldRevisions(Page $page): void { $revisionLimit = config('app.revision_limit'); if ($revisionLimit === false) { return; } $revisionsToDelete = PageRevision::query() ->where('page_id', '=', $page->id) ->orderBy('created_at', 'desc') ->skip(intval($revisionLimit)) ->take(10) ->get(['id']); if ($revisionsToDelete->count() > 0) { PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete(); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Repos/BookRepo.php
app/Entities/Repos/BookRepo.php
<?php namespace BookStack\Entities\Repos; use BookStack\Activity\ActivityType; use BookStack\Activity\TagRepo; use BookStack\Entities\Models\Book; use BookStack\Entities\Tools\TrashCan; use BookStack\Exceptions\ImageUploadException; use BookStack\Facades\Activity; use BookStack\Sorting\SortRule; use BookStack\Uploads\ImageRepo; use BookStack\Util\DatabaseTransaction; use Exception; use Illuminate\Http\UploadedFile; class BookRepo { public function __construct( protected BaseRepo $baseRepo, protected TagRepo $tagRepo, protected ImageRepo $imageRepo, protected TrashCan $trashCan, ) { } /** * Create a new book in the system. */ public function create(array $input): Book { return (new DatabaseTransaction(function () use ($input) { $book = $this->baseRepo->create(new Book(), $input); $this->baseRepo->updateCoverImage($book, $input['image'] ?? null); $book->defaultTemplate()->setFromId(intval($input['default_template_id'] ?? null)); Activity::add(ActivityType::BOOK_CREATE, $book); $defaultBookSortSetting = intval(setting('sorting-book-default', '0')); if ($defaultBookSortSetting && SortRule::query()->find($defaultBookSortSetting)) { $book->sort_rule_id = $defaultBookSortSetting; } $book->save(); return $book; }))->run(); } /** * Update the given book. */ public function update(Book $book, array $input): Book { $book = $this->baseRepo->update($book, $input); if (array_key_exists('default_template_id', $input)) { $book->defaultTemplate()->setFromId(intval($input['default_template_id'])); } if (array_key_exists('image', $input)) { $this->baseRepo->updateCoverImage($book, $input['image'], $input['image'] === null); } $book->save(); Activity::add(ActivityType::BOOK_UPDATE, $book); return $book; } /** * Update the given book's cover image or clear it. * * @throws ImageUploadException * @throws Exception */ public function updateCoverImage(Book $book, ?UploadedFile $coverImage, bool $removeImage = false): void { $this->baseRepo->updateCoverImage($book, $coverImage, $removeImage); } /** * Remove a book from the system. * * @throws Exception */ public function destroy(Book $book): void { $this->trashCan->softDestroyBook($book); Activity::add(ActivityType::BOOK_DELETE, $book); $this->trashCan->autoClearOld(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Repos/BookshelfRepo.php
app/Entities/Repos/BookshelfRepo.php
<?php namespace BookStack\Entities\Repos; use BookStack\Activity\ActivityType; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Queries\BookQueries; use BookStack\Entities\Tools\TrashCan; use BookStack\Facades\Activity; use BookStack\Util\DatabaseTransaction; use Exception; class BookshelfRepo { public function __construct( protected BaseRepo $baseRepo, protected BookQueries $bookQueries, protected TrashCan $trashCan, ) { } /** * Create a new shelf in the system. */ public function create(array $input, array $bookIds): Bookshelf { return (new DatabaseTransaction(function () use ($input, $bookIds) { $shelf = $this->baseRepo->create(new Bookshelf(), $input); $this->baseRepo->updateCoverImage($shelf, $input['image'] ?? null); $this->updateBooks($shelf, $bookIds); Activity::add(ActivityType::BOOKSHELF_CREATE, $shelf); return $shelf; }))->run(); } /** * Update an existing shelf in the system using the given input. */ public function update(Bookshelf $shelf, array $input, ?array $bookIds): Bookshelf { $shelf = $this->baseRepo->update($shelf, $input); if (!is_null($bookIds)) { $this->updateBooks($shelf, $bookIds); } if (array_key_exists('image', $input)) { $this->baseRepo->updateCoverImage($shelf, $input['image'], $input['image'] === null); } Activity::add(ActivityType::BOOKSHELF_UPDATE, $shelf); return $shelf; } /** * Update which books are assigned to this shelf by syncing the given book ids. * Function ensures the managed books are visible to the current user and existing, * and that the user does not alter the assignment of books that are not visible to them. */ protected function updateBooks(Bookshelf $shelf, array $bookIds): void { $numericIDs = collect($bookIds)->map(function ($id) { return intval($id); }); $existingBookIds = $shelf->books()->pluck('id')->toArray(); $visibleExistingBookIds = $this->bookQueries->visibleForList() ->whereIn('id', $existingBookIds) ->pluck('id') ->toArray(); $nonVisibleExistingBookIds = array_values(array_diff($existingBookIds, $visibleExistingBookIds)); $newIdsToAssign = $this->bookQueries->visibleForList() ->whereIn('id', $bookIds) ->pluck('id') ->toArray(); $maxNewIndex = max($numericIDs->keys()->toArray() ?: [0]); $syncData = []; foreach ($newIdsToAssign as $id) { $syncData[$id] = ['order' => $numericIDs->search($id)]; } foreach ($nonVisibleExistingBookIds as $index => $id) { $syncData[$id] = ['order' => $maxNewIndex + ($index + 1)]; } $shelf->books()->sync($syncData); } /** * Remove a bookshelf from the system. * * @throws Exception */ public function destroy(Bookshelf $shelf): void { $this->trashCan->softDestroyShelf($shelf); Activity::add(ActivityType::BOOKSHELF_DELETE, $shelf); $this->trashCan->autoClearOld(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Repos/BaseRepo.php
app/Entities/Repos/BaseRepo.php
<?php namespace BookStack\Entities\Repos; use BookStack\Activity\TagRepo; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\HasCoverInterface; use BookStack\Entities\Models\HasDescriptionInterface; use BookStack\Entities\Models\Entity; use BookStack\Entities\Queries\PageQueries; use BookStack\Entities\Tools\SlugGenerator; use BookStack\Entities\Tools\SlugHistory; use BookStack\Exceptions\ImageUploadException; use BookStack\References\ReferenceStore; use BookStack\References\ReferenceUpdater; use BookStack\Sorting\BookSorter; use BookStack\Uploads\ImageRepo; use BookStack\Util\HtmlDescriptionFilter; use Illuminate\Http\UploadedFile; class BaseRepo { public function __construct( protected TagRepo $tagRepo, protected ImageRepo $imageRepo, protected ReferenceUpdater $referenceUpdater, protected ReferenceStore $referenceStore, protected PageQueries $pageQueries, protected BookSorter $bookSorter, protected SlugGenerator $slugGenerator, protected SlugHistory $slugHistory, ) { } /** * Create a new entity in the system. * @template T of Entity * @param T $entity * @return T */ public function create(Entity $entity, array $input): Entity { $entity = (clone $entity)->refresh(); $entity->fill($input); $entity->forceFill([ 'created_by' => user()->id, 'updated_by' => user()->id, 'owned_by' => user()->id, ]); $this->refreshSlug($entity); if ($entity instanceof HasDescriptionInterface) { $this->updateDescription($entity, $input); } $entity->save(); if (isset($input['tags'])) { $this->tagRepo->saveTagsToEntity($entity, $input['tags']); } $entity->refresh(); $entity->rebuildPermissions(); $entity->indexForSearch(); $this->referenceStore->updateForEntity($entity); return $entity; } /** * Update the given entity. * @template T of Entity * @param T $entity * @return T */ public function update(Entity $entity, array $input): Entity { $oldUrl = $entity->getUrl(); $entity->fill($input); $entity->updated_by = user()->id; if ($entity->isDirty('name') || empty($entity->slug)) { $this->refreshSlug($entity); } if ($entity instanceof HasDescriptionInterface) { $this->updateDescription($entity, $input); } $entity->save(); if (isset($input['tags'])) { $this->tagRepo->saveTagsToEntity($entity, $input['tags']); $entity->touch(); } $entity->indexForSearch(); $this->referenceStore->updateForEntity($entity); if ($oldUrl !== $entity->getUrl()) { $this->referenceUpdater->updateEntityReferences($entity, $oldUrl); } return $entity; } /** * Update the given items' cover image or clear it. * * @throws ImageUploadException * @throws \Exception */ public function updateCoverImage(Entity&HasCoverInterface $entity, ?UploadedFile $coverImage, bool $removeImage = false): void { if ($coverImage) { $imageType = 'cover_' . $entity->type; $this->imageRepo->destroyImage($entity->coverInfo()->getImage()); $image = $this->imageRepo->saveNew($coverImage, $imageType, $entity->id, 512, 512, true); $entity->coverInfo()->setImage($image); $entity->save(); } if ($removeImage) { $this->imageRepo->destroyImage($entity->coverInfo()->getImage()); $entity->coverInfo()->setImage(null); $entity->save(); } } /** * Sort the parent of the given entity if any auto sort actions are set for it. * Typically ran during create/update/insert events. */ public function sortParent(Entity $entity): void { if ($entity instanceof BookChild) { $book = $entity->book; $this->bookSorter->runBookAutoSort($book); } } /** * Update the description of the given entity from input data. */ protected function updateDescription(Entity $entity, array $input): void { if (!$entity instanceof HasDescriptionInterface) { return; } if (isset($input['description_html'])) { $entity->descriptionInfo()->set( HtmlDescriptionFilter::filterFromString($input['description_html']), html_entity_decode(strip_tags($input['description_html'])) ); } else if (isset($input['description'])) { $entity->descriptionInfo()->set('', $input['description']); } } /** * Refresh the slug for the given entity. */ public function refreshSlug(Entity $entity): void { $this->slugHistory->recordForEntity($entity); $this->slugGenerator->regenerateForEntity($entity); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Repos/PageRepo.php
app/Entities/Repos/PageRepo.php
<?php namespace BookStack\Entities\Repos; use BookStack\Activity\ActivityType; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Entities\Models\PageRevision; use BookStack\Entities\Queries\EntityQueries; use BookStack\Entities\Tools\BookContents; use BookStack\Entities\Tools\PageContent; use BookStack\Entities\Tools\PageEditorType; use BookStack\Entities\Tools\ParentChanger; use BookStack\Entities\Tools\TrashCan; use BookStack\Exceptions\MoveOperationException; use BookStack\Exceptions\PermissionsException; use BookStack\Facades\Activity; use BookStack\Permissions\Permission; use BookStack\References\ReferenceStore; use BookStack\References\ReferenceUpdater; use BookStack\Util\DatabaseTransaction; use Exception; class PageRepo { public function __construct( protected BaseRepo $baseRepo, protected RevisionRepo $revisionRepo, protected EntityQueries $entityQueries, protected ReferenceStore $referenceStore, protected ReferenceUpdater $referenceUpdater, protected TrashCan $trashCan, protected ParentChanger $parentChanger, ) { } /** * Get a new draft page belonging to the given parent entity. */ public function getNewDraftPage(Entity $parent): Page { $page = (new Page())->forceFill([ 'name' => trans('entities.pages_initial_name'), 'created_by' => user()->id, 'owned_by' => user()->id, 'updated_by' => user()->id, 'draft' => true, 'editor' => PageEditorType::getSystemDefault()->value, 'html' => '', 'markdown' => '', 'text' => '', ]); if ($parent instanceof Chapter) { $page->chapter_id = $parent->id; $page->book_id = $parent->book_id; } else { $page->book_id = $parent->id; } $defaultTemplate = $page->chapter?->defaultTemplate()->get() ?? $page->book?->defaultTemplate()->get(); if ($defaultTemplate) { $page->forceFill([ 'html' => $defaultTemplate->html, 'markdown' => $defaultTemplate->markdown, ]); $page->text = (new PageContent($page))->toPlainText(); } (new DatabaseTransaction(function () use ($page) { $page->save(); $page->rebuildPermissions(); }))->run(); return $page; } /** * Publish a draft page to make it a live, non-draft page. */ public function publishDraft(Page $draft, array $input): Page { return (new DatabaseTransaction(function () use ($draft, $input) { $draft->draft = false; $draft->revision_count = 1; $draft->priority = $this->getNewPriority($draft); $this->updateTemplateStatusAndContentFromInput($draft, $input); $draft = $this->baseRepo->update($draft, $input); $draft->rebuildPermissions(); $summary = trim($input['summary'] ?? '') ?: trans('entities.pages_initial_revision'); $this->revisionRepo->storeNewForPage($draft, $summary); $draft->refresh(); Activity::add(ActivityType::PAGE_CREATE, $draft); $this->baseRepo->sortParent($draft); return $draft; }))->run(); } /** * Directly update the content for the given page from the provided input. * Used for direct content access in a way that performs required changes * (Search index and reference regen) without performing an official update. */ public function setContentFromInput(Page $page, array $input): void { $this->updateTemplateStatusAndContentFromInput($page, $input); $this->baseRepo->update($page, []); } /** * Update a page in the system. */ public function update(Page $page, array $input): Page { // Hold the old details to compare later $oldName = $page->name; $oldHtml = $page->html; $oldMarkdown = $page->markdown; $this->updateTemplateStatusAndContentFromInput($page, $input); $page = $this->baseRepo->update($page, $input); // Update with new details $page->revision_count++; $page->save(); // Remove all update drafts for this user and page. $this->revisionRepo->deleteDraftsForCurrentUser($page); // Save a revision after updating $summary = trim($input['summary'] ?? ''); $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml; $nameChanged = isset($input['name']) && $input['name'] !== $oldName; $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown; if ($htmlChanged || $nameChanged || $markdownChanged || $summary) { $this->revisionRepo->storeNewForPage($page, $summary); } Activity::add(ActivityType::PAGE_UPDATE, $page); $this->baseRepo->sortParent($page); return $page; } protected function updateTemplateStatusAndContentFromInput(Page $page, array $input): void { if (isset($input['template']) && userCan(Permission::TemplatesManage)) { $page->template = ($input['template'] === 'true'); } $pageContent = new PageContent($page); $defaultEditor = PageEditorType::getSystemDefault(); $currentEditor = PageEditorType::forPage($page) ?: $defaultEditor; $inputEditor = PageEditorType::fromRequestValue($input['editor'] ?? '') ?? $currentEditor; $newEditor = $currentEditor; $haveInput = isset($input['markdown']) || isset($input['html']); $inputEmpty = empty($input['markdown']) && empty($input['html']); if ($haveInput && $inputEmpty) { $pageContent->setNewHTML('', user()); } elseif (!empty($input['markdown']) && is_string($input['markdown'])) { $newEditor = PageEditorType::Markdown; $pageContent->setNewMarkdown($input['markdown'], user()); } elseif (isset($input['html'])) { $newEditor = ($inputEditor->isHtmlBased() ? $inputEditor : null) ?? ($defaultEditor->isHtmlBased() ? $defaultEditor : null) ?? PageEditorType::WysiwygTinymce; $pageContent->setNewHTML($input['html'], user()); } if (($newEditor !== $currentEditor || empty($page->editor)) && userCan(Permission::EditorChange)) { $page->editor = $newEditor->value; } elseif (empty($page->editor)) { $page->editor = $defaultEditor->value; } } /** * Save a page update draft. */ public function updatePageDraft(Page $page, array $input): Page|PageRevision { // If the page itself is a draft, simply update that if ($page->draft) { $this->updateTemplateStatusAndContentFromInput($page, $input); $page->forceFill(array_intersect_key($input, array_flip(['name'])))->save(); $page->save(); return $page; } // Otherwise, save the data to a revision $draft = $this->revisionRepo->getNewDraftForCurrentUser($page); $draft->fill($input); if (!empty($input['markdown'])) { $draft->markdown = $input['markdown']; $draft->html = ''; } else { $draft->html = $input['html']; $draft->markdown = ''; } $draft->save(); return $draft; } /** * Destroy a page from the system. * * @throws Exception */ public function destroy(Page $page): void { $this->trashCan->softDestroyPage($page); Activity::add(ActivityType::PAGE_DELETE, $page); $this->trashCan->autoClearOld(); } /** * Restores a revision's content back into a page. */ public function restoreRevision(Page $page, int $revisionId): Page { $oldUrl = $page->getUrl(); $page->revision_count++; /** @var PageRevision $revision */ $revision = $page->revisions()->where('id', '=', $revisionId)->first(); $page->fill($revision->toArray()); $content = new PageContent($page); if (!empty($revision->markdown)) { $content->setNewMarkdown($revision->markdown, user()); } else { $content->setNewHTML($revision->html, user()); } $page->updated_by = user()->id; $this->baseRepo->refreshSlug($page); $page->save(); $page->indexForSearch(); $this->referenceStore->updateForEntity($page); $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]); $this->revisionRepo->storeNewForPage($page, $summary); if ($oldUrl !== $page->getUrl()) { $this->referenceUpdater->updateEntityReferences($page, $oldUrl); } Activity::add(ActivityType::PAGE_RESTORE, $page); Activity::add(ActivityType::REVISION_RESTORE, $revision); $this->baseRepo->sortParent($page); return $page; } /** * Move the given page into a new parent book or chapter. * The $parentIdentifier must be a string of the following format: * 'book:<id>' (book:5). * * @throws MoveOperationException * @throws PermissionsException */ public function move(Page $page, string $parentIdentifier): Entity { $parent = $this->entityQueries->findVisibleByStringIdentifier($parentIdentifier); if (!$parent instanceof Chapter && !$parent instanceof Book) { throw new MoveOperationException('Book or chapter to move page into not found'); } if (!userCan(Permission::PageCreate, $parent)) { throw new PermissionsException('User does not have permission to create a page within the new parent'); } return (new DatabaseTransaction(function () use ($page, $parent) { $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null; $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id; $this->parentChanger->changeBook($page, $newBookId); $page->rebuildPermissions(); Activity::add(ActivityType::PAGE_MOVE, $page); $this->baseRepo->sortParent($page); return $parent; }))->run(); } /** * Get a new priority for a page. */ protected function getNewPriority(Page $page): int { $parent = $page->getParent(); if ($parent instanceof Chapter) { /** @var ?Page $lastPage */ $lastPage = $parent->pages('desc')->first(); return $lastPage ? $lastPage->priority + 1 : 0; } return (new BookContents($page->book))->getLastPriority() + 1; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Repos/ChapterRepo.php
app/Entities/Repos/ChapterRepo.php
<?php namespace BookStack\Entities\Repos; use BookStack\Activity\ActivityType; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Queries\EntityQueries; use BookStack\Entities\Tools\BookContents; use BookStack\Entities\Tools\ParentChanger; use BookStack\Entities\Tools\TrashCan; use BookStack\Exceptions\MoveOperationException; use BookStack\Exceptions\PermissionsException; use BookStack\Facades\Activity; use BookStack\Permissions\Permission; use BookStack\Util\DatabaseTransaction; use Exception; class ChapterRepo { public function __construct( protected BaseRepo $baseRepo, protected EntityQueries $entityQueries, protected TrashCan $trashCan, protected ParentChanger $parentChanger, ) { } /** * Create a new chapter in the system. */ public function create(array $input, Book $parentBook): Chapter { return (new DatabaseTransaction(function () use ($input, $parentBook) { $chapter = new Chapter(); $chapter->book_id = $parentBook->id; $chapter->priority = (new BookContents($parentBook))->getLastPriority() + 1; $chapter = $this->baseRepo->create($chapter, $input); $chapter->defaultTemplate()->setFromId(intval($input['default_template_id'] ?? null)); $chapter->save(); Activity::add(ActivityType::CHAPTER_CREATE, $chapter); $this->baseRepo->sortParent($chapter); return $chapter; }))->run(); } /** * Update the given chapter. */ public function update(Chapter $chapter, array $input): Chapter { $chapter = $this->baseRepo->update($chapter, $input); if (array_key_exists('default_template_id', $input)) { $chapter->defaultTemplate()->setFromId(intval($input['default_template_id'])); } $chapter->save(); Activity::add(ActivityType::CHAPTER_UPDATE, $chapter); $this->baseRepo->sortParent($chapter); return $chapter; } /** * Remove a chapter from the system. * * @throws Exception */ public function destroy(Chapter $chapter): void { $this->trashCan->softDestroyChapter($chapter); Activity::add(ActivityType::CHAPTER_DELETE, $chapter); $this->trashCan->autoClearOld(); } /** * Move the given chapter into a new parent book. * The $parentIdentifier must be a string of the following format: * 'book:<id>' (book:5). * * @throws MoveOperationException * @throws PermissionsException */ public function move(Chapter $chapter, string $parentIdentifier): Book { $parent = $this->entityQueries->findVisibleByStringIdentifier($parentIdentifier); if (!$parent instanceof Book) { throw new MoveOperationException('Book to move chapter into not found'); } if (!userCan(Permission::ChapterCreate, $parent)) { throw new PermissionsException('User does not have permission to create a chapter within the chosen book'); } return (new DatabaseTransaction(function () use ($chapter, $parent) { $this->parentChanger->changeBook($chapter, $parent->id); $chapter->rebuildPermissions(); Activity::add(ActivityType::CHAPTER_MOVE, $chapter); $this->baseRepo->sortParent($chapter); return $parent; }))->run(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Repos/DeletionRepo.php
app/Entities/Repos/DeletionRepo.php
<?php namespace BookStack\Entities\Repos; use BookStack\Activity\ActivityType; use BookStack\Entities\Models\Deletion; use BookStack\Entities\Tools\TrashCan; use BookStack\Facades\Activity; class DeletionRepo { public function __construct( protected TrashCan $trashCan ) { } public function restore(int $id): int { /** @var Deletion $deletion */ $deletion = Deletion::query()->findOrFail($id); Activity::add(ActivityType::RECYCLE_BIN_RESTORE, $deletion); return $this->trashCan->restoreFromDeletion($deletion); } public function destroy(int $id): int { /** @var Deletion $deletion */ $deletion = Deletion::query()->findOrFail($id); Activity::add(ActivityType::RECYCLE_BIN_DESTROY, $deletion); return $this->trashCan->destroyFromDeletion($deletion); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/EmailConfirmationService.php
app/Access/EmailConfirmationService.php
<?php namespace BookStack\Access; use BookStack\Access\Notifications\ConfirmEmailNotification; use BookStack\Exceptions\ConfirmationEmailException; use BookStack\Users\Models\User; class EmailConfirmationService extends UserTokenService { protected string $tokenTable = 'email_confirmations'; protected int $expiryTime = 24; /** * Create new confirmation for a user, * Also removes any existing old ones. * * @throws ConfirmationEmailException */ public function sendConfirmation(User $user): void { if ($user->email_confirmed) { throw new ConfirmationEmailException(trans('errors.email_already_confirmed'), '/login'); } $this->deleteByUser($user); $token = $this->createTokenForUser($user); $user->notify(new ConfirmEmailNotification($token)); } /** * Check if confirmation is required in this instance. */ public function confirmationRequired(): bool { return setting('registration-confirmation') || setting('registration-restrict'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Saml2Service.php
app/Access/Saml2Service.php
<?php namespace BookStack\Access; use BookStack\Exceptions\JsonDebugException; use BookStack\Exceptions\SamlException; use BookStack\Exceptions\StoppedAuthenticationException; use BookStack\Exceptions\UserRegistrationException; use BookStack\Users\Models\User; use Exception; use OneLogin\Saml2\Auth; use OneLogin\Saml2\Constants; use OneLogin\Saml2\Error; use OneLogin\Saml2\IdPMetadataParser; use OneLogin\Saml2\ValidationError; /** * Class Saml2Service * Handles any app-specific SAML tasks. */ class Saml2Service { protected array $config; public function __construct( protected RegistrationService $registrationService, protected LoginService $loginService, protected GroupSyncService $groupSyncService ) { $this->config = config('saml2'); } /** * Initiate a login flow. * * @throws Error */ public function login(): array { $toolKit = $this->getToolkit(); $returnRoute = url('/saml2/acs'); return [ 'url' => $toolKit->login($returnRoute, [], false, false, true), 'id' => $toolKit->getLastRequestID(), ]; } /** * Initiate a logout flow. * Returns the SAML2 request ID, and the URL to redirect the user to. * * @throws Error * @return array{url: string, id: ?string} */ public function logout(User $user): array { $toolKit = $this->getToolkit(); $sessionIndex = session()->get('saml2_session_index'); $returnUrl = url($this->loginService->logout()); try { $url = $toolKit->logout( $returnUrl, [], $user->email, $sessionIndex, true, Constants::NAMEID_EMAIL_ADDRESS ); $id = $toolKit->getLastRequestID(); } catch (Error $error) { if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) { throw $error; } $url = $returnUrl; $id = null; } return ['url' => $url, 'id' => $id]; } /** * Process the ACS response from the idp and return the * matching, or new if registration active, user matched to the idp. * Returns null if not authenticated. * * @throws Error * @throws SamlException * @throws ValidationError * @throws JsonDebugException * @throws UserRegistrationException */ public function processAcsResponse(?string $requestId, string $samlResponse): ?User { // The SAML2 toolkit expects the response to be within the $_POST superglobal // so we need to manually put it back there at this point. $_POST['SAMLResponse'] = $samlResponse; $toolkit = $this->getToolkit(); $toolkit->processResponse($requestId); $errors = $toolkit->getErrors(); if (!empty($errors)) { $reason = $toolkit->getLastErrorReason(); $message = 'Invalid ACS Response; Errors: ' . implode(', ', $errors); $message .= $reason ? "; Reason: {$reason}" : ''; throw new Error($message); } if (!$toolkit->isAuthenticated()) { return null; } $attrs = $toolkit->getAttributes(); $id = $toolkit->getNameId(); session()->put('saml2_session_index', $toolkit->getSessionIndex()); return $this->processLoginCallback($id, $attrs); } /** * Process a response for the single logout service. * * @throws Error */ public function processSlsResponse(?string $requestId): string { $toolkit = $this->getToolkit(); // The $retrieveParametersFromServer in the call below will mean the library will take the query // parameters, used for the response signing, from the raw $_SERVER['QUERY_STRING'] // value so that the exact encoding format is matched when checking the signature. // This is primarily due to ADFS encoding query params with lowercase percent encoding while // PHP (And most other sensible providers) standardise on uppercase. /** @var ?string $samlRedirect */ $samlRedirect = $toolkit->processSLO(true, $requestId, true, null, true); $errors = $toolkit->getErrors(); if (!empty($errors)) { throw new Error( 'Invalid SLS Response: ' . implode(', ', $errors) ); } $defaultBookStackRedirect = $this->loginService->logout(); return $samlRedirect ?? $defaultBookStackRedirect; } /** * Get the metadata for this service provider. * * @throws Error */ public function metadata(): string { $toolKit = $this->getToolkit(true); $settings = $toolKit->getSettings(); $metadata = $settings->getSPMetadata(); $errors = $settings->validateMetadata($metadata); if (!empty($errors)) { throw new Error( 'Invalid SP metadata: ' . implode(', ', $errors), Error::METADATA_SP_INVALID ); } return $metadata; } /** * Load the underlying Onelogin SAML2 toolkit. * * @throws Error * @throws Exception */ protected function getToolkit(bool $spOnly = false): Auth { $settings = $this->config['onelogin']; $overrides = $this->config['onelogin_overrides'] ?? []; if ($overrides && is_string($overrides)) { $overrides = json_decode($overrides, true); } $metaDataSettings = []; if (!$spOnly && $this->config['autoload_from_metadata']) { $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']); } $spSettings = $this->loadOneloginServiceProviderDetails(); $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides); return new Auth($settings, $spOnly); } /** * Load dynamic service provider options required by the onelogin toolkit. */ protected function loadOneloginServiceProviderDetails(): array { $spDetails = [ 'entityId' => url('/saml2/metadata'), 'assertionConsumerService' => [ 'url' => url('/saml2/acs'), ], 'singleLogoutService' => [ 'url' => url('/saml2/sls'), ], ]; return [ 'baseurl' => url('/saml2'), 'sp' => $spDetails, ]; } /** * Check if groups should be synced. */ protected function shouldSyncGroups(): bool { return $this->config['user_to_groups'] !== false; } /** * Calculate the display name. */ protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string { $displayNameAttr = $this->config['display_name_attributes']; $displayName = []; foreach ($displayNameAttr as $dnAttr) { $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null); if ($dnComponent !== null) { $displayName[] = $dnComponent; } } if (count($displayName) == 0) { $displayName = $defaultValue; } else { $displayName = implode(' ', $displayName); } return $displayName; } /** * Get the value to use as the external id saved in BookStack * used to link the user to an existing BookStack DB user. */ protected function getExternalId(array $samlAttributes, string $defaultValue) { $userNameAttr = $this->config['external_id_attribute']; if ($userNameAttr === null) { return $defaultValue; } return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue); } /** * Extract the details of a user from a SAML response. * * @return array{external_id: string, name: string, email: string, saml_id: string} */ protected function getUserDetails(string $samlID, $samlAttributes): array { $emailAttr = $this->config['email_attribute']; $externalId = $this->getExternalId($samlAttributes, $samlID); $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null; $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail); return [ 'external_id' => $externalId, 'name' => $this->getUserDisplayName($samlAttributes, $externalId), 'email' => $email, 'saml_id' => $samlID, ]; } /** * Get the groups a user is a part of from the SAML response. */ public function getUserGroups(array $samlAttributes): array { $groupsAttr = $this->config['group_attribute']; $userGroups = $samlAttributes[$groupsAttr] ?? null; if (!is_array($userGroups)) { $userGroups = []; } return $userGroups; } /** * For an array of strings, return a default for an empty array, * a string for an array with one element and the full array for * more than one element. */ protected function simplifyValue(array $data, $defaultValue) { switch (count($data)) { case 0: $data = $defaultValue; break; case 1: $data = $data[0]; break; } return $data; } /** * Get a property from an SAML response. * Handles properties potentially being an array. */ protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue) { if (isset($samlAttributes[$propertyKey])) { return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue); } return $defaultValue; } /** * Process the SAML response for a user. Login the user when * they exist, optionally registering them automatically. * * @throws SamlException * @throws JsonDebugException * @throws UserRegistrationException * @throws StoppedAuthenticationException */ public function processLoginCallback(string $samlID, array $samlAttributes): User { $userDetails = $this->getUserDetails($samlID, $samlAttributes); $isLoggedIn = auth()->check(); if ($this->shouldSyncGroups()) { $userDetails['groups'] = $this->getUserGroups($samlAttributes); } if ($this->config['dump_user_details']) { throw new JsonDebugException([ 'id_from_idp' => $samlID, 'attrs_from_idp' => $samlAttributes, 'attrs_after_parsing' => $userDetails, ]); } if ($userDetails['email'] === null) { throw new SamlException(trans('errors.saml_no_email_address')); } if ($isLoggedIn) { throw new SamlException(trans('errors.saml_already_logged_in'), '/login'); } $user = $this->registrationService->findOrRegister( $userDetails['name'], $userDetails['email'], $userDetails['external_id'] ); if ($this->shouldSyncGroups()) { $this->groupSyncService->syncUserWithFoundGroups($user, $userDetails['groups'], $this->config['remove_from_groups']); } $this->loginService->login($user, 'saml2'); return $user; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/UserInviteException.php
app/Access/UserInviteException.php
<?php namespace BookStack\Access; use Exception; class UserInviteException extends Exception { // }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Ldap.php
app/Access/Ldap.php
<?php namespace BookStack\Access; /** * Class Ldap * An object-orientated thin abstraction wrapper for common PHP LDAP functions. * Allows the standard LDAP functions to be mocked for testing. */ class Ldap { /** * Connect to an LDAP server. * * @return resource|\LDAP\Connection|false */ public function connect(string $hostName) { return ldap_connect($hostName); } /** * Set the value of an LDAP option for the given connection. * * @param resource|\LDAP\Connection|null $ldapConnection */ public function setOption($ldapConnection, int $option, mixed $value): bool { return ldap_set_option($ldapConnection, $option, $value); } /** * Start TLS on the given LDAP connection. */ public function startTls($ldapConnection): bool { return ldap_start_tls($ldapConnection); } /** * Set the version number for the given LDAP connection. * * @param resource|\LDAP\Connection $ldapConnection */ public function setVersion($ldapConnection, int $version): bool { return $this->setOption($ldapConnection, LDAP_OPT_PROTOCOL_VERSION, $version); } /** * Search LDAP tree using the provided filter. * * @param resource|\LDAP\Connection $ldapConnection * * @return \LDAP\Result|array|false */ public function search($ldapConnection, string $baseDn, string $filter, array $attributes = []) { return ldap_search($ldapConnection, $baseDn, $filter, $attributes); } /** * Read an entry from the LDAP tree. * * @param resource|\Ldap\Connection $ldapConnection * * @return \LDAP\Result|array|false */ public function read($ldapConnection, string $baseDn, string $filter, array $attributes = []) { return ldap_read($ldapConnection, $baseDn, $filter, $attributes); } /** * Get entries from an LDAP search result. * * @param resource|\LDAP\Connection $ldapConnection * @param resource|\LDAP\Result $ldapSearchResult */ public function getEntries($ldapConnection, $ldapSearchResult): array|false { return ldap_get_entries($ldapConnection, $ldapSearchResult); } /** * Search and get entries immediately. * * @param resource|\LDAP\Connection $ldapConnection */ public function searchAndGetEntries($ldapConnection, string $baseDn, string $filter, array $attributes = []): array|false { $search = $this->search($ldapConnection, $baseDn, $filter, $attributes); return $this->getEntries($ldapConnection, $search); } /** * Bind to LDAP directory. * * @param resource|\LDAP\Connection $ldapConnection */ public function bind($ldapConnection, ?string $bindRdn = null, ?string $bindPassword = null): bool { return ldap_bind($ldapConnection, $bindRdn, $bindPassword); } /** * Explode an LDAP dn string into an array of components. */ public function explodeDn(string $dn, int $withAttrib): array|false { return ldap_explode_dn($dn, $withAttrib); } /** * Escape a string for use in an LDAP filter. */ public function escape(string $value, string $ignore = '', int $flags = 0): string { return ldap_escape($value, $ignore, $flags); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/SocialAccount.php
app/Access/SocialAccount.php
<?php namespace BookStack\Access; use BookStack\Activity\Models\Loggable; use BookStack\App\Model; use BookStack\Users\Models\User; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * @property string $driver * @property User $user */ class SocialAccount extends Model implements Loggable { use HasFactory; protected $fillable = ['user_id', 'driver', 'driver_id']; /** * @return BelongsTo<User, $this> */ public function user(): BelongsTo { return $this->belongsTo(User::class); } /** * {@inheritdoc} */ public function logDescriptor(): string { return "{$this->driver}; {$this->user->logDescriptor()}"; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/SocialAuthService.php
app/Access/SocialAuthService.php
<?php namespace BookStack\Access; use BookStack\Exceptions\SocialDriverNotConfigured; use BookStack\Exceptions\SocialSignInAccountNotUsed; use BookStack\Exceptions\UserRegistrationException; use BookStack\Users\Models\User; use Illuminate\Support\Str; use Laravel\Socialite\Contracts\Factory as Socialite; use Laravel\Socialite\Contracts\Provider; use Laravel\Socialite\Contracts\User as SocialUser; use Laravel\Socialite\Two\GoogleProvider; use Symfony\Component\HttpFoundation\RedirectResponse; class SocialAuthService { public function __construct( protected Socialite $socialite, protected LoginService $loginService, protected SocialDriverManager $driverManager, ) { } /** * Start the social login path. * * @throws SocialDriverNotConfigured */ public function startLogIn(string $socialDriver): RedirectResponse { $socialDriver = trim(strtolower($socialDriver)); $this->driverManager->ensureDriverActive($socialDriver); return $this->getDriverForRedirect($socialDriver)->redirect(); } /** * Start the social registration process. * * @throws SocialDriverNotConfigured */ public function startRegister(string $socialDriver): RedirectResponse { $socialDriver = trim(strtolower($socialDriver)); $this->driverManager->ensureDriverActive($socialDriver); return $this->getDriverForRedirect($socialDriver)->redirect(); } /** * Handle the social registration process on callback. * * @throws UserRegistrationException */ public function handleRegistrationCallback(string $socialDriver, SocialUser $socialUser): SocialUser { // Check social account has not already been used if (SocialAccount::query()->where('driver_id', '=', $socialUser->getId())->exists()) { throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount' => $socialDriver]), '/login'); } if (User::query()->where('email', '=', $socialUser->getEmail())->exists()) { $email = $socialUser->getEmail(); throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $email]), '/login'); } return $socialUser; } /** * Get the social user details via the social driver. * * @throws SocialDriverNotConfigured */ public function getSocialUser(string $socialDriver): SocialUser { $socialDriver = trim(strtolower($socialDriver)); $this->driverManager->ensureDriverActive($socialDriver); return $this->socialite->driver($socialDriver)->user(); } /** * Handle the login process on a oAuth callback. * * @throws SocialSignInAccountNotUsed */ public function handleLoginCallback(string $socialDriver, SocialUser $socialUser) { $socialDriver = trim(strtolower($socialDriver)); $socialId = $socialUser->getId(); // Get any attached social accounts or users $socialAccount = SocialAccount::query()->where('driver_id', '=', $socialId)->first(); $isLoggedIn = auth()->check(); $currentUser = user(); $titleCaseDriver = Str::title($socialDriver); // When a user is not logged in and a matching SocialAccount exists, // Simply log the user into the application. if (!$isLoggedIn && $socialAccount !== null) { $this->loginService->login($socialAccount->user, $socialDriver); return redirect()->intended('/'); } // When a user is logged in but the social account does not exist, // Create the social account and attach it to the user & redirect to the profile page. if ($isLoggedIn && $socialAccount === null) { $account = $this->newSocialAccount($socialDriver, $socialUser); $currentUser->socialAccounts()->save($account); session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => $titleCaseDriver])); return redirect('/my-account/auth#social_accounts'); } // When a user is logged in and the social account exists and is already linked to the current user. if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) { session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => $titleCaseDriver])); return redirect('/my-account/auth#social_accounts'); } // When a user is logged in, A social account exists but the users do not match. if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) { session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => $titleCaseDriver])); return redirect('/my-account/auth#social_accounts'); } // Otherwise let the user know this social account is not used by anyone. $message = trans('errors.social_account_not_used', ['socialAccount' => $titleCaseDriver]); if (setting('registration-enabled') && config('auth.method') !== 'ldap' && config('auth.method') !== 'saml2') { $message .= trans('errors.social_account_register_instructions', ['socialAccount' => $titleCaseDriver]); } throw new SocialSignInAccountNotUsed($message, '/login'); } /** * Get the social driver manager used by this service. */ public function drivers(): SocialDriverManager { return $this->driverManager; } /** * Fill and return a SocialAccount from the given driver name and SocialUser. */ public function newSocialAccount(string $socialDriver, SocialUser $socialUser): SocialAccount { return new SocialAccount([ 'driver' => $socialDriver, 'driver_id' => $socialUser->getId(), 'avatar' => $socialUser->getAvatar(), ]); } /** * Detach a social account from a user. */ public function detachSocialAccount(string $socialDriver): void { user()->socialAccounts()->where('driver', '=', $socialDriver)->delete(); } /** * Provide redirect options per service for the Laravel Socialite driver. */ protected function getDriverForRedirect(string $driverName): Provider { $driver = $this->socialite->driver($driverName); if ($driver instanceof GoogleProvider && config('services.google.select_account')) { $driver->with(['prompt' => 'select_account']); } $this->driverManager->getConfigureForRedirectCallback($driverName)($driver); return $driver; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/ExternalBaseUserProvider.php
app/Access/ExternalBaseUserProvider.php
<?php namespace BookStack\Access; use BookStack\Users\Models\User; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; class ExternalBaseUserProvider implements UserProvider { /** * Retrieve a user by their unique identifier. */ public function retrieveById(mixed $identifier): ?Authenticatable { return User::query()->find($identifier); } /** * Retrieve a user by their unique identifier and "remember me" token. * * @param string $token */ public function retrieveByToken(mixed $identifier, $token): null { return null; } /** * Update the "remember me" token for the given user in storage. * * @param Authenticatable $user * @param string $token * * @return void */ public function updateRememberToken(Authenticatable $user, $token) { // } /** * Retrieve a user by the given credentials. */ public function retrieveByCredentials(array $credentials): ?Authenticatable { return User::query() ->where('external_auth_id', $credentials['external_auth_id']) ->first(); } /** * Validate a user against the given credentials. */ public function validateCredentials(Authenticatable $user, array $credentials): bool { // Should be done in the guard. return false; } public function rehashPasswordIfRequired(Authenticatable $user, #[\SensitiveParameter] array $credentials, bool $force = false) { // No action to perform, any passwords are external in the auth system } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/LoginService.php
app/Access/LoginService.php
<?php namespace BookStack\Access; use BookStack\Access\Mfa\MfaSession; use BookStack\Activity\ActivityType; use BookStack\Exceptions\LoginAttemptException; use BookStack\Exceptions\LoginAttemptInvalidUserException; use BookStack\Exceptions\StoppedAuthenticationException; use BookStack\Facades\Activity; use BookStack\Facades\Theme; use BookStack\Permissions\Permission; use BookStack\Theming\ThemeEvents; use BookStack\Users\Models\User; use Exception; class LoginService { protected const LAST_LOGIN_ATTEMPTED_SESSION_KEY = 'auth-login-last-attempted'; public function __construct( protected MfaSession $mfaSession, protected EmailConfirmationService $emailConfirmationService, protected SocialDriverManager $socialDriverManager, ) { } /** * Log the given user into the system. * Will start a login of the given user but will prevent if there's * a reason to (MFA or Unconfirmed Email). * Returns a boolean to indicate the current login result. * * @throws StoppedAuthenticationException|LoginAttemptInvalidUserException */ public function login(User $user, string $method, bool $remember = false): void { if ($user->isGuest()) { throw new LoginAttemptInvalidUserException('Login not allowed for guest user'); } if ($this->awaitingEmailConfirmation($user) || $this->needsMfaVerification($user)) { $this->setLastLoginAttemptedForUser($user, $method, $remember); throw new StoppedAuthenticationException($user, $this); } $this->clearLastLoginAttempted(); auth()->login($user, $remember); Activity::add(ActivityType::AUTH_LOGIN, "{$method}; {$user->logDescriptor()}"); Theme::dispatch(ThemeEvents::AUTH_LOGIN, $method, $user); // Authenticate on all session guards if a likely admin if ($user->can(Permission::UsersManage) && $user->can(Permission::UserRolesManage)) { $guards = ['standard', 'ldap', 'saml2', 'oidc']; foreach ($guards as $guard) { auth($guard)->login($user); } } } /** * Reattempt a system login after a previous stopped attempt. * * @throws Exception */ public function reattemptLoginFor(User $user): void { if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) { throw new Exception('Login reattempt user does align with current session state'); } $lastLoginDetails = $this->getLastLoginAttemptDetails(); $this->login($user, $lastLoginDetails['method'], $lastLoginDetails['remember'] ?? false); } /** * Get the last user that was attempted to be logged in. * Only exists if the last login attempt had correct credentials * but had been prevented by a secondary factor. */ public function getLastLoginAttemptUser(): ?User { $id = $this->getLastLoginAttemptDetails()['user_id']; return User::query()->where('id', '=', $id)->first(); } /** * Get the details of the last login attempt. * Checks upon a ttl of about 1 hour since that last attempted login. * * @return array{user_id: ?string, method: ?string, remember: bool} */ protected function getLastLoginAttemptDetails(): array { $value = session()->get(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY); if (!$value) { return ['user_id' => null, 'method' => null, 'remember' => false]; } [$id, $method, $remember, $time] = explode(':', $value); $hourAgo = time() - (60 * 60); if ($time < $hourAgo) { $this->clearLastLoginAttempted(); return ['user_id' => null, 'method' => null, 'remember' => false]; } return ['user_id' => $id, 'method' => $method, 'remember' => boolval($remember)]; } /** * Set the last login-attempted user. * Must be only used when credentials are correct and a login could be * achieved, but a secondary factor has stopped the login. */ protected function setLastLoginAttemptedForUser(User $user, string $method, bool $remember): void { session()->put( self::LAST_LOGIN_ATTEMPTED_SESSION_KEY, implode(':', [$user->id, $method, $remember, time()]) ); } /** * Clear the last login attempted session value. */ protected function clearLastLoginAttempted(): void { session()->remove(self::LAST_LOGIN_ATTEMPTED_SESSION_KEY); } /** * Check if MFA verification is needed. */ public function needsMfaVerification(User $user): bool { return !$this->mfaSession->isVerifiedForUser($user) && $this->mfaSession->isRequiredForUser($user); } /** * Check if the given user is awaiting email confirmation. */ public function awaitingEmailConfirmation(User $user): bool { return $this->emailConfirmationService->confirmationRequired() && !$user->email_confirmed; } /** * Attempt the login of a user using the given credentials. * Meant to mirror Laravel's default guard 'attempt' method * but in a manner that always routes through our login system. * May interrupt the flow if extra authentication requirements are imposed. * * @throws StoppedAuthenticationException * @throws LoginAttemptException */ public function attempt(array $credentials, string $method, bool $remember = false): bool { if ($this->areCredentialsForGuest($credentials)) { return false; } $result = auth()->attempt($credentials, $remember); if ($result) { $user = auth()->user(); auth()->logout(); try { $this->login($user, $method, $remember); } catch (LoginAttemptInvalidUserException $e) { // Catch and return false for non-login accounts // so it looks like a normal invalid login. return false; } } return $result; } /** * Check if the given credentials are likely for the system guest account. */ protected function areCredentialsForGuest(array $credentials): bool { if (isset($credentials['email'])) { return User::query()->where('email', '=', $credentials['email']) ->where('system_name', '=', 'public') ->exists(); } return false; } /** * Logs the current user out of the application. * Returns an app post-redirect path. */ public function logout(): string { auth()->logout(); session()->invalidate(); session()->regenerateToken(); return $this->shouldAutoInitiate() ? '/login?prevent_auto_init=true' : '/'; } /** * Check if login auto-initiate should be active based upon authentication config. */ public function shouldAutoInitiate(): bool { $autoRedirect = config('auth.auto_initiate'); if (!$autoRedirect) { return false; } $socialDrivers = $this->socialDriverManager->getActive(); $authMethod = config('auth.method'); return count($socialDrivers) === 0 && in_array($authMethod, ['oidc', 'saml2']); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/UserTokenService.php
app/Access/UserTokenService.php
<?php namespace BookStack\Access; use BookStack\Exceptions\UserTokenExpiredException; use BookStack\Exceptions\UserTokenNotFoundException; use BookStack\Users\Models\User; use Carbon\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use stdClass; class UserTokenService { /** * Name of table where user tokens are stored. */ protected string $tokenTable = 'user_tokens'; /** * Token expiry time in hours. */ protected int $expiryTime = 24; /** * Delete all tokens that belong to a user. */ public function deleteByUser(User $user): void { DB::table($this->tokenTable) ->where('user_id', '=', $user->id) ->delete(); } /** * Get the user id from a token, while checking the token exists and has not expired. * * @throws UserTokenNotFoundException * @throws UserTokenExpiredException */ public function checkTokenAndGetUserId(string $token): int { $entry = $this->getEntryByToken($token); if (is_null($entry)) { throw new UserTokenNotFoundException('Token "' . $token . '" not found'); } if ($this->entryExpired($entry)) { throw new UserTokenExpiredException("Token of id {$entry->id} has expired.", $entry->user_id); } return $entry->user_id; } /** * Creates a unique token within the email confirmation database. */ protected function generateToken(): string { $token = Str::random(24); while ($this->tokenExists($token)) { $token = Str::random(25); } return $token; } /** * Generate and store a token for the given user. */ protected function createTokenForUser(User $user): string { $token = $this->generateToken(); DB::table($this->tokenTable)->insert([ 'user_id' => $user->id, 'token' => $token, 'created_at' => Carbon::now(), 'updated_at' => Carbon::now(), ]); return $token; } /** * Check if the given token exists. */ protected function tokenExists(string $token): bool { return DB::table($this->tokenTable) ->where('token', '=', $token)->exists(); } /** * Get a token entry for the given token. */ protected function getEntryByToken(string $token): ?stdClass { return DB::table($this->tokenTable) ->where('token', '=', $token) ->first(); } /** * Check if the given token entry has expired. */ protected function entryExpired(stdClass $tokenEntry): bool { return Carbon::now()->subHours($this->expiryTime) ->gt(new Carbon($tokenEntry->created_at)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/SocialDriverManager.php
app/Access/SocialDriverManager.php
<?php namespace BookStack\Access; use BookStack\Exceptions\SocialDriverNotConfigured; use Illuminate\Support\Facades\Event; use Illuminate\Support\Str; use SocialiteProviders\Manager\SocialiteWasCalled; class SocialDriverManager { /** * The default built-in social drivers we support. * * @var string[] */ protected array $validDrivers = [ 'google', 'github', 'facebook', 'slack', 'twitter', 'azure', 'okta', 'gitlab', 'twitch', 'discord', ]; /** * Callbacks to run when configuring a social driver * for an initial redirect action. * Array is keyed by social driver name. * Callbacks are passed an instance of the driver. * * @var array<string, callable> */ protected array $configureForRedirectCallbacks = []; /** * Check if the current config for the given driver allows auto-registration. */ public function isAutoRegisterEnabled(string $driver): bool { return $this->getDriverConfigProperty($driver, 'auto_register') === true; } /** * Check if the current config for the given driver allow email address auto-confirmation. */ public function isAutoConfirmEmailEnabled(string $driver): bool { return $this->getDriverConfigProperty($driver, 'auto_confirm') === true; } /** * Gets the names of the active social drivers, keyed by driver id. * @return array<string, string> */ public function getActive(): array { $activeDrivers = []; foreach ($this->validDrivers as $driverKey) { if ($this->checkDriverConfigured($driverKey)) { $activeDrivers[$driverKey] = $this->getName($driverKey); } } return $activeDrivers; } /** * Get the configure-for-redirect callback for the given driver. * This is a callable that allows modification of the driver at redirect time. * Commonly used to perform custom dynamic configuration where required. * The callback is passed a \Laravel\Socialite\Contracts\Provider instance. */ public function getConfigureForRedirectCallback(string $driver): callable { return $this->configureForRedirectCallbacks[$driver] ?? (fn() => true); } /** * Add a custom socialite driver to be used. * Driver name should be lower_snake_case. * Config array should mirror the structure of a service * within the `Config/services.php` file. * Handler should be a Class@method handler to the SocialiteWasCalled event. */ public function addSocialDriver( string $driverName, array $config, string $socialiteHandler, ?callable $configureForRedirect = null ) { $this->validDrivers[] = $driverName; config()->set('services.' . $driverName, $config); config()->set('services.' . $driverName . '.redirect', url('/login/service/' . $driverName . '/callback')); config()->set('services.' . $driverName . '.name', $config['name'] ?? $driverName); Event::listen(SocialiteWasCalled::class, $socialiteHandler); if (!is_null($configureForRedirect)) { $this->configureForRedirectCallbacks[$driverName] = $configureForRedirect; } } /** * Get the presentational name for a driver. */ protected function getName(string $driver): string { return $this->getDriverConfigProperty($driver, 'name') ?? ''; } protected function getDriverConfigProperty(string $driver, string $property): mixed { return config("services.{$driver}.{$property}"); } /** * Ensure the social driver is correct and supported. * * @throws SocialDriverNotConfigured */ public function ensureDriverActive(string $driverName): void { if (!in_array($driverName, $this->validDrivers)) { abort(404, trans('errors.social_driver_not_found')); } if (!$this->checkDriverConfigured($driverName)) { throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => Str::title($driverName)])); } } /** * Check a social driver has been configured correctly. */ protected function checkDriverConfigured(string $driver): bool { $lowerName = strtolower($driver); $configPrefix = 'services.' . $lowerName . '.'; $config = [config($configPrefix . 'client_id'), config($configPrefix . 'client_secret'), config('services.callback_url')]; return !in_array(false, $config) && !in_array(null, $config); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/LdapService.php
app/Access/LdapService.php
<?php namespace BookStack\Access; use BookStack\Exceptions\JsonDebugException; use BookStack\Exceptions\LdapException; use BookStack\Uploads\UserAvatars; use BookStack\Users\Models\User; use ErrorException; use Illuminate\Support\Facades\Log; /** * Class LdapService * Handles any app-specific LDAP tasks. */ class LdapService { /** * @var resource|\LDAP\Connection */ protected $ldapConnection; protected array $config; protected bool $enabled; public function __construct( protected Ldap $ldap, protected UserAvatars $userAvatars, protected GroupSyncService $groupSyncService ) { $this->config = config('services.ldap'); $this->enabled = config('auth.method') === 'ldap'; } /** * Check if groups should be synced. */ public function shouldSyncGroups(): bool { return $this->enabled && $this->config['user_to_groups'] !== false; } /** * Search for attributes for a specific user on the ldap. * * @throws LdapException */ private function getUserWithAttributes(string $userName, array $attributes): ?array { $ldapConnection = $this->getConnection(); $this->bindSystemUser($ldapConnection); // Clean attributes foreach ($attributes as $index => $attribute) { if (str_starts_with($attribute, 'BIN;')) { $attributes[$index] = substr($attribute, strlen('BIN;')); } } // Find user $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]); $baseDn = $this->config['base_dn']; $followReferrals = $this->config['follow_referrals'] ? 1 : 0; $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals); $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes); if ($users['count'] === 0) { return null; } return $users[0]; } /** * Build the user display name from the (potentially multiple) attributes defined by the configuration. */ protected function getUserDisplayName(array $userDetails, array $displayNameAttrs, string $defaultValue): string { $displayNameParts = []; foreach ($displayNameAttrs as $dnAttr) { $dnComponent = $this->getUserResponseProperty($userDetails, $dnAttr, null); if ($dnComponent) { $displayNameParts[] = $dnComponent; } } if (empty($displayNameParts)) { return $defaultValue; } return implode(' ', $displayNameParts); } /** * Get the details of a user from LDAP using the given username. * User found via configurable user filter. * * @throws LdapException|JsonDebugException */ public function getUserDetails(string $userName): ?array { $idAttr = $this->config['id_attribute']; $emailAttr = $this->config['email_attribute']; $displayNameAttrs = explode('|', $this->config['display_name_attribute']); $thumbnailAttr = $this->config['thumbnail_attribute']; $user = $this->getUserWithAttributes($userName, array_filter([ 'cn', 'dn', $idAttr, $emailAttr, ...$displayNameAttrs, $thumbnailAttr, ])); if (is_null($user)) { return null; } $nameDefault = $this->getUserResponseProperty($user, 'cn', null); if (is_null($nameDefault)) { $nameDefault = ldap_explode_dn($user['dn'], 1)[0] ?? $user['dn']; } $formatted = [ 'uid' => $this->getUserResponseProperty($user, $idAttr, $user['dn']), 'name' => $this->getUserDisplayName($user, $displayNameAttrs, $nameDefault), 'dn' => $user['dn'], 'email' => $this->getUserResponseProperty($user, $emailAttr, null), 'avatar' => $thumbnailAttr ? $this->getUserResponseProperty($user, $thumbnailAttr, null) : null, ]; if ($this->config['dump_user_details']) { throw new JsonDebugException([ 'details_from_ldap' => $user, 'details_bookstack_parsed' => $formatted, ]); } return $formatted; } /** * Get a property from an LDAP user response fetch. * Handles properties potentially being part of an array. * If the given key is prefixed with 'BIN;', that indicator will be stripped * from the key and any fetched values will be converted from binary to hex. */ protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue) { $isBinary = str_starts_with($propertyKey, 'BIN;'); $propertyKey = strtolower($propertyKey); $value = $defaultValue; if ($isBinary) { $propertyKey = substr($propertyKey, strlen('BIN;')); } if (isset($userDetails[$propertyKey])) { $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]); if ($isBinary) { $value = bin2hex($value); } } return $value; } /** * Check if the given credentials are valid for the given user. * * @throws LdapException */ public function validateUserCredentials(?array $ldapUserDetails, string $password): bool { if (is_null($ldapUserDetails)) { return false; } $ldapConnection = $this->getConnection(); try { $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['dn'], $password); } catch (ErrorException $e) { $ldapBind = false; } return $ldapBind; } /** * Bind the system user to the LDAP connection using the given credentials * otherwise anonymous access is attempted. * * @param resource|\LDAP\Connection $connection * * @throws LdapException */ protected function bindSystemUser($connection): void { $ldapDn = $this->config['dn']; $ldapPass = $this->config['pass']; $isAnonymous = ($ldapDn === false || $ldapPass === false); if ($isAnonymous) { $ldapBind = $this->ldap->bind($connection); } else { $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass); } if (!$ldapBind) { throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed'))); } } /** * Get the connection to the LDAP server. * Creates a new connection if one does not exist. * * @throws LdapException * * @return resource|\LDAP\Connection */ protected function getConnection() { if ($this->ldapConnection !== null) { return $this->ldapConnection; } // Check LDAP extension in installed if (!function_exists('ldap_connect') && config('app.env') !== 'testing') { throw new LdapException(trans('errors.ldap_extension_not_installed')); } // Disable certificate verification. // This option works globally and must be set before a connection is created. if ($this->config['tls_insecure']) { $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER); } // Configure any user-provided CA cert files for LDAP. // This option works globally and must be set before a connection is created. if ($this->config['tls_ca_cert']) { $this->configureTlsCaCerts($this->config['tls_ca_cert']); } $ldapHost = $this->parseServerString($this->config['server']); $ldapConnection = $this->ldap->connect($ldapHost); if ($ldapConnection === false) { throw new LdapException(trans('errors.ldap_cannot_connect')); } // Set any required options if ($this->config['version']) { $this->ldap->setVersion($ldapConnection, $this->config['version']); } // Start and verify TLS if it's enabled if ($this->config['start_tls']) { try { $started = $this->ldap->startTls($ldapConnection); } catch (\Exception $exception) { $error = $exception->getMessage() . ' :: ' . ldap_error($ldapConnection); ldap_get_option($ldapConnection, LDAP_OPT_DIAGNOSTIC_MESSAGE, $detail); Log::info("LDAP STARTTLS failure: {$error} {$detail}"); throw new LdapException('Could not start TLS connection. Further details in the application log.'); } if (!$started) { throw new LdapException('Could not start TLS connection'); } } $this->ldapConnection = $ldapConnection; return $this->ldapConnection; } /** * Configure TLS CA certs globally for ldap use. * This will detect if the given path is a directory or file, and set the relevant * LDAP TLS options appropriately otherwise throw an exception if no file/folder found. * * Note: When using a folder, certificates are expected to be correctly named by hash * which can be done via the c_rehash utility. * * @throws LdapException */ protected function configureTlsCaCerts(string $caCertPath): void { $errMessage = "Provided path [{$caCertPath}] for LDAP TLS CA certs could not be resolved to an existing location"; $path = realpath($caCertPath); if ($path === false) { throw new LdapException($errMessage); } if (is_dir($path)) { $this->ldap->setOption(null, LDAP_OPT_X_TLS_CACERTDIR, $path); } else if (is_file($path)) { $this->ldap->setOption(null, LDAP_OPT_X_TLS_CACERTFILE, $path); } else { throw new LdapException($errMessage); } } /** * Parse an LDAP server string and return the host suitable for a connection. * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'. */ protected function parseServerString(string $serverString): string { if (str_starts_with($serverString, 'ldaps://') || str_starts_with($serverString, 'ldap://')) { return $serverString; } return "ldap://{$serverString}"; } /** * Build a filter string by injecting common variables. * Both "${var}" and "{var}" style placeholders are supported. * Dollar based are old format but supported for compatibility. */ protected function buildFilter(string $filterString, array $attrs): string { $newAttrs = []; foreach ($attrs as $key => $attrText) { $escapedText = $this->ldap->escape($attrText); $oldVarKey = '${' . $key . '}'; $newVarKey = '{' . $key . '}'; $newAttrs[$oldVarKey] = $escapedText; $newAttrs[$newVarKey] = $escapedText; } return strtr($filterString, $newAttrs); } /** * Get the groups a user is a part of on ldap. * * @throws LdapException * @throws JsonDebugException */ public function getUserGroups(string $userName): array { $groupsAttr = $this->config['group_attribute']; $user = $this->getUserWithAttributes($userName, [$groupsAttr]); if ($user === null) { return []; } $userGroups = $this->extractGroupsFromSearchResponseEntry($user); $allGroups = $this->getGroupsRecursive($userGroups, []); $formattedGroups = $this->extractGroupNamesFromLdapGroupDns($allGroups); if ($this->config['dump_user_groups']) { throw new JsonDebugException([ 'details_from_ldap' => $user, 'parsed_direct_user_groups' => $userGroups, 'parsed_recursive_user_groups' => $allGroups, 'parsed_resulting_group_names' => $formattedGroups, ]); } return $formattedGroups; } protected function extractGroupNamesFromLdapGroupDns(array $groupDNs): array { $names = []; foreach ($groupDNs as $groupDN) { $exploded = $this->ldap->explodeDn($groupDN, 1); if ($exploded !== false && count($exploded) > 0) { $names[] = $exploded[0]; } } return array_unique($names); } /** * Build an array of all relevant groups DNs after recursively scanning * across parents of the groups given. * * @throws LdapException */ protected function getGroupsRecursive(array $groupDNs, array $checked): array { $groupsToAdd = []; foreach ($groupDNs as $groupDN) { if (in_array($groupDN, $checked)) { continue; } $parentGroups = $this->getParentsOfGroup($groupDN); $groupsToAdd = array_merge($groupsToAdd, $parentGroups); $checked[] = $groupDN; } $uniqueDNs = array_unique(array_merge($groupDNs, $groupsToAdd), SORT_REGULAR); if (empty($groupsToAdd)) { return $uniqueDNs; } return $this->getGroupsRecursive($uniqueDNs, $checked); } /** * @throws LdapException */ protected function getParentsOfGroup(string $groupDN): array { $groupsAttr = strtolower($this->config['group_attribute']); $ldapConnection = $this->getConnection(); $this->bindSystemUser($ldapConnection); $followReferrals = $this->config['follow_referrals'] ? 1 : 0; $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals); $read = $this->ldap->read($ldapConnection, $groupDN, '(objectClass=*)', [$groupsAttr]); $results = $this->ldap->getEntries($ldapConnection, $read); if ($results['count'] === 0) { return []; } return $this->extractGroupsFromSearchResponseEntry($results[0]); } /** * Extract an array of group DN values from the given LDAP search response entry */ protected function extractGroupsFromSearchResponseEntry(array $ldapEntry): array { $groupsAttr = strtolower($this->config['group_attribute']); $groupDNs = []; $count = 0; if (isset($ldapEntry[$groupsAttr]['count'])) { $count = (int) $ldapEntry[$groupsAttr]['count']; } for ($i = 0; $i < $count; $i++) { $dn = $ldapEntry[$groupsAttr][$i]; if (!in_array($dn, $groupDNs)) { $groupDNs[] = $dn; } } return $groupDNs; } /** * Sync the LDAP groups to the user roles for the current user. * * @throws LdapException * @throws JsonDebugException */ public function syncGroups(User $user, string $username): void { $userLdapGroups = $this->getUserGroups($username); $this->groupSyncService->syncUserWithFoundGroups($user, $userLdapGroups, $this->config['remove_from_groups']); } /** * Save and attach an avatar image, if found in the ldap details, and attach * to the given user model. */ public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void { if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) { return; } try { $imageData = $ldapUserDetails['avatar']; $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg'); } catch (\Exception $exception) { Log::info("Failed to use avatar image from LDAP data for user id {$user->id}"); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/RegistrationService.php
app/Access/RegistrationService.php
<?php namespace BookStack\Access; use BookStack\Activity\ActivityType; use BookStack\Exceptions\UserRegistrationException; use BookStack\Facades\Activity; use BookStack\Facades\Theme; use BookStack\Theming\ThemeEvents; use BookStack\Users\Models\User; use BookStack\Users\UserRepo; use Exception; use Illuminate\Support\Str; class RegistrationService { public function __construct( protected UserRepo $userRepo, protected EmailConfirmationService $emailConfirmationService, ) { } /** * Check if registrations are allowed in the app settings. * * @throws UserRegistrationException */ public function ensureRegistrationAllowed() { if (!$this->registrationAllowed()) { throw new UserRegistrationException(trans('auth.registrations_disabled'), '/login'); } } /** * Check if standard BookStack User registrations are currently allowed. * Does not prevent external-auth based registration. */ protected function registrationAllowed(): bool { $authMethod = config('auth.method'); $authMethodsWithRegistration = ['standard']; return in_array($authMethod, $authMethodsWithRegistration) && setting('registration-enabled'); } /** * Attempt to find a user in the system otherwise register them as a new * user. For use with external auth systems since password is auto-generated. * * @throws UserRegistrationException */ public function findOrRegister(string $name, string $email, string $externalId): User { $user = User::query() ->where('external_auth_id', '=', $externalId) ->first(); if (is_null($user)) { $userData = [ 'name' => $name, 'email' => $email, 'password' => Str::random(32), 'external_auth_id' => $externalId, ]; $user = $this->registerUser($userData, null, false); } return $user; } /** * The registrations flow for all users. * * @throws UserRegistrationException */ public function registerUser(array $userData, ?SocialAccount $socialAccount = null, bool $emailConfirmed = false): User { $userEmail = $userData['email']; $authSystem = $socialAccount ? $socialAccount->driver : auth()->getDefaultDriver(); // Email restriction $this->ensureEmailDomainAllowed($userEmail); // Ensure user does not already exist $alreadyUser = !is_null($this->userRepo->getByEmail($userEmail)); if ($alreadyUser) { throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $userEmail]), '/login'); } /** @var ?bool $shouldRegister */ $shouldRegister = Theme::dispatch(ThemeEvents::AUTH_PRE_REGISTER, $authSystem, $userData); if ($shouldRegister === false) { throw new UserRegistrationException(trans('errors.auth_pre_register_theme_prevention'), '/login'); } // Create the user $newUser = $this->userRepo->createWithoutActivity($userData, $emailConfirmed); $newUser->attachDefaultRole(); // Assign social account if given if ($socialAccount) { $newUser->socialAccounts()->save($socialAccount); } Activity::add(ActivityType::AUTH_REGISTER, $socialAccount ?? $newUser); Theme::dispatch(ThemeEvents::AUTH_REGISTER, $authSystem, $newUser); // Start email confirmation flow if required if ($this->emailConfirmationService->confirmationRequired() && !$emailConfirmed) { $newUser->save(); try { $this->emailConfirmationService->sendConfirmation($newUser); session()->flash('sent-email-confirmation', true); } catch (Exception $e) { $message = trans('auth.email_confirm_send_error'); throw new UserRegistrationException($message, '/register/confirm'); } } return $newUser; } /** * Ensure that the given email meets any active email domain registration restrictions. * Throws if restrictions are active and the email does not match an allowed domain. * * @throws UserRegistrationException */ protected function ensureEmailDomainAllowed(string $userEmail): void { $registrationRestrict = setting('registration-restrict'); if (!$registrationRestrict) { return; } $restrictedEmailDomains = explode(',', str_replace(' ', '', $registrationRestrict)); $userEmailDomain = mb_substr(mb_strrchr($userEmail, '@'), 1); if (!in_array($userEmailDomain, $restrictedEmailDomains)) { $redirect = $this->registrationAllowed() ? '/register' : '/login'; throw new UserRegistrationException(trans('auth.registration_email_domain_invalid'), $redirect); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/UserInviteService.php
app/Access/UserInviteService.php
<?php namespace BookStack\Access; use BookStack\Access\Notifications\UserInviteNotification; use BookStack\Users\Models\User; class UserInviteService extends UserTokenService { protected string $tokenTable = 'user_invites'; protected int $expiryTime = 336; // Two weeks /** * Send an invitation to a user to sign into BookStack * Removes existing invitation tokens. * @throws UserInviteException */ public function sendInvitation(User $user) { $this->deleteByUser($user); $token = $this->createTokenForUser($user); try { $user->notify(new UserInviteNotification($token)); } catch (\Exception $exception) { throw new UserInviteException($exception->getMessage(), $exception->getCode(), $exception); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/GroupSyncService.php
app/Access/GroupSyncService.php
<?php namespace BookStack\Access; use BookStack\Users\Models\Role; use BookStack\Users\Models\User; use Illuminate\Support\Collection; class GroupSyncService { /** * Check a role against an array of group names to see if it matches. * Checked against role 'external_auth_id' if set otherwise the name of the role. */ protected function roleMatchesGroupNames(Role $role, array $groupNames): bool { if ($role->external_auth_id) { return $this->externalIdMatchesGroupNames($role->external_auth_id, $groupNames); } $roleName = str_replace(' ', '-', trim(strtolower($role->display_name))); return in_array($roleName, $groupNames); } /** * Check if the given external auth ID string matches one of the given group names. */ protected function externalIdMatchesGroupNames(string $externalId, array $groupNames): bool { foreach ($this->parseRoleExternalAuthId($externalId) as $externalAuthId) { if (in_array($externalAuthId, $groupNames)) { return true; } } return false; } protected function parseRoleExternalAuthId(string $externalId): array { $inputIds = preg_split('/(?<!\\\),/', strtolower($externalId)); $cleanIds = []; foreach ($inputIds as $inputId) { $cleanIds[] = str_replace('\,', ',', trim($inputId)); } return $cleanIds; } /** * Match an array of group names to BookStack system roles. * Formats group names to be lower-case and hyphenated. */ protected function matchGroupsToSystemsRoles(array $groupNames): Collection { foreach ($groupNames as $i => $groupName) { $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName))); } $roles = Role::query()->get(['id', 'external_auth_id', 'display_name']); $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) { return $this->roleMatchesGroupNames($role, $groupNames); }); return $matchedRoles->pluck('id'); } /** * Sync the groups to the user roles for the current user. */ public function syncUserWithFoundGroups(User $user, array $userGroups, bool $detachExisting): void { // Get the ids for the roles from the names $groupsAsRoles = $this->matchGroupsToSystemsRoles($userGroups); // Sync groups if ($detachExisting) { $user->roles()->sync($groupsAsRoles); $user->attachDefaultRole(); } else { $user->roles()->syncWithoutDetaching($groupsAsRoles); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/Saml2Controller.php
app/Access/Controllers/Saml2Controller.php
<?php namespace BookStack\Access\Controllers; use BookStack\Access\Saml2Service; use BookStack\Http\Controller; use Illuminate\Http\Request; use Illuminate\Support\Str; class Saml2Controller extends Controller { public function __construct( protected Saml2Service $samlService ) { $this->middleware('guard:saml2'); } /** * Start the login flow via SAML2. */ public function login() { $loginDetails = $this->samlService->login(); session()->flash('saml2_request_id', $loginDetails['id']); return redirect($loginDetails['url']); } /** * Start the logout flow via SAML2. */ public function logout() { $user = user(); if ($user->isGuest()) { return redirect('/login'); } $logoutDetails = $this->samlService->logout($user); if ($logoutDetails['id']) { session()->flash('saml2_logout_request_id', $logoutDetails['id']); } return redirect($logoutDetails['url']); } /* * Get the metadata for this SAML2 service provider. */ public function metadata() { $metaData = $this->samlService->metadata(); return response()->make($metaData, 200, [ 'Content-Type' => 'text/xml', ]); } /** * Single logout service. * Handle logout requests and responses. */ public function sls() { $requestId = session()->pull('saml2_logout_request_id', null); $redirect = $this->samlService->processSlsResponse($requestId); return redirect($redirect); } /** * Assertion Consumer Service start URL. Takes the SAMLResponse from the IDP. * Due to being an external POST request, we likely won't have context of the * current user session due to lax cookies. To work around this we store the * SAMLResponse data and redirect to the processAcs endpoint for the actual * processing of the request with proper context of the user session. */ public function startAcs(Request $request) { $samlResponse = $request->get('SAMLResponse', null); if (empty($samlResponse)) { $this->showErrorNotification(trans('errors.saml_fail_authed', ['system' => config('saml2.name')])); return redirect('/login'); } $acsId = Str::random(16); $cacheKey = 'saml2_acs:' . $acsId; cache()->set($cacheKey, encrypt($samlResponse), 10); return redirect()->guest('/saml2/acs?id=' . $acsId); } /** * Assertion Consumer Service process endpoint. * Processes the SAML response from the IDP with context of the current session. * Takes the SAML request from the cache, added by the startAcs method above. */ public function processAcs(Request $request) { $acsId = $request->get('id', null); $cacheKey = 'saml2_acs:' . $acsId; $samlResponse = null; try { $samlResponse = decrypt(cache()->pull($cacheKey)); } catch (\Exception $exception) { } $requestId = session()->pull('saml2_request_id', null); if (empty($acsId) || empty($samlResponse)) { $this->showErrorNotification(trans('errors.saml_fail_authed', ['system' => config('saml2.name')])); return redirect('/login'); } $user = $this->samlService->processAcsResponse($requestId, $samlResponse); if (is_null($user)) { $this->showErrorNotification(trans('errors.saml_fail_authed', ['system' => config('saml2.name')])); return redirect('/login'); } return redirect()->intended(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/HandlesPartialLogins.php
app/Access/Controllers/HandlesPartialLogins.php
<?php namespace BookStack\Access\Controllers; use BookStack\Access\LoginService; use BookStack\Exceptions\NotFoundException; use BookStack\Users\Models\User; trait HandlesPartialLogins { /** * @throws NotFoundException */ protected function currentOrLastAttemptedUser(): User { $loginService = app()->make(LoginService::class); $user = auth()->user() ?? $loginService->getLastLoginAttemptUser(); if (!$user) { throw new NotFoundException(trans('errors.login_user_not_found')); } return $user; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/MfaBackupCodesController.php
app/Access/Controllers/MfaBackupCodesController.php
<?php namespace BookStack\Access\Controllers; use BookStack\Access\LoginService; use BookStack\Access\Mfa\BackupCodeService; use BookStack\Access\Mfa\MfaSession; use BookStack\Access\Mfa\MfaValue; use BookStack\Activity\ActivityType; use BookStack\Exceptions\NotFoundException; use BookStack\Http\Controller; use Exception; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; class MfaBackupCodesController extends Controller { use HandlesPartialLogins; protected const SETUP_SECRET_SESSION_KEY = 'mfa-setup-backup-codes'; /** * Show a view that generates and displays backup codes. */ public function generate(BackupCodeService $codeService) { $codes = $codeService->generateNewSet(); session()->put(self::SETUP_SECRET_SESSION_KEY, encrypt($codes)); $downloadUrl = 'data:application/octet-stream;base64,' . base64_encode(implode("\n\n", $codes)); $this->setPageTitle(trans('auth.mfa_gen_backup_codes_title')); return view('mfa.backup-codes-generate', [ 'codes' => $codes, 'downloadUrl' => $downloadUrl, ]); } /** * Confirm the setup of backup codes, storing them against the user. * * @throws Exception */ public function confirm() { if (!session()->has(self::SETUP_SECRET_SESSION_KEY)) { return response('No generated codes found in the session', 500); } $codes = decrypt(session()->pull(self::SETUP_SECRET_SESSION_KEY)); MfaValue::upsertWithValue($this->currentOrLastAttemptedUser(), MfaValue::METHOD_BACKUP_CODES, json_encode($codes)); $this->logActivity(ActivityType::MFA_SETUP_METHOD, 'backup-codes'); if (!auth()->check()) { $this->showSuccessNotification(trans('auth.mfa_setup_login_notification')); return redirect('/login'); } return redirect('/mfa/setup'); } /** * Verify the MFA method submission on check. * * @throws NotFoundException * @throws ValidationException */ public function verify(Request $request, BackupCodeService $codeService, MfaSession $mfaSession, LoginService $loginService) { $user = $this->currentOrLastAttemptedUser(); $codes = MfaValue::getValueForUser($user, MfaValue::METHOD_BACKUP_CODES) ?? '[]'; $this->validate($request, [ 'code' => [ 'required', 'max:12', 'min:8', function ($attribute, $value, $fail) use ($codeService, $codes) { if (!$codeService->inputCodeExistsInSet($value, $codes)) { $fail(trans('validation.backup_codes')); } }, ], ]); $updatedCodes = $codeService->removeInputCodeFromSet($request->get('code'), $codes); MfaValue::upsertWithValue($user, MfaValue::METHOD_BACKUP_CODES, $updatedCodes); $mfaSession->markVerifiedForUser($user); $loginService->reattemptLoginFor($user); if ($codeService->countCodesInSet($updatedCodes) < 5) { $this->showWarningNotification(trans('auth.mfa_backup_codes_usage_limit_warning')); } return redirect()->intended(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/SocialController.php
app/Access/Controllers/SocialController.php
<?php namespace BookStack\Access\Controllers; use BookStack\Access\LoginService; use BookStack\Access\RegistrationService; use BookStack\Access\SocialAuthService; use BookStack\Exceptions\SocialDriverNotConfigured; use BookStack\Exceptions\SocialSignInAccountNotUsed; use BookStack\Exceptions\SocialSignInException; use BookStack\Exceptions\UserRegistrationException; use BookStack\Http\Controller; use Illuminate\Http\Request; use Illuminate\Support\Str; use Laravel\Socialite\Contracts\User as SocialUser; class SocialController extends Controller { public function __construct( protected SocialAuthService $socialAuthService, protected RegistrationService $registrationService, protected LoginService $loginService, ) { $this->middleware('guest')->only(['register']); } /** * Redirect to the relevant social site. * * @throws SocialDriverNotConfigured */ public function login(string $socialDriver) { session()->put('social-callback', 'login'); return $this->socialAuthService->startLogIn($socialDriver); } /** * Redirect to the social site for authentication intended to register. * * @throws SocialDriverNotConfigured * @throws UserRegistrationException */ public function register(string $socialDriver) { $this->registrationService->ensureRegistrationAllowed(); session()->put('social-callback', 'register'); return $this->socialAuthService->startRegister($socialDriver); } /** * The callback for social login services. * * @throws SocialSignInException * @throws SocialDriverNotConfigured * @throws UserRegistrationException */ public function callback(Request $request, string $socialDriver) { if (!session()->has('social-callback')) { throw new SocialSignInException(trans('errors.social_no_action_defined'), '/login'); } // Check request for error information if ($request->has('error') && $request->has('error_description')) { throw new SocialSignInException(trans('errors.social_login_bad_response', [ 'socialAccount' => $socialDriver, 'error' => $request->get('error_description'), ]), '/login'); } $action = session()->pull('social-callback'); // Attempt login or fall-back to register if allowed. $socialUser = $this->socialAuthService->getSocialUser($socialDriver); if ($action === 'login') { try { return $this->socialAuthService->handleLoginCallback($socialDriver, $socialUser); } catch (SocialSignInAccountNotUsed $exception) { if ($this->socialAuthService->drivers()->isAutoRegisterEnabled($socialDriver)) { return $this->socialRegisterCallback($socialDriver, $socialUser); } throw $exception; } } if ($action === 'register') { return $this->socialRegisterCallback($socialDriver, $socialUser); } return redirect('/'); } /** * Detach a social account from a user. */ public function detach(string $socialDriver) { $this->socialAuthService->detachSocialAccount($socialDriver); session()->flash('success', trans('settings.users_social_disconnected', ['socialAccount' => Str::title($socialDriver)])); return redirect('/my-account/auth#social-accounts'); } /** * Register a new user after a registration callback. * * @throws UserRegistrationException */ protected function socialRegisterCallback(string $socialDriver, SocialUser $socialUser) { $socialUser = $this->socialAuthService->handleRegistrationCallback($socialDriver, $socialUser); $socialAccount = $this->socialAuthService->newSocialAccount($socialDriver, $socialUser); $emailVerified = $this->socialAuthService->drivers()->isAutoConfirmEmailEnabled($socialDriver); // Create an array of the user data to create a new user instance $userData = [ 'name' => $socialUser->getName(), 'email' => $socialUser->getEmail(), 'password' => Str::random(32), ]; // Take name from email address if empty if (!$userData['name']) { $userData['name'] = explode('@', $userData['email'])[0]; } $user = $this->registrationService->registerUser($userData, $socialAccount, $emailVerified); $this->showSuccessNotification(trans('auth.register_success')); $this->loginService->login($user, $socialDriver); return redirect('/'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/ThrottlesLogins.php
app/Access/Controllers/ThrottlesLogins.php
<?php namespace BookStack\Access\Controllers; use Illuminate\Cache\RateLimiter; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; trait ThrottlesLogins { /** * Determine if the user has too many failed login attempts. */ protected function hasTooManyLoginAttempts(Request $request): bool { return $this->limiter()->tooManyAttempts( $this->throttleKey($request), $this->maxAttempts() ); } /** * Increment the login attempts for the user. */ protected function incrementLoginAttempts(Request $request): void { $this->limiter()->hit( $this->throttleKey($request), $this->decayMinutes() * 60 ); } /** * Redirect the user after determining they are locked out. * @throws ValidationException */ protected function sendLockoutResponse(Request $request): \Symfony\Component\HttpFoundation\Response { $seconds = $this->limiter()->availableIn( $this->throttleKey($request) ); throw ValidationException::withMessages([ $this->username() => [trans('auth.throttle', [ 'seconds' => $seconds, 'minutes' => ceil($seconds / 60), ])], ])->status(Response::HTTP_TOO_MANY_REQUESTS); } /** * Clear the login locks for the given user credentials. */ protected function clearLoginAttempts(Request $request): void { $this->limiter()->clear($this->throttleKey($request)); } /** * Get the throttle key for the given request. */ protected function throttleKey(Request $request): string { return Str::transliterate(Str::lower($request->input($this->username())) . '|' . $request->ip()); } /** * Get the rate limiter instance. */ protected function limiter(): RateLimiter { return app()->make(RateLimiter::class); } /** * Get the maximum number of attempts to allow. */ public function maxAttempts(): int { return 5; } /** * Get the number of minutes to throttle for. */ public function decayMinutes(): int { return 1; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/MfaTotpController.php
app/Access/Controllers/MfaTotpController.php
<?php namespace BookStack\Access\Controllers; use BookStack\Access\LoginService; use BookStack\Access\Mfa\MfaSession; use BookStack\Access\Mfa\MfaValue; use BookStack\Access\Mfa\TotpService; use BookStack\Access\Mfa\TotpValidationRule; use BookStack\Activity\ActivityType; use BookStack\Exceptions\NotFoundException; use BookStack\Http\Controller; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; class MfaTotpController extends Controller { use HandlesPartialLogins; protected const SETUP_SECRET_SESSION_KEY = 'mfa-setup-totp-secret'; public function __construct( protected TotpService $totp ) { } /** * Show a view that generates and displays a TOTP QR code. */ public function generate() { if (session()->has(static::SETUP_SECRET_SESSION_KEY)) { $totpSecret = decrypt(session()->get(static::SETUP_SECRET_SESSION_KEY)); } else { $totpSecret = $this->totp->generateSecret(); session()->put(static::SETUP_SECRET_SESSION_KEY, encrypt($totpSecret)); } $qrCodeUrl = $this->totp->generateUrl($totpSecret, $this->currentOrLastAttemptedUser()); $svg = $this->totp->generateQrCodeSvg($qrCodeUrl); $this->setPageTitle(trans('auth.mfa_gen_totp_title')); return view('mfa.totp-generate', [ 'url' => $qrCodeUrl, 'svg' => $svg, ]); } /** * Confirm the setup of TOTP and save the auth method secret * against the current user. * * @throws ValidationException * @throws NotFoundException */ public function confirm(Request $request) { $totpSecret = decrypt(session()->get(static::SETUP_SECRET_SESSION_KEY)); $this->validate($request, [ 'code' => [ 'required', 'max:12', 'min:4', new TotpValidationRule($totpSecret, $this->totp), ], ]); MfaValue::upsertWithValue($this->currentOrLastAttemptedUser(), MfaValue::METHOD_TOTP, $totpSecret); session()->remove(static::SETUP_SECRET_SESSION_KEY); $this->logActivity(ActivityType::MFA_SETUP_METHOD, 'totp'); if (!auth()->check()) { $this->showSuccessNotification(trans('auth.mfa_setup_login_notification')); return redirect('/login'); } return redirect('/mfa/setup'); } /** * Verify the MFA method submission on check. * * @throws NotFoundException */ public function verify(Request $request, LoginService $loginService, MfaSession $mfaSession) { $user = $this->currentOrLastAttemptedUser(); $totpSecret = MfaValue::getValueForUser($user, MfaValue::METHOD_TOTP); $this->validate($request, [ 'code' => [ 'required', 'max:12', 'min:4', new TotpValidationRule($totpSecret, $this->totp), ], ]); $mfaSession->markVerifiedForUser($user); $loginService->reattemptLoginFor($user); return redirect()->intended(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/LoginController.php
app/Access/Controllers/LoginController.php
<?php namespace BookStack\Access\Controllers; use BookStack\Access\LoginService; use BookStack\Access\SocialDriverManager; use BookStack\Exceptions\LoginAttemptEmailNeededException; use BookStack\Exceptions\LoginAttemptException; use BookStack\Facades\Activity; use BookStack\Http\Controller; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; class LoginController extends Controller { use ThrottlesLogins; public function __construct( protected SocialDriverManager $socialDriverManager, protected LoginService $loginService, ) { $this->middleware('guest', ['only' => ['getLogin', 'login']]); $this->middleware('guard:standard,ldap', ['only' => ['login']]); $this->middleware('guard:standard,ldap,oidc', ['only' => ['logout']]); } /** * Show the application login form. */ public function getLogin(Request $request) { $socialDrivers = $this->socialDriverManager->getActive(); $authMethod = config('auth.method'); $preventInitiation = $request->get('prevent_auto_init') === 'true'; if ($request->has('email')) { session()->flashInput([ 'email' => $request->get('email'), 'password' => (config('app.env') === 'demo') ? $request->get('password', '') : '', ]); } // Store the previous location for redirect after login $this->updateIntendedFromPrevious(); if (!$preventInitiation && $this->loginService->shouldAutoInitiate()) { return view('auth.login-initiate', [ 'authMethod' => $authMethod, ]); } return view('auth.login', [ 'socialDrivers' => $socialDrivers, 'authMethod' => $authMethod, ]); } /** * Handle a login request to the application. */ public function login(Request $request) { $this->validateLogin($request); $username = $request->get($this->username()); // Check login throttling attempts to see if they've gone over the limit if ($this->hasTooManyLoginAttempts($request)) { Activity::logFailedLogin($username); return $this->sendLockoutResponse($request); } try { if ($this->attemptLogin($request)) { return $this->sendLoginResponse($request); } } catch (LoginAttemptException $exception) { Activity::logFailedLogin($username); return $this->sendLoginAttemptExceptionResponse($exception, $request); } // On unsuccessful login attempt, Increment login attempts for throttling and log failed login. $this->incrementLoginAttempts($request); Activity::logFailedLogin($username); // Throw validation failure for failed login throw ValidationException::withMessages([ $this->username() => [trans('auth.failed')], ])->redirectTo('/login'); } /** * Logout user and perform subsequent redirect. */ public function logout() { return redirect($this->loginService->logout()); } /** * Get the expected username input based upon the current auth method. */ protected function username(): string { return config('auth.method') === 'standard' ? 'email' : 'username'; } /** * Get the needed authorization credentials from the request. */ protected function credentials(Request $request): array { return $request->only('username', 'email', 'password'); } /** * Send the response after the user was authenticated. * @return RedirectResponse */ protected function sendLoginResponse(Request $request) { $request->session()->regenerate(); $this->clearLoginAttempts($request); return redirect()->intended('/'); } /** * Attempt to log the user into the application. */ protected function attemptLogin(Request $request): bool { return $this->loginService->attempt( $this->credentials($request), auth()->getDefaultDriver(), $request->filled('remember') ); } /** * Validate the user login request. * @throws ValidationException */ protected function validateLogin(Request $request): void { $rules = ['password' => ['required', 'string']]; $authMethod = config('auth.method'); if ($authMethod === 'standard') { $rules['email'] = ['required', 'email']; } if ($authMethod === 'ldap') { $rules['username'] = ['required', 'string']; $rules['email'] = ['email']; } $request->validate($rules); } /** * Send a response when a login attempt exception occurs. */ protected function sendLoginAttemptExceptionResponse(LoginAttemptException $exception, Request $request) { if ($exception instanceof LoginAttemptEmailNeededException) { $request->flash(); session()->flash('request-email', true); } if ($message = $exception->getMessage()) { $this->showWarningNotification($message); } return redirect('/login'); } /** * Update the intended URL location from their previous URL. * Ignores if not from the current app instance or if from certain * login or authentication routes. */ protected function updateIntendedFromPrevious(): void { // Store the previous location for redirect after login $previous = url()->previous(''); $isPreviousFromInstance = str_starts_with($previous, url('/')); if (!$previous || !setting('app-public') || !$isPreviousFromInstance) { return; } $ignorePrefixList = [ '/login', '/mfa', ]; foreach ($ignorePrefixList as $ignorePrefix) { if (str_starts_with($previous, url($ignorePrefix))) { return; } } redirect()->setIntendedUrl($previous); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/ForgotPasswordController.php
app/Access/Controllers/ForgotPasswordController.php
<?php namespace BookStack\Access\Controllers; use BookStack\Activity\ActivityType; use BookStack\Http\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Password; use Illuminate\Support\Sleep; class ForgotPasswordController extends Controller { public function __construct() { $this->middleware('guest'); $this->middleware('guard:standard'); } /** * Display the form to request a password reset link. */ public function showLinkRequestForm() { return view('auth.passwords.email'); } /** * Send a reset link to the given user. */ public function sendResetLinkEmail(Request $request) { $this->validate($request, [ 'email' => ['required', 'email'], ]); // Add random pause to the response to help avoid time-base sniffing // of valid resets via slower email send handling. Sleep::for(random_int(1000, 3000))->milliseconds(); // We will send the password reset link to this user. Once we have attempted // to send the link, we will examine the response then see the message we // need to show to the user. Finally, we'll send out a proper response. $response = Password::broker()->sendResetLink( $request->only('email') ); if ($response === Password::RESET_LINK_SENT) { $this->logActivity(ActivityType::AUTH_PASSWORD_RESET, $request->get('email')); } if (in_array($response, [Password::RESET_LINK_SENT, Password::INVALID_USER, Password::RESET_THROTTLED])) { $message = trans('auth.reset_password_sent', ['email' => $request->get('email')]); $this->showSuccessNotification($message); return redirect('/password/email')->with('status', trans($response)); } // If an error was returned by the password broker, we will get this message // translated so we can notify a user of the problem. We'll redirect back // to where the users came from so they can attempt this process again. return redirect('/password/email')->withErrors( ['email' => trans($response)] ); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/UserInviteController.php
app/Access/Controllers/UserInviteController.php
<?php namespace BookStack\Access\Controllers; use BookStack\Access\UserInviteService; use BookStack\Exceptions\UserTokenExpiredException; use BookStack\Exceptions\UserTokenNotFoundException; use BookStack\Http\Controller; use BookStack\Users\UserRepo; use Exception; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Routing\Redirector; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\Rules\Password; class UserInviteController extends Controller { protected UserInviteService $inviteService; protected UserRepo $userRepo; /** * Create a new controller instance. */ public function __construct(UserInviteService $inviteService, UserRepo $userRepo) { $this->middleware('guest'); $this->middleware('guard:standard'); $this->inviteService = $inviteService; $this->userRepo = $userRepo; } /** * Show the page for the user to set the password for their account. * * @throws Exception */ public function showSetPassword(string $token) { try { $this->inviteService->checkTokenAndGetUserId($token); } catch (Exception $exception) { return $this->handleTokenException($exception); } return view('auth.invite-set-password', [ 'token' => $token, ]); } /** * Sets the password for an invited user and then grants them access. * * @throws Exception */ public function setPassword(Request $request, string $token) { $this->validate($request, [ 'password' => ['required', Password::default()], ]); try { $userId = $this->inviteService->checkTokenAndGetUserId($token); } catch (Exception $exception) { return $this->handleTokenException($exception); } $user = $this->userRepo->getById($userId); $user->password = Hash::make($request->get('password')); $user->email_confirmed = true; $user->save(); $this->inviteService->deleteByUser($user); $this->showSuccessNotification(trans('auth.user_invite_success_login', ['appName' => setting('app-name')])); return redirect('/login'); } /** * Check and validate the exception thrown when checking an invite token. * * @throws Exception * * @return RedirectResponse|Redirector */ protected function handleTokenException(Exception $exception) { if ($exception instanceof UserTokenNotFoundException) { return redirect('/'); } if ($exception instanceof UserTokenExpiredException) { $this->showErrorNotification(trans('errors.invite_token_expired')); return redirect('/password/email'); } throw $exception; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/ResetPasswordController.php
app/Access/Controllers/ResetPasswordController.php
<?php namespace BookStack\Access\Controllers; use BookStack\Access\LoginService; use BookStack\Activity\ActivityType; use BookStack\Http\Controller; use BookStack\Users\Models\User; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Password; use Illuminate\Support\Str; use Illuminate\Validation\Rules\Password as PasswordRule; class ResetPasswordController extends Controller { public function __construct( protected LoginService $loginService ) { $this->middleware('guest'); $this->middleware('guard:standard'); } /** * Display the password reset view for the given token. * If no token is present, display the link request form. */ public function showResetForm(Request $request) { $token = $request->route()->parameter('token'); return view('auth.passwords.reset')->with( ['token' => $token, 'email' => $request->email] ); } /** * Reset the given user's password. */ public function reset(Request $request) { $request->validate([ 'token' => 'required', 'email' => 'required|email', 'password' => ['required', 'confirmed', PasswordRule::defaults()], ]); // Here we will attempt to reset the user's password. If it is successful we // will update the password on an actual user model and persist it to the // database. Otherwise we will parse the error and return the response. $credentials = $request->only('email', 'password', 'password_confirmation', 'token'); $response = Password::broker()->reset($credentials, function (User $user, string $password) { $user->password = Hash::make($password); $user->setRememberToken(Str::random(60)); $user->save(); $this->loginService->login($user, auth()->getDefaultDriver()); }); // If the password was successfully reset, we will redirect the user back to // the application's home authenticated view. If there is an error we can // redirect them back to where they came from with their error message. return $response === Password::PASSWORD_RESET ? $this->sendResetResponse() : $this->sendResetFailedResponse($request, $response, $request->get('token')); } /** * Get the response for a successful password reset. */ protected function sendResetResponse(): RedirectResponse { $this->showSuccessNotification(trans('auth.reset_password_success')); $this->logActivity(ActivityType::AUTH_PASSWORD_RESET_UPDATE, user()); return redirect('/'); } /** * Get the response for a failed password reset. */ protected function sendResetFailedResponse(Request $request, string $response, string $token): RedirectResponse { // We show invalid users as invalid tokens as to not leak what // users may exist in the system. if ($response === Password::INVALID_USER) { $response = Password::INVALID_TOKEN; } return redirect("/password/reset/{$token}") ->withInput($request->only('email')) ->withErrors(['email' => trans($response)]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/OidcController.php
app/Access/Controllers/OidcController.php
<?php namespace BookStack\Access\Controllers; use BookStack\Access\Oidc\OidcException; use BookStack\Access\Oidc\OidcService; use BookStack\Http\Controller; use Illuminate\Http\Request; class OidcController extends Controller { public function __construct( protected OidcService $oidcService ) { $this->middleware('guard:oidc'); } /** * Start the authorization login flow via OIDC. */ public function login() { try { $loginDetails = $this->oidcService->login(); } catch (OidcException $exception) { $this->showErrorNotification($exception->getMessage()); return redirect('/login'); } session()->put('oidc_state', time() . ':' . $loginDetails['state']); return redirect($loginDetails['url']); } /** * Authorization flow redirect callback. * Processes authorization response from the OIDC Authorization Server. */ public function callback(Request $request) { $responseState = $request->query('state'); $splitState = explode(':', session()->pull('oidc_state', ':'), 2); if (count($splitState) !== 2) { $splitState = [null, null]; } [$storedStateTime, $storedState] = $splitState; $threeMinutesAgo = time() - 3 * 60; if (!$storedState || $storedState !== $responseState || intval($storedStateTime) < $threeMinutesAgo) { $this->showErrorNotification(trans('errors.oidc_fail_authed', ['system' => config('oidc.name')])); return redirect('/login'); } try { $this->oidcService->processAuthorizeResponse($request->query('code')); } catch (OidcException $oidcException) { $this->showErrorNotification($oidcException->getMessage()); return redirect('/login'); } return redirect()->intended(); } /** * Log the user out, then start the OIDC RP-initiated logout process. */ public function logout() { return redirect($this->oidcService->logout()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/MfaController.php
app/Access/Controllers/MfaController.php
<?php namespace BookStack\Access\Controllers; use BookStack\Access\Mfa\MfaValue; use BookStack\Activity\ActivityType; use BookStack\Http\Controller; use Illuminate\Http\Request; class MfaController extends Controller { use HandlesPartialLogins; /** * Show the view to setup MFA for the current user. */ public function setup() { $userMethods = $this->currentOrLastAttemptedUser() ->mfaValues() ->get(['id', 'method']) ->groupBy('method'); $this->setPageTitle(trans('auth.mfa_setup')); return view('mfa.setup', [ 'userMethods' => $userMethods, ]); } /** * Remove an MFA method for the current user. * * @throws \Exception */ public function remove(string $method) { if (in_array($method, MfaValue::allMethods())) { $value = user()->mfaValues()->where('method', '=', $method)->first(); if ($value) { $value->delete(); $this->logActivity(ActivityType::MFA_REMOVE_METHOD, $method); } } return redirect('/mfa/setup'); } /** * Show the page to start an MFA verification. */ public function verify(Request $request) { $desiredMethod = $request->get('method'); $userMethods = $this->currentOrLastAttemptedUser() ->mfaValues() ->get(['id', 'method']) ->groupBy('method'); // Basic search for the default option for a user. // (Prioritises totp over backup codes) $method = $userMethods->has($desiredMethod) ? $desiredMethod : $userMethods->keys()->sort()->reverse()->first(); $otherMethods = $userMethods->keys()->filter(function ($userMethod) use ($method) { return $method !== $userMethod; })->all(); return view('mfa.verify', [ 'userMethods' => $userMethods, 'method' => $method, 'otherMethods' => $otherMethods, ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/RegisterController.php
app/Access/Controllers/RegisterController.php
<?php namespace BookStack\Access\Controllers; use BookStack\Access\LoginService; use BookStack\Access\RegistrationService; use BookStack\Access\SocialDriverManager; use BookStack\Exceptions\StoppedAuthenticationException; use BookStack\Exceptions\UserRegistrationException; use BookStack\Http\Controller; use Illuminate\Contracts\Validation\Validator as ValidatorContract; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rules\Password; class RegisterController extends Controller { public function __construct( protected SocialDriverManager $socialDriverManager, protected RegistrationService $registrationService, protected LoginService $loginService ) { $this->middleware('guest'); $this->middleware('guard:standard'); } /** * Show the application registration form. * * @throws UserRegistrationException */ public function getRegister() { $this->registrationService->ensureRegistrationAllowed(); $socialDrivers = $this->socialDriverManager->getActive(); return view('auth.register', [ 'socialDrivers' => $socialDrivers, ]); } /** * Handle a registration request for the application. * * @throws UserRegistrationException * @throws StoppedAuthenticationException */ public function postRegister(Request $request) { $this->registrationService->ensureRegistrationAllowed(); $this->validator($request->all())->validate(); $userData = $request->all(); try { $user = $this->registrationService->registerUser($userData); $this->loginService->login($user, auth()->getDefaultDriver()); } catch (UserRegistrationException $exception) { if ($exception->getMessage()) { $this->showErrorNotification($exception->getMessage()); } return redirect($exception->redirectLocation); } $this->showSuccessNotification(trans('auth.register_success')); return redirect('/'); } /** * Get a validator for an incoming registration request. */ protected function validator(array $data): ValidatorContract { return Validator::make($data, [ 'name' => ['required', 'min:2', 'max:100'], 'email' => ['required', 'email', 'max:255', 'unique:users'], 'password' => ['required', Password::default()], // Basic honey for bots that must not be filled in 'username' => ['prohibited'], ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Controllers/ConfirmEmailController.php
app/Access/Controllers/ConfirmEmailController.php
<?php namespace BookStack\Access\Controllers; use BookStack\Access\EmailConfirmationService; use BookStack\Access\LoginService; use BookStack\Exceptions\ConfirmationEmailException; use BookStack\Exceptions\UserTokenExpiredException; use BookStack\Exceptions\UserTokenNotFoundException; use BookStack\Http\Controller; use BookStack\Users\UserRepo; use Exception; use Illuminate\Http\Request; class ConfirmEmailController extends Controller { public function __construct( protected EmailConfirmationService $emailConfirmationService, protected LoginService $loginService, protected UserRepo $userRepo ) { } /** * Show the page to tell the user to check their email * and confirm their address. */ public function show() { return view('auth.register-confirm'); } /** * Shows a notice that a user's email address has not been confirmed, * along with the option to re-send the confirmation email. */ public function showAwaiting() { $user = $this->loginService->getLastLoginAttemptUser(); if ($user === null) { $this->showErrorNotification(trans('errors.login_user_not_found')); return redirect('/login'); } return view('auth.register-confirm-awaiting'); } /** * Show the form for a user to provide their positive confirmation of their email. */ public function showAcceptForm(string $token) { return view('auth.register-confirm-accept', ['token' => $token]); } /** * Confirms an email via a token and logs the user into the system. * * @throws ConfirmationEmailException * @throws Exception */ public function confirm(Request $request) { $validated = $this->validate($request, [ 'token' => ['required', 'string'] ]); $token = $validated['token']; try { $userId = $this->emailConfirmationService->checkTokenAndGetUserId($token); } catch (UserTokenNotFoundException $exception) { $this->showErrorNotification(trans('errors.email_confirmation_invalid')); return redirect('/register'); } catch (UserTokenExpiredException $exception) { $user = $this->userRepo->getById($exception->userId); $this->emailConfirmationService->sendConfirmation($user); $this->showErrorNotification(trans('errors.email_confirmation_expired')); return redirect('/register/confirm'); } $user = $this->userRepo->getById($userId); $user->email_confirmed = true; $user->save(); $this->emailConfirmationService->deleteByUser($user); $this->showSuccessNotification(trans('auth.email_confirm_success')); return redirect('/login'); } /** * Resend the confirmation email. */ public function resend() { $user = $this->loginService->getLastLoginAttemptUser(); if ($user === null) { $this->showErrorNotification(trans('errors.login_user_not_found')); return redirect('/login'); } try { $this->emailConfirmationService->sendConfirmation($user); } catch (ConfirmationEmailException $e) { $this->showErrorNotification($e->getMessage()); return redirect('/login'); } catch (Exception $e) { $this->showErrorNotification(trans('auth.email_confirm_send_error')); return redirect('/register/awaiting'); } $this->showSuccessNotification(trans('auth.email_confirm_resent')); return redirect('/register/confirm'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcJwtSigningKey.php
app/Access/Oidc/OidcJwtSigningKey.php
<?php namespace BookStack\Access\Oidc; use phpseclib3\Crypt\Common\PublicKey; use phpseclib3\Crypt\PublicKeyLoader; use phpseclib3\Crypt\RSA; use phpseclib3\Math\BigInteger; class OidcJwtSigningKey { /** * @var PublicKey */ protected $key; /** * Can be created either from a JWK parameter array or local file path to load a certificate from. * Examples: * 'file:///var/www/cert.pem' * ['kty' => 'RSA', 'alg' => 'RS256', 'n' => 'abc123...']. * * @param array|string $jwkOrKeyPath * * @throws OidcInvalidKeyException */ public function __construct($jwkOrKeyPath) { if (is_array($jwkOrKeyPath)) { $this->loadFromJwkArray($jwkOrKeyPath); } elseif (is_string($jwkOrKeyPath) && strpos($jwkOrKeyPath, 'file://') === 0) { $this->loadFromPath($jwkOrKeyPath); } else { throw new OidcInvalidKeyException('Unexpected type of key value provided'); } } /** * @throws OidcInvalidKeyException */ protected function loadFromPath(string $path) { try { $key = PublicKeyLoader::load( file_get_contents($path) ); } catch (\Exception $exception) { throw new OidcInvalidKeyException("Failed to load key from file path with error: {$exception->getMessage()}"); } if (!$key instanceof RSA) { throw new OidcInvalidKeyException('Key loaded from file path is not an RSA key as expected'); } $this->key = $key->withPadding(RSA::SIGNATURE_PKCS1); } /** * @throws OidcInvalidKeyException */ protected function loadFromJwkArray(array $jwk) { // 'alg' is optional for a JWK, but we will still attempt to validate if // it exists otherwise presume it will be compatible. $alg = $jwk['alg'] ?? null; if ($jwk['kty'] !== 'RSA' || !(is_null($alg) || $alg === 'RS256')) { throw new OidcInvalidKeyException("Only RS256 keys are currently supported. Found key using {$alg}"); } // 'use' is optional for a JWK but we assume 'sig' where no value exists since that's what // the OIDC discovery spec infers since 'sig' MUST be set if encryption keys come into play. $use = $jwk['use'] ?? 'sig'; if ($use !== 'sig') { throw new OidcInvalidKeyException("Only signature keys are currently supported. Found key for use {$jwk['use']}"); } if (empty($jwk['e'])) { throw new OidcInvalidKeyException('An "e" parameter on the provided key is expected'); } if (empty($jwk['n'])) { throw new OidcInvalidKeyException('A "n" parameter on the provided key is expected'); } $n = strtr($jwk['n'] ?? '', '-_', '+/'); try { $key = PublicKeyLoader::load([ 'e' => new BigInteger(base64_decode($jwk['e']), 256), 'n' => new BigInteger(base64_decode($n), 256), ]); } catch (\Exception $exception) { throw new OidcInvalidKeyException("Failed to load key from JWK parameters with error: {$exception->getMessage()}"); } if (!$key instanceof RSA) { throw new OidcInvalidKeyException('Key loaded from file path is not an RSA key as expected'); } $this->key = $key->withPadding(RSA::SIGNATURE_PKCS1); } /** * Use this key to sign the given content and return the signature. */ public function verify(string $content, string $signature): bool { return $this->key->verify($content, $signature); } /** * Convert the key to a PEM encoded key string. */ public function toPem(): string { return $this->key->toString('PKCS8'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcInvalidTokenException.php
app/Access/Oidc/OidcInvalidTokenException.php
<?php namespace BookStack\Access\Oidc; use Exception; class OidcInvalidTokenException extends Exception { }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcService.php
app/Access/Oidc/OidcService.php
<?php namespace BookStack\Access\Oidc; use BookStack\Access\GroupSyncService; use BookStack\Access\LoginService; use BookStack\Access\RegistrationService; use BookStack\Exceptions\JsonDebugException; use BookStack\Exceptions\StoppedAuthenticationException; use BookStack\Exceptions\UserRegistrationException; use BookStack\Facades\Theme; use BookStack\Http\HttpRequestService; use BookStack\Theming\ThemeEvents; use BookStack\Uploads\UserAvatars; use BookStack\Users\Models\User; use Illuminate\Support\Facades\Cache; use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider; use League\OAuth2\Client\Provider\Exception\IdentityProviderException; /** * Class OpenIdConnectService * Handles any app-specific OIDC tasks. */ class OidcService { public function __construct( protected RegistrationService $registrationService, protected LoginService $loginService, protected HttpRequestService $http, protected GroupSyncService $groupService, protected UserAvatars $userAvatars ) { } /** * Initiate an authorization flow. * Provides back an authorize redirect URL, in addition to other * details which may be required for the auth flow. * * @throws OidcException * * @return array{url: string, state: string} */ public function login(): array { $settings = $this->getProviderSettings(); $provider = $this->getProvider($settings); $url = $provider->getAuthorizationUrl(); session()->put('oidc_pkce_code', $provider->getPkceCode() ?? ''); return [ 'url' => $url, 'state' => $provider->getState(), ]; } /** * Process the Authorization response from the authorization server and * return the matching, or new if registration active, user matched to the * authorization server. Throws if the user cannot be auth if not authenticated. * * @throws JsonDebugException * @throws OidcException * @throws StoppedAuthenticationException * @throws IdentityProviderException */ public function processAuthorizeResponse(?string $authorizationCode): User { $settings = $this->getProviderSettings(); $provider = $this->getProvider($settings); // Set PKCE code flashed at login $pkceCode = session()->pull('oidc_pkce_code', ''); $provider->setPkceCode($pkceCode); // Try to exchange authorization code for access token $accessToken = $provider->getAccessToken('authorization_code', [ 'code' => $authorizationCode, ]); return $this->processAccessTokenCallback($accessToken, $settings); } /** * @throws OidcException */ protected function getProviderSettings(): OidcProviderSettings { $config = $this->config(); $settings = new OidcProviderSettings([ 'issuer' => $config['issuer'], 'clientId' => $config['client_id'], 'clientSecret' => $config['client_secret'], 'authorizationEndpoint' => $config['authorization_endpoint'], 'tokenEndpoint' => $config['token_endpoint'], 'endSessionEndpoint' => is_string($config['end_session_endpoint']) ? $config['end_session_endpoint'] : null, 'userinfoEndpoint' => $config['userinfo_endpoint'], ]); // Use keys if configured if (!empty($config['jwt_public_key'])) { $settings->keys = [$config['jwt_public_key']]; } // Run discovery if ($config['discover'] ?? false) { try { $settings->discoverFromIssuer($this->http->buildClient(5), Cache::store(null), 15); } catch (OidcIssuerDiscoveryException $exception) { throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage()); } } // Prevent use of RP-initiated logout if specifically disabled // Or force use of a URL if specifically set. if ($config['end_session_endpoint'] === false) { $settings->endSessionEndpoint = null; } else if (is_string($config['end_session_endpoint'])) { $settings->endSessionEndpoint = $config['end_session_endpoint']; } $settings->validate(); return $settings; } /** * Load the underlying OpenID Connect Provider. */ protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider { $provider = new OidcOAuthProvider([ ...$settings->arrayForOAuthProvider(), 'redirectUri' => url('/oidc/callback'), ], [ 'httpClient' => $this->http->buildClient(5), 'optionProvider' => new HttpBasicAuthOptionProvider(), ]); foreach ($this->getAdditionalScopes() as $scope) { $provider->addScope($scope); } return $provider; } /** * Get any user-defined addition/custom scopes to apply to the authentication request. * * @return string[] */ protected function getAdditionalScopes(): array { $scopeConfig = $this->config()['additional_scopes'] ?: ''; $scopeArr = explode(',', $scopeConfig); $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr); return array_filter($scopeArr); } /** * Processes a received access token for a user. Login the user when * they exist, optionally registering them automatically. * * @throws OidcException * @throws JsonDebugException * @throws StoppedAuthenticationException */ protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User { $idTokenText = $accessToken->getIdToken(); $idToken = new OidcIdToken( $idTokenText, $settings->issuer, $settings->keys, ); session()->put("oidc_id_token", $idTokenText); $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [ 'access_token' => $accessToken->getToken(), 'expires_in' => $accessToken->getExpires(), 'refresh_token' => $accessToken->getRefreshToken(), ]); if (!is_null($returnClaims)) { $idToken->replaceClaims($returnClaims); } if ($this->config()['dump_user_details']) { throw new JsonDebugException($idToken->getAllClaims()); } try { $idToken->validate($settings->clientId); } catch (OidcInvalidTokenException $exception) { throw new OidcException("ID token validation failed with error: {$exception->getMessage()}"); } $userDetails = $this->getUserDetailsFromToken($idToken, $accessToken, $settings); if (empty($userDetails->email)) { throw new OidcException(trans('errors.oidc_no_email_address')); } if (empty($userDetails->name)) { $userDetails->name = $userDetails->externalId; } $isLoggedIn = auth()->check(); if ($isLoggedIn) { throw new OidcException(trans('errors.oidc_already_logged_in')); } try { $user = $this->registrationService->findOrRegister( $userDetails->name, $userDetails->email, $userDetails->externalId ); } catch (UserRegistrationException $exception) { throw new OidcException($exception->getMessage()); } if ($this->config()['fetch_avatar'] && !$user->avatar()->exists() && $userDetails->picture) { $this->userAvatars->assignToUserFromUrl($user, $userDetails->picture); } if ($this->shouldSyncGroups()) { $detachExisting = $this->config()['remove_from_groups']; $this->groupService->syncUserWithFoundGroups($user, $userDetails->groups ?? [], $detachExisting); } $this->loginService->login($user, 'oidc'); return $user; } /** * @throws OidcException */ protected function getUserDetailsFromToken(OidcIdToken $idToken, OidcAccessToken $accessToken, OidcProviderSettings $settings): OidcUserDetails { $userDetails = new OidcUserDetails(); $userDetails->populate( $idToken, $this->config()['external_id_claim'], $this->config()['display_name_claims'] ?? '', $this->config()['groups_claim'] ?? '' ); if (!$userDetails->isFullyPopulated($this->shouldSyncGroups()) && !empty($settings->userinfoEndpoint)) { $provider = $this->getProvider($settings); $request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken()); $response = new OidcUserinfoResponse( $provider->getResponse($request), $settings->issuer, $settings->keys, ); try { $response->validate($idToken->getClaim('sub'), $settings->clientId); } catch (OidcInvalidTokenException $exception) { throw new OidcException("Userinfo endpoint response validation failed with error: {$exception->getMessage()}"); } $userDetails->populate( $response, $this->config()['external_id_claim'], $this->config()['display_name_claims'] ?? '', $this->config()['groups_claim'] ?? '' ); } return $userDetails; } /** * Get the OIDC config from the application. */ protected function config(): array { return config('oidc'); } /** * Check if groups should be synced. */ protected function shouldSyncGroups(): bool { return $this->config()['user_to_groups'] !== false; } /** * Start the RP-initiated logout flow if active, otherwise start a standard logout flow. * Returns a post-app-logout redirect URL. * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html * @throws OidcException */ public function logout(): string { $oidcToken = session()->pull("oidc_id_token"); $defaultLogoutUrl = url($this->loginService->logout()); $oidcSettings = $this->getProviderSettings(); if (!$oidcSettings->endSessionEndpoint) { return $defaultLogoutUrl; } $endpointParams = [ 'id_token_hint' => $oidcToken, 'post_logout_redirect_uri' => $defaultLogoutUrl, ]; $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?'; return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcAccessToken.php
app/Access/Oidc/OidcAccessToken.php
<?php namespace BookStack\Access\Oidc; use InvalidArgumentException; use League\OAuth2\Client\Token\AccessToken; class OidcAccessToken extends AccessToken { /** * Constructs an access token. * * @param array $options An array of options returned by the service provider * in the access token request. The `access_token` option is required. * * @throws InvalidArgumentException if `access_token` is not provided in `$options`. */ public function __construct(array $options = []) { parent::__construct($options); $this->validate($options); } /** * Validate this access token response for OIDC. * As per https://openid.net/specs/openid-connect-basic-1_0.html#TokenOK. */ private function validate(array $options): void { // access_token: REQUIRED. Access Token for the UserInfo Endpoint. // Performed on the extended class // token_type: REQUIRED. OAuth 2.0 Token Type value. The value MUST be Bearer, as specified in OAuth 2.0 // Bearer Token Usage [RFC6750], for Clients using this subset. // Note that the token_type value is case-insensitive. if (strtolower(($options['token_type'] ?? '')) !== 'bearer') { throw new InvalidArgumentException('The response token type MUST be "Bearer"'); } // id_token: REQUIRED. ID Token. if (empty($options['id_token'])) { throw new InvalidArgumentException('An "id_token" property must be provided'); } } /** * Get the id token value from this access token response. */ public function getIdToken(): string { return $this->getValues()['id_token']; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcUserinfoResponse.php
app/Access/Oidc/OidcUserinfoResponse.php
<?php namespace BookStack\Access\Oidc; use Psr\Http\Message\ResponseInterface; class OidcUserinfoResponse implements ProvidesClaims { protected array $claims = []; protected ?OidcJwtWithClaims $jwt = null; public function __construct(ResponseInterface $response, string $issuer, array $keys) { $contentTypeHeaderValue = $response->getHeader('Content-Type')[0] ?? ''; $contentType = strtolower(trim(explode(';', $contentTypeHeaderValue, 2)[0])); if ($contentType === 'application/json') { $this->claims = json_decode($response->getBody()->getContents(), true); } if ($contentType === 'application/jwt') { $this->jwt = new OidcJwtWithClaims($response->getBody()->getContents(), $issuer, $keys); $this->claims = $this->jwt->getAllClaims(); } } /** * @throws OidcInvalidTokenException */ public function validate(string $idTokenSub, string $clientId): bool { if (!is_null($this->jwt)) { $this->jwt->validateCommonTokenDetails($clientId); } $sub = $this->getClaim('sub'); // Spec: v1.0 5.3.2: The sub (subject) Claim MUST always be returned in the UserInfo Response. if (!is_string($sub) || empty($sub)) { throw new OidcInvalidTokenException("No valid subject value found in userinfo data"); } // Spec: v1.0 5.3.2: The sub Claim in the UserInfo Response MUST be verified to exactly match the sub Claim in the ID Token; // if they do not match, the UserInfo Response values MUST NOT be used. if ($idTokenSub !== $sub) { throw new OidcInvalidTokenException("Subject value provided in the userinfo endpoint does not match the provided ID token value"); } // Spec v1.0 5.3.4 Defines the following: // Verify that the OP that responded was the intended OP through a TLS server certificate check, per RFC 6125 [RFC6125]. // This is effectively done as part of the HTTP request we're making through CURLOPT_SSL_VERIFYHOST on the request. // If the Client has provided a userinfo_encrypted_response_alg parameter during Registration, decrypt the UserInfo Response using the keys specified during Registration. // We don't currently support JWT encryption for OIDC // If the response was signed, the Client SHOULD validate the signature according to JWS [JWS]. // This is done as part of the validateCommonClaims above. return true; } public function getClaim(string $claim): mixed { return $this->claims[$claim] ?? null; } public function getAllClaims(): array { return $this->claims; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/ProvidesClaims.php
app/Access/Oidc/ProvidesClaims.php
<?php namespace BookStack\Access\Oidc; interface ProvidesClaims { /** * Fetch a specific claim. * Returns null if it is null or does not exist. */ public function getClaim(string $claim): mixed; /** * Get all contained claims. */ public function getAllClaims(): array; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcOAuthProvider.php
app/Access/Oidc/OidcOAuthProvider.php
<?php namespace BookStack\Access\Oidc; use League\OAuth2\Client\Grant\AbstractGrant; use League\OAuth2\Client\Provider\AbstractProvider; use League\OAuth2\Client\Provider\Exception\IdentityProviderException; use League\OAuth2\Client\Provider\GenericResourceOwner; use League\OAuth2\Client\Provider\ResourceOwnerInterface; use League\OAuth2\Client\Token\AccessToken; use League\OAuth2\Client\Tool\BearerAuthorizationTrait; use Psr\Http\Message\ResponseInterface; /** * Extended OAuth2Provider for using with OIDC. * Credit to the https://github.com/steverhoades/oauth2-openid-connect-client * project for the idea of extending a League\OAuth2 client for this use-case. */ class OidcOAuthProvider extends AbstractProvider { use BearerAuthorizationTrait; protected string $authorizationEndpoint; protected string $tokenEndpoint; /** * Scopes to use for the OIDC authorization call. */ protected array $scopes = ['openid', 'profile', 'email']; /** * Returns the base URL for authorizing a client. */ public function getBaseAuthorizationUrl(): string { return $this->authorizationEndpoint; } /** * Returns the base URL for requesting an access token. */ public function getBaseAccessTokenUrl(array $params): string { return $this->tokenEndpoint; } /** * Returns the URL for requesting the resource owner's details. */ public function getResourceOwnerDetailsUrl(AccessToken $token): string { return ''; } /** * Add another scope to this provider upon the default. */ public function addScope(string $scope): void { $this->scopes[] = $scope; $this->scopes = array_unique($this->scopes); } /** * Returns the default scopes used by this provider. * * This should only be the scopes that are required to request the details * of the resource owner, rather than all the available scopes. */ protected function getDefaultScopes(): array { return $this->scopes; } /** * Returns the string that should be used to separate scopes when building * the URL for requesting an access token. */ protected function getScopeSeparator(): string { return ' '; } /** * Checks a provider response for errors. * @throws IdentityProviderException */ protected function checkResponse(ResponseInterface $response, $data): void { if ($response->getStatusCode() >= 400 || isset($data['error'])) { throw new IdentityProviderException( $data['error'] ?? $response->getReasonPhrase(), $response->getStatusCode(), (string) $response->getBody() ); } } /** * Generates a resource owner object from a successful resource owner * details request. */ protected function createResourceOwner(array $response, AccessToken $token): ResourceOwnerInterface { return new GenericResourceOwner($response, ''); } /** * Creates an access token from a response. * * The grant that was used to fetch the response can be used to provide * additional context. */ protected function createAccessToken(array $response, AbstractGrant $grant): OidcAccessToken { return new OidcAccessToken($response); } /** * Get the method used for PKCE code verifier hashing, which is passed * in the "code_challenge_method" parameter in the authorization request. */ protected function getPkceMethod(): string { return static::PKCE_METHOD_S256; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcIdToken.php
app/Access/Oidc/OidcIdToken.php
<?php namespace BookStack\Access\Oidc; class OidcIdToken extends OidcJwtWithClaims implements ProvidesClaims { /** * Validate all possible parts of the id token. * * @throws OidcInvalidTokenException */ public function validate(string $clientId): bool { parent::validateCommonTokenDetails($clientId); $this->validateTokenClaims($clientId); return true; } /** * Validate the claims of the token. * As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation. * * @throws OidcInvalidTokenException */ protected function validateTokenClaims(string $clientId): void { // 1. The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery) // MUST exactly match the value of the iss (issuer) Claim. // Already done in parent. // 2. The Client MUST validate that the aud (audience) Claim contains its client_id value registered // at the Issuer identified by the iss (issuer) Claim as an audience. The ID Token MUST be rejected // if the ID Token does not list the Client as a valid audience, or if it contains additional // audiences not trusted by the Client. // Partially done in parent. $aud = is_string($this->payload['aud']) ? [$this->payload['aud']] : $this->payload['aud']; if (count($aud) !== 1) { throw new OidcInvalidTokenException('Token audience value has ' . count($aud) . ' values, Expected 1'); } // 3. If the ID Token contains multiple audiences, the Client SHOULD verify that an azp Claim is present. // NOTE: Addressed by enforcing a count of 1 above. // 4. If an azp (authorized party) Claim is present, the Client SHOULD verify that its client_id // is the Claim Value. if (isset($this->payload['azp']) && $this->payload['azp'] !== $clientId) { throw new OidcInvalidTokenException('Token authorized party exists but does not match the expected client_id'); } // 5. The current time MUST be before the time represented by the exp Claim // (possibly allowing for some small leeway to account for clock skew). if (empty($this->payload['exp'])) { throw new OidcInvalidTokenException('Missing token expiration time value'); } $skewSeconds = 120; $now = time(); if ($now >= (intval($this->payload['exp']) + $skewSeconds)) { throw new OidcInvalidTokenException('Token has expired'); } // 6. The iat Claim can be used to reject tokens that were issued too far away from the current time, // limiting the amount of time that nonces need to be stored to prevent attacks. // The acceptable range is Client specific. if (empty($this->payload['iat'])) { throw new OidcInvalidTokenException('Missing token issued at time value'); } $dayAgo = time() - 86400; $iat = intval($this->payload['iat']); if ($iat > ($now + $skewSeconds) || $iat < $dayAgo) { throw new OidcInvalidTokenException('Token issue at time is not recent or is invalid'); } // 7. If the acr Claim was requested, the Client SHOULD check that the asserted Claim Value is appropriate. // The meaning and processing of acr Claim Values is out of scope for this document. // NOTE: Not used for our case here. acr is not requested. // 8. When a max_age request is made, the Client SHOULD check the auth_time Claim value and request // re-authentication if it determines too much time has elapsed since the last End-User authentication. // NOTE: Not used for our case here. A max_age request is not made. // Custom: Ensure the "sub" (Subject) Claim exists and has a value. if (empty($this->payload['sub'])) { throw new OidcInvalidTokenException('Missing token subject value'); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcJwtWithClaims.php
app/Access/Oidc/OidcJwtWithClaims.php
<?php namespace BookStack\Access\Oidc; class OidcJwtWithClaims implements ProvidesClaims { protected array $header; protected array $payload; protected string $signature; protected string $issuer; protected array $tokenParts = []; /** * @var array[]|string[] */ protected array $keys; public function __construct(string $token, string $issuer, array $keys) { $this->keys = $keys; $this->issuer = $issuer; $this->parse($token); } /** * Parse the token content into its components. */ protected function parse(string $token): void { $this->tokenParts = explode('.', $token); $this->header = $this->parseEncodedTokenPart($this->tokenParts[0]); $this->payload = $this->parseEncodedTokenPart($this->tokenParts[1] ?? ''); $this->signature = $this->base64UrlDecode($this->tokenParts[2] ?? '') ?: ''; } /** * Parse a Base64-JSON encoded token part. * Returns the data as a key-value array or empty array upon error. */ protected function parseEncodedTokenPart(string $part): array { $json = $this->base64UrlDecode($part) ?: '{}'; $decoded = json_decode($json, true); return is_array($decoded) ? $decoded : []; } /** * Base64URL decode. Needs some character conversions to be compatible * with PHP's default base64 handling. */ protected function base64UrlDecode(string $encoded): string { return base64_decode(strtr($encoded, '-_', '+/')); } /** * Validate common parts of OIDC JWT tokens. * * @throws OidcInvalidTokenException */ public function validateCommonTokenDetails(string $clientId): bool { $this->validateTokenStructure(); $this->validateTokenSignature(); $this->validateCommonClaims($clientId); return true; } /** * Fetch a specific claim from this token. * Returns null if it is null or does not exist. */ public function getClaim(string $claim): mixed { return $this->payload[$claim] ?? null; } /** * Get all returned claims within the token. */ public function getAllClaims(): array { return $this->payload; } /** * Replace the existing claim data of this token with that provided. */ public function replaceClaims(array $claims): void { $this->payload = $claims; } /** * Validate the structure of the given token and ensure we have the required pieces. * As per https://datatracker.ietf.org/doc/html/rfc7519#section-7.2. * * @throws OidcInvalidTokenException */ protected function validateTokenStructure(): void { foreach (['header', 'payload'] as $prop) { if (empty($this->$prop) || !is_array($this->$prop)) { throw new OidcInvalidTokenException("Could not parse out a valid {$prop} within the provided token"); } } if (empty($this->signature) || !is_string($this->signature)) { throw new OidcInvalidTokenException('Could not parse out a valid signature within the provided token'); } } /** * Validate the signature of the given token and ensure it validates against the provided key. * * @throws OidcInvalidTokenException */ protected function validateTokenSignature(): void { if ($this->header['alg'] !== 'RS256') { throw new OidcInvalidTokenException("Only RS256 signature validation is supported. Token reports using {$this->header['alg']}"); } $parsedKeys = array_map(function ($key) { try { return new OidcJwtSigningKey($key); } catch (OidcInvalidKeyException $e) { throw new OidcInvalidTokenException('Failed to read signing key with error: ' . $e->getMessage()); } }, $this->keys); $parsedKeys = array_filter($parsedKeys); $contentToSign = $this->tokenParts[0] . '.' . $this->tokenParts[1]; /** @var OidcJwtSigningKey $parsedKey */ foreach ($parsedKeys as $parsedKey) { if ($parsedKey->verify($contentToSign, $this->signature)) { return; } } throw new OidcInvalidTokenException('Token signature could not be validated using the provided keys'); } /** * Validate common claims for OIDC JWT tokens. * As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation * and https://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse * * @throws OidcInvalidTokenException */ protected function validateCommonClaims(string $clientId): void { // 1. The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery) // MUST exactly match the value of the iss (issuer) Claim. if (empty($this->payload['iss']) || $this->issuer !== $this->payload['iss']) { throw new OidcInvalidTokenException('Missing or non-matching token issuer value'); } // 2. The Client MUST validate that the aud (audience) Claim contains its client_id value registered // at the Issuer identified by the iss (issuer) Claim as an audience. The ID Token MUST be rejected // if the ID Token does not list the Client as a valid audience. if (empty($this->payload['aud'])) { throw new OidcInvalidTokenException('Missing token audience value'); } $aud = is_string($this->payload['aud']) ? [$this->payload['aud']] : $this->payload['aud']; if (!in_array($clientId, $aud, true)) { throw new OidcInvalidTokenException('Token audience value did not match the expected client_id'); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcInvalidKeyException.php
app/Access/Oidc/OidcInvalidKeyException.php
<?php namespace BookStack\Access\Oidc; class OidcInvalidKeyException extends \Exception { }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcProviderSettings.php
app/Access/Oidc/OidcProviderSettings.php
<?php namespace BookStack\Access\Oidc; use GuzzleHttp\Psr7\Request; use Illuminate\Contracts\Cache\Repository; use InvalidArgumentException; use Psr\Http\Client\ClientExceptionInterface; use Psr\Http\Client\ClientInterface; /** * OpenIdConnectProviderSettings * Acts as a DTO for settings used within the oidc request and token handling. * Performs auto-discovery upon request. */ class OidcProviderSettings { public string $issuer; public string $clientId; public string $clientSecret; public ?string $authorizationEndpoint; public ?string $tokenEndpoint; public ?string $endSessionEndpoint; public ?string $userinfoEndpoint; /** * @var string[]|array[] */ public ?array $keys = []; public function __construct(array $settings) { $this->applySettingsFromArray($settings); $this->validateInitial(); } /** * Apply an array of settings to populate setting properties within this class. */ protected function applySettingsFromArray(array $settingsArray): void { foreach ($settingsArray as $key => $value) { if (property_exists($this, $key)) { $this->$key = $value; } } } /** * Validate any core, required properties have been set. * * @throws InvalidArgumentException */ protected function validateInitial(): void { $required = ['clientId', 'clientSecret', 'issuer']; foreach ($required as $prop) { if (empty($this->$prop)) { throw new InvalidArgumentException("Missing required configuration \"{$prop}\" value"); } } if (!str_starts_with($this->issuer, 'https://')) { throw new InvalidArgumentException('Issuer value must start with https://'); } } /** * Perform a full validation on these settings. * * @throws InvalidArgumentException */ public function validate(): void { $this->validateInitial(); $required = ['keys', 'tokenEndpoint', 'authorizationEndpoint']; foreach ($required as $prop) { if (empty($this->$prop)) { throw new InvalidArgumentException("Missing required configuration \"{$prop}\" value"); } } $endpointProperties = ['tokenEndpoint', 'authorizationEndpoint', 'userinfoEndpoint']; foreach ($endpointProperties as $prop) { if (is_string($this->$prop) && !str_starts_with($this->$prop, 'https://')) { throw new InvalidArgumentException("Endpoint value for \"{$prop}\" must start with https://"); } } } /** * Discover and autoload settings from the configured issuer. * * @throws OidcIssuerDiscoveryException */ public function discoverFromIssuer(ClientInterface $httpClient, Repository $cache, int $cacheMinutes): void { try { $cacheKey = 'oidc-discovery::' . $this->issuer; $discoveredSettings = $cache->remember($cacheKey, $cacheMinutes * 60, function () use ($httpClient) { return $this->loadSettingsFromIssuerDiscovery($httpClient); }); $this->applySettingsFromArray($discoveredSettings); } catch (ClientExceptionInterface $exception) { throw new OidcIssuerDiscoveryException("HTTP request failed during discovery with error: {$exception->getMessage()}"); } } /** * @throws OidcIssuerDiscoveryException * @throws ClientExceptionInterface */ protected function loadSettingsFromIssuerDiscovery(ClientInterface $httpClient): array { $issuerUrl = rtrim($this->issuer, '/') . '/.well-known/openid-configuration'; $request = new Request('GET', $issuerUrl); $response = $httpClient->sendRequest($request); $result = json_decode($response->getBody()->getContents(), true); if (empty($result) || !is_array($result)) { throw new OidcIssuerDiscoveryException("Error discovering provider settings from issuer at URL {$issuerUrl}"); } if ($result['issuer'] !== $this->issuer) { throw new OidcIssuerDiscoveryException('Unexpected issuer value found on discovery response'); } $discoveredSettings = []; if (!empty($result['authorization_endpoint'])) { $discoveredSettings['authorizationEndpoint'] = $result['authorization_endpoint']; } if (!empty($result['token_endpoint'])) { $discoveredSettings['tokenEndpoint'] = $result['token_endpoint']; } if (!empty($result['userinfo_endpoint'])) { $discoveredSettings['userinfoEndpoint'] = $result['userinfo_endpoint']; } if (!empty($result['jwks_uri'])) { $keys = $this->loadKeysFromUri($result['jwks_uri'], $httpClient); $discoveredSettings['keys'] = $this->filterKeys($keys); } if (!empty($result['end_session_endpoint'])) { $discoveredSettings['endSessionEndpoint'] = $result['end_session_endpoint']; } return $discoveredSettings; } /** * Filter the given JWK keys down to just those we support. */ protected function filterKeys(array $keys): array { return array_filter($keys, function (array $key) { $alg = $key['alg'] ?? 'RS256'; $use = $key['use'] ?? 'sig'; return $key['kty'] === 'RSA' && $use === 'sig' && $alg === 'RS256'; }); } /** * Return an array of jwks as PHP key=>value arrays. * * @throws ClientExceptionInterface * @throws OidcIssuerDiscoveryException */ protected function loadKeysFromUri(string $uri, ClientInterface $httpClient): array { $request = new Request('GET', $uri); $response = $httpClient->sendRequest($request); $result = json_decode($response->getBody()->getContents(), true); if (empty($result) || !is_array($result) || !isset($result['keys'])) { throw new OidcIssuerDiscoveryException('Error reading keys from issuer jwks_uri'); } return $result['keys']; } /** * Get the settings needed by an OAuth provider, as a key=>value array. */ public function arrayForOAuthProvider(): array { $settingKeys = ['clientId', 'clientSecret', 'authorizationEndpoint', 'tokenEndpoint', 'userinfoEndpoint']; $settings = []; foreach ($settingKeys as $setting) { $settings[$setting] = $this->$setting; } return $settings; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcUserDetails.php
app/Access/Oidc/OidcUserDetails.php
<?php namespace BookStack\Access\Oidc; use Illuminate\Support\Arr; class OidcUserDetails { public function __construct( public ?string $externalId = null, public ?string $email = null, public ?string $name = null, public ?array $groups = null, public ?string $picture = null, ) { } /** * Check if the user details are fully populated for our usage. */ public function isFullyPopulated(bool $groupSyncActive): bool { $hasEmpty = empty($this->externalId) || empty($this->email) || empty($this->name) || ($groupSyncActive && $this->groups === null); return !$hasEmpty; } /** * Populate user details from the given claim data. */ public function populate( ProvidesClaims $claims, string $idClaim, string $displayNameClaims, string $groupsClaim, ): void { $this->externalId = $claims->getClaim($idClaim) ?? $this->externalId; $this->email = $claims->getClaim('email') ?? $this->email; $this->name = static::getUserDisplayName($displayNameClaims, $claims) ?? $this->name; $this->groups = static::getUserGroups($groupsClaim, $claims) ?? $this->groups; $this->picture = static::getPicture($claims) ?: $this->picture; } protected static function getUserDisplayName(string $displayNameClaims, ProvidesClaims $claims): string { $displayNameClaimParts = explode('|', $displayNameClaims); $displayName = []; foreach ($displayNameClaimParts as $claim) { $component = $claims->getClaim(trim($claim)) ?? ''; if ($component !== '') { $displayName[] = $component; } } return implode(' ', $displayName); } protected static function getUserGroups(string $groupsClaim, ProvidesClaims $claims): ?array { if (empty($groupsClaim)) { return null; } $groupsList = Arr::get($claims->getAllClaims(), $groupsClaim); if (!is_array($groupsList)) { return null; } return array_values(array_filter($groupsList, function ($val) { return is_string($val); })); } protected static function getPicture(ProvidesClaims $claims): ?string { $picture = $claims->getClaim('picture'); if (is_string($picture) && str_starts_with($picture, 'http')) { return $picture; } return null; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcIssuerDiscoveryException.php
app/Access/Oidc/OidcIssuerDiscoveryException.php
<?php namespace BookStack\Access\Oidc; use Exception; class OidcIssuerDiscoveryException extends Exception { }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Oidc/OidcException.php
app/Access/Oidc/OidcException.php
<?php namespace BookStack\Access\Oidc; use Exception; class OidcException extends Exception { }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Guards/ExternalBaseSessionGuard.php
app/Access/Guards/ExternalBaseSessionGuard.php
<?php namespace BookStack\Access\Guards; use BookStack\Access\RegistrationService; use Illuminate\Auth\GuardHelpers; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\StatefulGuard; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Contracts\Session\Session; /** * Class BaseSessionGuard * A base implementation of a session guard. Is a copy of the default Laravel * guard with 'remember' functionality removed. Basic auth and event emission * has also been removed to keep this simple. Designed to be extended by external * Auth Guards. */ class ExternalBaseSessionGuard implements StatefulGuard { use GuardHelpers; /** * The name of the Guard. Typically "session". * * Corresponds to guard name in authentication configuration. */ protected readonly string $name; /** * The user we last attempted to retrieve. */ protected Authenticatable|null $lastAttempted; /** * The session used by the guard. */ protected Session $session; /** * Indicates if the logout method has been called. */ protected bool $loggedOut = false; /** * Service to handle common registration actions. */ protected RegistrationService $registrationService; /** * Create a new authentication guard. */ public function __construct(string $name, UserProvider $provider, Session $session, RegistrationService $registrationService) { $this->name = $name; $this->session = $session; $this->provider = $provider; $this->registrationService = $registrationService; } /** * Get the currently authenticated user. */ public function user(): Authenticatable|null { if ($this->loggedOut) { return null; } // If we've already retrieved the user for the current request we can just // return it back immediately. We do not want to fetch the user data on // every call to this method because that would be tremendously slow. if (!is_null($this->user)) { return $this->user; } $id = $this->session->get($this->getName()); // First we will try to load the user using the // identifier in the session if one exists. if (!is_null($id)) { $this->user = $this->provider->retrieveById($id); } return $this->user; } /** * Get the ID for the currently authenticated user. */ public function id(): int|null { if ($this->loggedOut) { return null; } return $this->user() ? $this->user()->getAuthIdentifier() : $this->session->get($this->getName()); } /** * Log a user into the application without sessions or cookies. */ public function once(array $credentials = []): bool { if ($this->validate($credentials)) { $this->setUser($this->lastAttempted); return true; } return false; } /** * Log the given user ID into the application without sessions or cookies. */ public function onceUsingId($id): Authenticatable|false { if (!is_null($user = $this->provider->retrieveById($id))) { $this->setUser($user); return $user; } return false; } /** * Validate a user's credentials. */ public function validate(array $credentials = []): bool { return false; } /** * Attempt to authenticate a user using the given credentials. * @param bool $remember */ public function attempt(array $credentials = [], $remember = false): bool { return false; } /** * Log the given user ID into the application. * @param bool $remember */ public function loginUsingId(mixed $id, $remember = false): Authenticatable|false { // Always return false as to disable this method, // Logins should route through LoginService. return false; } /** * Log a user into the application. * * @param bool $remember */ public function login(Authenticatable $user, $remember = false): void { $this->updateSession($user->getAuthIdentifier()); $this->setUser($user); } /** * Update the session with the given ID. */ protected function updateSession(string|int $id): void { $this->session->put($this->getName(), $id); $this->session->migrate(true); } /** * Log the user out of the application. */ public function logout(): void { $this->clearUserDataFromStorage(); // Now we will clear the users out of memory so they are no longer available // as the user is no longer considered as being signed into this // application and should not be available here. $this->user = null; $this->loggedOut = true; } /** * Remove the user data from the session and cookies. */ protected function clearUserDataFromStorage(): void { $this->session->remove($this->getName()); } /** * Get the last user we attempted to authenticate. */ public function getLastAttempted(): Authenticatable { return $this->lastAttempted; } /** * Get a unique identifier for the auth session value. */ public function getName(): string { return 'login_' . $this->name . '_' . sha1(static::class); } /** * Determine if the user was authenticated via "remember me" cookie. */ public function viaRemember(): bool { return false; } /** * Return the currently cached user. */ public function getUser(): Authenticatable|null { return $this->user; } /** * Set the current user. */ public function setUser(Authenticatable $user): self { $this->user = $user; $this->loggedOut = false; return $this; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Guards/AsyncExternalBaseSessionGuard.php
app/Access/Guards/AsyncExternalBaseSessionGuard.php
<?php namespace BookStack\Access\Guards; /** * External Auth Session Guard. * * The login process for external auth (SAML2/OIDC) is async in nature, meaning it does not fit very well * into the default laravel 'Guard' auth flow. Instead, most of the logic is done via the relevant * controller and services. This class provides a safer, thin version of SessionGuard. */ class AsyncExternalBaseSessionGuard extends ExternalBaseSessionGuard { /** * Validate a user's credentials. */ public function validate(array $credentials = []): bool { return false; } /** * Attempt to authenticate a user using the given credentials. * * @param bool $remember */ public function attempt(array $credentials = [], $remember = false): bool { return false; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Guards/LdapSessionGuard.php
app/Access/Guards/LdapSessionGuard.php
<?php namespace BookStack\Access\Guards; use BookStack\Access\LdapService; use BookStack\Access\RegistrationService; use BookStack\Exceptions\JsonDebugException; use BookStack\Exceptions\LdapException; use BookStack\Exceptions\LoginAttemptEmailNeededException; use BookStack\Exceptions\LoginAttemptException; use BookStack\Exceptions\UserRegistrationException; use BookStack\Users\Models\User; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Contracts\Session\Session; use Illuminate\Support\Str; class LdapSessionGuard extends ExternalBaseSessionGuard { protected LdapService $ldapService; /** * LdapSessionGuard constructor. */ public function __construct( $name, UserProvider $provider, Session $session, LdapService $ldapService, RegistrationService $registrationService ) { $this->ldapService = $ldapService; parent::__construct($name, $provider, $session, $registrationService); } /** * Validate a user's credentials. * * @throws LdapException */ public function validate(array $credentials = []): bool { $userDetails = $this->ldapService->getUserDetails($credentials['username']); if (isset($userDetails['uid'])) { $this->lastAttempted = $this->provider->retrieveByCredentials([ 'external_auth_id' => $userDetails['uid'], ]); } return $this->ldapService->validateUserCredentials($userDetails, $credentials['password']); } /** * Attempt to authenticate a user using the given credentials. * * @param bool $remember * * @throws LdapException * @throws LoginAttemptException * @throws JsonDebugException */ public function attempt(array $credentials = [], $remember = false): bool { $username = $credentials['username']; $userDetails = $this->ldapService->getUserDetails($username); $user = null; if (isset($userDetails['uid'])) { $this->lastAttempted = $user = $this->provider->retrieveByCredentials([ 'external_auth_id' => $userDetails['uid'], ]); } if (!$this->ldapService->validateUserCredentials($userDetails, $credentials['password'])) { return false; } if (is_null($user)) { try { $user = $this->createNewFromLdapAndCreds($userDetails, $credentials); } catch (UserRegistrationException $exception) { throw new LoginAttemptException($exception->getMessage()); } } // Sync LDAP groups if required if ($this->ldapService->shouldSyncGroups()) { $this->ldapService->syncGroups($user, $username); } // Attach avatar if non-existent if (!$user->avatar()->exists()) { $this->ldapService->saveAndAttachAvatar($user, $userDetails); } $this->login($user, $remember); return true; } /** * Create a new user from the given ldap credentials and login credentials. * * @throws LoginAttemptEmailNeededException * @throws LoginAttemptException * @throws UserRegistrationException */ protected function createNewFromLdapAndCreds(array $ldapUserDetails, array $credentials): User { $email = trim($ldapUserDetails['email'] ?: ($credentials['email'] ?? '')); if (empty($email)) { throw new LoginAttemptEmailNeededException(); } $details = [ 'name' => $ldapUserDetails['name'], 'email' => $ldapUserDetails['email'] ?: $credentials['email'], 'external_auth_id' => $ldapUserDetails['uid'], 'password' => Str::random(32), ]; $user = $this->registrationService->registerUser($details, null, false); $this->ldapService->saveAndAttachAvatar($user, $ldapUserDetails); return $user; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Notifications/UserInviteNotification.php
app/Access/Notifications/UserInviteNotification.php
<?php namespace BookStack\Access\Notifications; use BookStack\App\MailNotification; use BookStack\Users\Models\User; use Illuminate\Notifications\Messages\MailMessage; class UserInviteNotification extends MailNotification { public function __construct( public string $token ) { } public function toMail(User $notifiable): MailMessage { $appName = ['appName' => setting('app-name')]; $locale = $notifiable->getLocale(); return $this->newMailMessage($locale) ->subject($locale->trans('auth.user_invite_email_subject', $appName)) ->greeting($locale->trans('auth.user_invite_email_greeting', $appName)) ->line($locale->trans('auth.user_invite_email_text')) ->action($locale->trans('auth.user_invite_email_action'), url('/register/invite/' . $this->token)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Notifications/ResetPasswordNotification.php
app/Access/Notifications/ResetPasswordNotification.php
<?php namespace BookStack\Access\Notifications; use BookStack\App\MailNotification; use BookStack\Users\Models\User; use Illuminate\Notifications\Messages\MailMessage; class ResetPasswordNotification extends MailNotification { public function __construct( public string $token ) { } public function toMail(User $notifiable): MailMessage { return $this->newMailMessage() ->subject(trans('auth.email_reset_subject', ['appName' => setting('app-name')])) ->line(trans('auth.email_reset_text')) ->action(trans('auth.reset_password'), url('password/reset/' . $this->token)) ->line(trans('auth.email_reset_not_requested')); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Notifications/ConfirmEmailNotification.php
app/Access/Notifications/ConfirmEmailNotification.php
<?php namespace BookStack\Access\Notifications; use BookStack\App\MailNotification; use BookStack\Users\Models\User; use Illuminate\Notifications\Messages\MailMessage; class ConfirmEmailNotification extends MailNotification { public function __construct( public string $token ) { } public function toMail(User $notifiable): MailMessage { $appName = ['appName' => setting('app-name')]; return $this->newMailMessage() ->subject(trans('auth.email_confirm_subject', $appName)) ->greeting(trans('auth.email_confirm_greeting', $appName)) ->line(trans('auth.email_confirm_text')) ->action(trans('auth.email_confirm_action'), url('/register/confirm/' . $this->token)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Mfa/MfaSession.php
app/Access/Mfa/MfaSession.php
<?php namespace BookStack\Access\Mfa; use BookStack\Users\Models\User; class MfaSession { /** * Check if MFA is required for the given user. */ public function isRequiredForUser(User $user): bool { return $user->mfaValues()->exists() || $this->userRoleEnforcesMfa($user); } /** * Check if the given user is pending MFA setup. * (MFA required but not yet configured). */ public function isPendingMfaSetup(User $user): bool { return $this->isRequiredForUser($user) && !$user->mfaValues()->exists(); } /** * Check if a role of the given user enforces MFA. */ protected function userRoleEnforcesMfa(User $user): bool { return $user->roles() ->where('mfa_enforced', '=', true) ->exists(); } /** * Check if the current MFA session has already been verified for the given user. */ public function isVerifiedForUser(User $user): bool { return session()->get($this->getMfaVerifiedSessionKey($user)) === 'true'; } /** * Mark the current session as MFA-verified. */ public function markVerifiedForUser(User $user): void { session()->put($this->getMfaVerifiedSessionKey($user), 'true'); } /** * Get the session key in which the MFA verification status is stored. */ protected function getMfaVerifiedSessionKey(User $user): string { return 'mfa-verification-passed:' . $user->id; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Mfa/TotpService.php
app/Access/Mfa/TotpService.php
<?php namespace BookStack\Access\Mfa; use BaconQrCode\Renderer\Color\Rgb; use BaconQrCode\Renderer\Image\SvgImageBackEnd; use BaconQrCode\Renderer\ImageRenderer; use BaconQrCode\Renderer\RendererStyle\Fill; use BaconQrCode\Renderer\RendererStyle\RendererStyle; use BaconQrCode\Writer; use BookStack\Users\Models\User; use PragmaRX\Google2FA\Google2FA; use PragmaRX\Google2FA\Support\Constants; class TotpService { public function __construct( protected Google2FA $google2fa ) { $this->google2fa = $google2fa; // Use SHA1 as a default, Personal testing of other options in 2021 found // many apps lack support for other algorithms yet still will scan // the code causing a confusing UX. $this->google2fa->setAlgorithm(Constants::SHA1); } /** * Generate a new totp secret key. */ public function generateSecret(): string { /** @noinspection PhpUnhandledExceptionInspection */ return $this->google2fa->generateSecretKey(); } /** * Generate a TOTP URL from a secret key. */ public function generateUrl(string $secret, User $user): string { return $this->google2fa->getQRCodeUrl( setting('app-name'), $user->email, $secret ); } /** * Generate a QR code to display a TOTP URL. */ public function generateQrCodeSvg(string $url): string { $color = Fill::uniformColor(new Rgb(255, 255, 255), new Rgb(32, 110, 167)); return (new Writer( new ImageRenderer( new RendererStyle(192, 4, null, null, $color), new SvgImageBackEnd() ) ))->writeString($url); } /** * Verify that the user provided code is valid for the secret. * The secret must be known, not user-provided. */ public function verifyCode(string $code, string $secret): bool { /** @noinspection PhpUnhandledExceptionInspection */ return $this->google2fa->verifyKey($secret, $code); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Mfa/TotpValidationRule.php
app/Access/Mfa/TotpValidationRule.php
<?php namespace BookStack\Access\Mfa; use Closure; use Illuminate\Contracts\Validation\ValidationRule; class TotpValidationRule implements ValidationRule { /** * Create a new rule instance. * Takes the TOTP secret that must be system provided, not user provided. */ public function __construct( protected string $secret, protected TotpService $totpService, ) { } public function validate(string $attribute, mixed $value, Closure $fail): void { $passes = $this->totpService->verifyCode($value, $this->secret); if (!$passes) { $fail(trans('validation.totp')); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Mfa/BackupCodeService.php
app/Access/Mfa/BackupCodeService.php
<?php namespace BookStack\Access\Mfa; use Illuminate\Support\Str; class BackupCodeService { /** * Generate a new set of 16 backup codes. */ public function generateNewSet(): array { $codes = []; while (count($codes) < 16) { $code = Str::random(5) . '-' . Str::random(5); if (!in_array($code, $codes)) { $codes[] = strtolower($code); } } return $codes; } /** * Check if the given code matches one of the available options. */ public function inputCodeExistsInSet(string $code, string $codeSet): bool { $cleanCode = $this->cleanInputCode($code); $codes = json_decode($codeSet); return in_array($cleanCode, $codes); } /** * Remove the given input code from the given available options. * Will return a JSON string containing the codes. */ public function removeInputCodeFromSet(string $code, string $codeSet): string { $cleanCode = $this->cleanInputCode($code); $codes = json_decode($codeSet); $pos = array_search($cleanCode, $codes, true); array_splice($codes, $pos, 1); return json_encode($codes); } /** * Count the number of codes in the given set. */ public function countCodesInSet(string $codeSet): int { return count(json_decode($codeSet)); } protected function cleanInputCode(string $code): string { return strtolower(str_replace(' ', '-', trim($code))); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Access/Mfa/MfaValue.php
app/Access/Mfa/MfaValue.php
<?php namespace BookStack\Access\Mfa; use BookStack\Users\Models\User; use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; /** * @property int $id * @property int $user_id * @property string $method * @property string $value * @property Carbon $created_at * @property Carbon $updated_at */ class MfaValue extends Model { use HasFactory; protected static $unguarded = true; const METHOD_TOTP = 'totp'; const METHOD_BACKUP_CODES = 'backup_codes'; /** * Get all the MFA methods available. */ public static function allMethods(): array { return [self::METHOD_TOTP, self::METHOD_BACKUP_CODES]; } /** * Upsert a new MFA value for the given user and method * using the provided value. */ public static function upsertWithValue(User $user, string $method, string $value): void { /** @var MfaValue $mfaVal */ $mfaVal = static::query()->firstOrNew([ 'user_id' => $user->id, 'method' => $method, ]); $mfaVal->setValue($value); $mfaVal->save(); } /** * Easily get the decrypted MFA value for the given user and method. */ public static function getValueForUser(User $user, string $method): ?string { /** @var MfaValue $mfaVal */ $mfaVal = static::query() ->where('user_id', '=', $user->id) ->where('method', '=', $method) ->first(); return $mfaVal ? $mfaVal->getValue() : null; } /** * Decrypt the value attribute upon access. */ protected function getValue(): string { return decrypt($this->value); } /** * Encrypt the value attribute upon access. */ protected function setValue($value): void { $this->value = encrypt($value); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false