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/Activity/Controllers/TagController.php
app/Activity/Controllers/TagController.php
<?php namespace BookStack\Activity\Controllers; use BookStack\Activity\TagRepo; use BookStack\Http\Controller; use BookStack\Util\SimpleListOptions; use Illuminate\Http\Request; class TagController extends Controller { public function __construct( protected TagRepo $tagRepo ) { } /** * Show a listing of existing tags in the system. */ public function index(Request $request) { $listOptions = SimpleListOptions::fromRequest($request, 'tags')->withSortOptions([ 'name' => trans('common.sort_name'), 'usages' => trans('entities.tags_usages'), ]); $nameFilter = $request->get('name', ''); $tags = $this->tagRepo ->queryWithTotals($listOptions, $nameFilter) ->paginate(50) ->appends(array_filter(array_merge($listOptions->getPaginationAppends(), [ 'name' => $nameFilter, ]))); $this->setPageTitle(trans('entities.tags')); return view('tags.index', [ 'tags' => $tags, 'nameFilter' => $nameFilter, 'listOptions' => $listOptions, ]); } /** * Get tag name suggestions from a given search term. */ public function getNameSuggestions(Request $request) { $searchTerm = $request->get('search', ''); $suggestions = $this->tagRepo->getNameSuggestions($searchTerm); return response()->json($suggestions); } /** * Get tag value suggestions from a given search term. */ public function getValueSuggestions(Request $request) { $searchTerm = $request->get('search', ''); $tagName = $request->get('name', ''); $suggestions = $this->tagRepo->getValueSuggestions($searchTerm, $tagName); return response()->json($suggestions); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Controllers/FavouriteController.php
app/Activity/Controllers/FavouriteController.php
<?php namespace BookStack\Activity\Controllers; use BookStack\Entities\Queries\QueryTopFavourites; use BookStack\Entities\Tools\MixedEntityRequestHelper; use BookStack\Http\Controller; use Illuminate\Http\Request; class FavouriteController extends Controller { public function __construct( protected MixedEntityRequestHelper $entityHelper, ) { } /** * Show a listing of all favourite items for the current user. */ public function index(Request $request, QueryTopFavourites $topFavourites) { $viewCount = 20; $page = intval($request->get('page', 1)); $favourites = $topFavourites->run($viewCount + 1, (($page - 1) * $viewCount)); $hasMoreLink = ($favourites->count() > $viewCount) ? url('/favourites?page=' . ($page + 1)) : null; $this->setPageTitle(trans('entities.my_favourites')); return view('common.detailed-listing-with-more', [ 'title' => trans('entities.my_favourites'), 'entities' => $favourites->slice(0, $viewCount), 'hasMoreLink' => $hasMoreLink, ]); } /** * Add a new item as a favourite. */ public function add(Request $request) { $modelInfo = $this->validate($request, $this->entityHelper->validationRules()); $entity = $this->entityHelper->getVisibleEntityFromRequestData($modelInfo); $entity->favourites()->firstOrCreate([ 'user_id' => user()->id, ]); $this->showSuccessNotification(trans('activities.favourite_add_notification', [ 'name' => $entity->name, ])); return redirect($entity->getUrl()); } /** * Remove an item as a favourite. */ public function remove(Request $request) { $modelInfo = $this->validate($request, $this->entityHelper->validationRules()); $entity = $this->entityHelper->getVisibleEntityFromRequestData($modelInfo); $entity->favourites()->where([ 'user_id' => user()->id, ])->delete(); $this->showSuccessNotification(trans('activities.favourite_remove_notification', [ 'name' => $entity->name, ])); return redirect($entity->getUrl()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/NotificationManager.php
app/Activity/Notifications/NotificationManager.php
<?php namespace BookStack\Activity\Notifications; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\Activity; use BookStack\Activity\Models\Loggable; use BookStack\Activity\Notifications\Handlers\CommentCreationNotificationHandler; use BookStack\Activity\Notifications\Handlers\CommentMentionNotificationHandler; use BookStack\Activity\Notifications\Handlers\NotificationHandler; use BookStack\Activity\Notifications\Handlers\PageCreationNotificationHandler; use BookStack\Activity\Notifications\Handlers\PageUpdateNotificationHandler; use BookStack\Users\Models\User; class NotificationManager { /** * @var class-string<NotificationHandler>[] */ protected array $handlers = []; public function handle(Activity $activity, string|Loggable $detail, User $user): void { $activityType = $activity->type; $handlersToRun = $this->handlers[$activityType] ?? []; foreach ($handlersToRun as $handlerClass) { /** @var NotificationHandler $handler */ $handler = new $handlerClass(); $handler->handle($activity, $detail, $user); } } /** * @param class-string<NotificationHandler> $handlerClass */ public function registerHandler(string $activityType, string $handlerClass): void { if (!isset($this->handlers[$activityType])) { $this->handlers[$activityType] = []; } if (!in_array($handlerClass, $this->handlers[$activityType])) { $this->handlers[$activityType][] = $handlerClass; } } public function loadDefaultHandlers(): void { $this->registerHandler(ActivityType::PAGE_CREATE, PageCreationNotificationHandler::class); $this->registerHandler(ActivityType::PAGE_UPDATE, PageUpdateNotificationHandler::class); $this->registerHandler(ActivityType::COMMENT_CREATE, CommentCreationNotificationHandler::class); $this->registerHandler(ActivityType::COMMENT_CREATE, CommentMentionNotificationHandler::class); $this->registerHandler(ActivityType::COMMENT_UPDATE, CommentMentionNotificationHandler::class); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/Messages/PageUpdateNotification.php
app/Activity/Notifications/Messages/PageUpdateNotification.php
<?php namespace BookStack\Activity\Notifications\Messages; use BookStack\Activity\Notifications\MessageParts\EntityLinkMessageLine; use BookStack\Activity\Notifications\MessageParts\ListMessageLine; use BookStack\Entities\Models\Page; use BookStack\Users\Models\User; use Illuminate\Notifications\Messages\MailMessage; class PageUpdateNotification extends BaseActivityNotification { public function toMail(User $notifiable): MailMessage { /** @var Page $page */ $page = $this->detail; $locale = $notifiable->getLocale(); $listLines = array_filter([ $locale->trans('notifications.detail_page_name') => new EntityLinkMessageLine($page), $locale->trans('notifications.detail_page_path') => $this->buildPagePathLine($page, $notifiable), $locale->trans('notifications.detail_updated_by') => $this->user->name, ]); return $this->newMailMessage($locale) ->subject($locale->trans('notifications.updated_page_subject', ['pageName' => $page->getShortName()])) ->line($locale->trans('notifications.updated_page_intro', ['appName' => setting('app-name')])) ->line(new ListMessageLine($listLines)) ->line($locale->trans('notifications.updated_page_debounce')) ->action($locale->trans('notifications.action_view_page'), $page->getUrl()) ->line($this->buildReasonFooterLine($locale)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/Messages/CommentMentionNotification.php
app/Activity/Notifications/Messages/CommentMentionNotification.php
<?php namespace BookStack\Activity\Notifications\Messages; use BookStack\Activity\Models\Comment; use BookStack\Activity\Notifications\MessageParts\EntityLinkMessageLine; use BookStack\Activity\Notifications\MessageParts\ListMessageLine; use BookStack\Entities\Models\Page; use BookStack\Users\Models\User; use Illuminate\Notifications\Messages\MailMessage; class CommentMentionNotification extends BaseActivityNotification { public function toMail(User $notifiable): MailMessage { /** @var Comment $comment */ $comment = $this->detail; /** @var Page $page */ $page = $comment->entity; $locale = $notifiable->getLocale(); $listLines = array_filter([ $locale->trans('notifications.detail_page_name') => new EntityLinkMessageLine($page), $locale->trans('notifications.detail_page_path') => $this->buildPagePathLine($page, $notifiable), $locale->trans('notifications.detail_commenter') => $this->user->name, $locale->trans('notifications.detail_comment') => strip_tags($comment->html), ]); return $this->newMailMessage($locale) ->subject($locale->trans('notifications.comment_mention_subject', ['pageName' => $page->getShortName()])) ->line($locale->trans('notifications.comment_mention_intro', ['appName' => setting('app-name')])) ->line(new ListMessageLine($listLines)) ->action($locale->trans('notifications.action_view_comment'), $page->getUrl('#comment' . $comment->local_id)) ->line($this->buildReasonFooterLine($locale)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/Messages/BaseActivityNotification.php
app/Activity/Notifications/Messages/BaseActivityNotification.php
<?php namespace BookStack\Activity\Notifications\Messages; use BookStack\Activity\Models\Loggable; use BookStack\Activity\Notifications\MessageParts\EntityPathMessageLine; use BookStack\Activity\Notifications\MessageParts\LinkedMailMessageLine; use BookStack\App\MailNotification; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Permissions\PermissionApplicator; use BookStack\Translation\LocaleDefinition; use BookStack\Users\Models\User; use Illuminate\Bus\Queueable; abstract class BaseActivityNotification extends MailNotification { use Queueable; public function __construct( protected Loggable|string $detail, protected User $user, ) { } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ 'activity_detail' => $this->detail, 'activity_creator' => $this->user, ]; } /** * Build the common reason footer line used in mail messages. */ protected function buildReasonFooterLine(LocaleDefinition $locale): LinkedMailMessageLine { return new LinkedMailMessageLine( url('/my-account/notifications'), $locale->trans('notifications.footer_reason'), $locale->trans('notifications.footer_reason_link'), ); } /** * Build a line which provides the book > chapter path to a page. * Takes into account visibility of these parent items. * Returns null if no path items can be used. */ protected function buildPagePathLine(Page $page, User $notifiable): ?EntityPathMessageLine { $permissions = new PermissionApplicator($notifiable); $path = array_filter([$page->book, $page->chapter], function (?Entity $entity) use ($permissions) { return !is_null($entity) && $permissions->checkOwnableUserAccess($entity, 'view'); }); return empty($path) ? null : new EntityPathMessageLine($path); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/Messages/CommentCreationNotification.php
app/Activity/Notifications/Messages/CommentCreationNotification.php
<?php namespace BookStack\Activity\Notifications\Messages; use BookStack\Activity\Models\Comment; use BookStack\Activity\Notifications\MessageParts\EntityLinkMessageLine; use BookStack\Activity\Notifications\MessageParts\ListMessageLine; use BookStack\Entities\Models\Page; use BookStack\Users\Models\User; use Illuminate\Notifications\Messages\MailMessage; class CommentCreationNotification extends BaseActivityNotification { public function toMail(User $notifiable): MailMessage { /** @var Comment $comment */ $comment = $this->detail; /** @var Page $page */ $page = $comment->entity; $locale = $notifiable->getLocale(); $listLines = array_filter([ $locale->trans('notifications.detail_page_name') => new EntityLinkMessageLine($page), $locale->trans('notifications.detail_page_path') => $this->buildPagePathLine($page, $notifiable), $locale->trans('notifications.detail_commenter') => $this->user->name, $locale->trans('notifications.detail_comment') => strip_tags($comment->html), ]); return $this->newMailMessage($locale) ->subject($locale->trans('notifications.new_comment_subject', ['pageName' => $page->getShortName()])) ->line($locale->trans('notifications.new_comment_intro', ['appName' => setting('app-name')])) ->line(new ListMessageLine($listLines)) ->action($locale->trans('notifications.action_view_comment'), $page->getUrl('#comment' . $comment->local_id)) ->line($this->buildReasonFooterLine($locale)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/Messages/PageCreationNotification.php
app/Activity/Notifications/Messages/PageCreationNotification.php
<?php namespace BookStack\Activity\Notifications\Messages; use BookStack\Activity\Notifications\MessageParts\EntityLinkMessageLine; use BookStack\Activity\Notifications\MessageParts\ListMessageLine; use BookStack\Entities\Models\Page; use BookStack\Users\Models\User; use Illuminate\Notifications\Messages\MailMessage; class PageCreationNotification extends BaseActivityNotification { public function toMail(User $notifiable): MailMessage { /** @var Page $page */ $page = $this->detail; $locale = $notifiable->getLocale(); $listLines = array_filter([ $locale->trans('notifications.detail_page_name') => new EntityLinkMessageLine($page), $locale->trans('notifications.detail_page_path') => $this->buildPagePathLine($page, $notifiable), $locale->trans('notifications.detail_created_by') => $this->user->name, ]); return $this->newMailMessage($locale) ->subject($locale->trans('notifications.new_page_subject', ['pageName' => $page->getShortName()])) ->line($locale->trans('notifications.new_page_intro', ['appName' => setting('app-name')])) ->line(new ListMessageLine($listLines)) ->action($locale->trans('notifications.action_view_page'), $page->getUrl()) ->line($this->buildReasonFooterLine($locale)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/MessageParts/LinkedMailMessageLine.php
app/Activity/Notifications/MessageParts/LinkedMailMessageLine.php
<?php namespace BookStack\Activity\Notifications\MessageParts; use Illuminate\Contracts\Support\Htmlable; use Stringable; /** * A line of text with linked text included, intended for use * in MailMessages. The line should have a ':link' placeholder for * where the link should be inserted within the line. */ class LinkedMailMessageLine implements Htmlable, Stringable { public function __construct( protected string $url, protected string $line, protected string $linkText, ) { } public function toHtml(): string { $link = '<a href="' . e($this->url) . '">' . e($this->linkText) . '</a>'; return str_replace(':link', $link, e($this->line)); } public function __toString(): string { $link = "{$this->linkText} ({$this->url})"; return str_replace(':link', $link, $this->line); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/MessageParts/ListMessageLine.php
app/Activity/Notifications/MessageParts/ListMessageLine.php
<?php namespace BookStack\Activity\Notifications\MessageParts; use Illuminate\Contracts\Support\Htmlable; use Stringable; /** * A bullet point list of content, where the keys of the given list array * are bolded header elements, and the values follow. */ class ListMessageLine implements Htmlable, Stringable { public function __construct( protected array $list ) { } public function toHtml(): string { $list = []; foreach ($this->list as $header => $content) { $list[] = '<strong>' . e($header) . '</strong> ' . e($content); } return implode("<br>\n", $list); } public function __toString(): string { $list = []; foreach ($this->list as $header => $content) { $list[] = $header . ' ' . $content; } return implode("\n", $list); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/MessageParts/EntityPathMessageLine.php
app/Activity/Notifications/MessageParts/EntityPathMessageLine.php
<?php namespace BookStack\Activity\Notifications\MessageParts; use BookStack\Entities\Models\Entity; use Illuminate\Contracts\Support\Htmlable; use Stringable; /** * A link to a specific entity in the system, with the text showing its name. */ class EntityPathMessageLine implements Htmlable, Stringable { /** * @var EntityLinkMessageLine[] */ protected array $entityLinks; public function __construct( protected array $entities ) { $this->entityLinks = array_map(fn (Entity $entity) => new EntityLinkMessageLine($entity, 24), $this->entities); } public function toHtml(): string { $entityHtmls = array_map(fn (EntityLinkMessageLine $line) => $line->toHtml(), $this->entityLinks); return implode(' &gt; ', $entityHtmls); } public function __toString(): string { return implode(' > ', $this->entityLinks); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/MessageParts/EntityLinkMessageLine.php
app/Activity/Notifications/MessageParts/EntityLinkMessageLine.php
<?php namespace BookStack\Activity\Notifications\MessageParts; use BookStack\Entities\Models\Entity; use Illuminate\Contracts\Support\Htmlable; use Stringable; /** * A link to a specific entity in the system, with the text showing its name. */ class EntityLinkMessageLine implements Htmlable, Stringable { public function __construct( protected Entity $entity, protected int $nameLength = 120, ) { } public function toHtml(): string { return '<a href="' . e($this->entity->getUrl()) . '">' . e($this->entity->getShortName($this->nameLength)) . '</a>'; } public function __toString(): string { return "{$this->entity->getShortName($this->nameLength)} ({$this->entity->getUrl()})"; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/Handlers/CommentCreationNotificationHandler.php
app/Activity/Notifications/Handlers/CommentCreationNotificationHandler.php
<?php namespace BookStack\Activity\Notifications\Handlers; use BookStack\Activity\Models\Activity; use BookStack\Activity\Models\Comment; use BookStack\Activity\Models\Loggable; use BookStack\Activity\Notifications\Messages\CommentCreationNotification; use BookStack\Activity\Tools\EntityWatchers; use BookStack\Activity\WatchLevels; use BookStack\Entities\Models\Page; use BookStack\Settings\UserNotificationPreferences; use BookStack\Users\Models\User; class CommentCreationNotificationHandler extends BaseNotificationHandler { public function handle(Activity $activity, Loggable|string $detail, User $user): void { if (!($detail instanceof Comment)) { throw new \InvalidArgumentException("Detail for comment creation notifications must be a comment"); } // Main watchers /** @var Page $page */ $page = $detail->entity; $watchers = new EntityWatchers($page, WatchLevels::COMMENTS); $watcherIds = $watchers->getWatcherUserIds(); // Page owner if user preferences allow if ($page->owned_by && !$watchers->isUserIgnoring($page->owned_by) && $page->ownedBy) { $userNotificationPrefs = new UserNotificationPreferences($page->ownedBy); if ($userNotificationPrefs->notifyOnOwnPageComments()) { $watcherIds[] = $page->owned_by; } } // Parent comment creator if preferences allow $parentComment = $detail->parent()->first(); if ($parentComment && $parentComment->created_by && !$watchers->isUserIgnoring($parentComment->created_by) && $parentComment->createdBy) { $parentCommenterNotificationsPrefs = new UserNotificationPreferences($parentComment->createdBy); if ($parentCommenterNotificationsPrefs->notifyOnCommentReplies()) { $watcherIds[] = $parentComment->created_by; } } $this->sendNotificationToUserIds(CommentCreationNotification::class, $watcherIds, $user, $detail, $page); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/Handlers/NotificationHandler.php
app/Activity/Notifications/Handlers/NotificationHandler.php
<?php namespace BookStack\Activity\Notifications\Handlers; use BookStack\Activity\Models\Activity; use BookStack\Activity\Models\Loggable; use BookStack\Users\Models\User; interface NotificationHandler { /** * Run this handler. * Provides the activity, related activity detail/model * along with the user that triggered the activity. */ public function handle(Activity $activity, string|Loggable $detail, User $user): void; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/Handlers/CommentMentionNotificationHandler.php
app/Activity/Notifications/Handlers/CommentMentionNotificationHandler.php
<?php namespace BookStack\Activity\Notifications\Handlers; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\Activity; use BookStack\Activity\Models\Comment; use BookStack\Activity\Models\Loggable; use BookStack\Activity\Models\MentionHistory; use BookStack\Activity\Notifications\Messages\CommentMentionNotification; use BookStack\Activity\Tools\MentionParser; use BookStack\Entities\Models\Page; use BookStack\Settings\UserNotificationPreferences; use BookStack\Users\Models\User; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Carbon; class CommentMentionNotificationHandler extends BaseNotificationHandler { public function handle(Activity $activity, Loggable|string $detail, User $user): void { if (!($detail instanceof Comment) || !($detail->entity instanceof Page)) { throw new \InvalidArgumentException("Detail for comment mention notifications must be a comment on a page"); } /** @var Page $page */ $page = $detail->entity; $parser = new MentionParser(); $mentionedUserIds = $parser->parseUserIdsFromHtml($detail->html); $realMentionedUsers = User::whereIn('id', $mentionedUserIds)->get(); $receivingNotifications = $realMentionedUsers->filter(function (User $user) { $prefs = new UserNotificationPreferences($user); return $prefs->notifyOnCommentMentions(); }); $receivingNotificationsUserIds = $receivingNotifications->pluck('id')->toArray(); $userMentionsToLog = $realMentionedUsers; // When an edit, we check our history to see if we've already notified the user about this comment before // so that we can filter them out to avoid double notifications. if ($activity->type === ActivityType::COMMENT_UPDATE) { $previouslyNotifiedUserIds = $this->getPreviouslyNotifiedUserIds($detail); $receivingNotificationsUserIds = array_values(array_diff($receivingNotificationsUserIds, $previouslyNotifiedUserIds)); $userMentionsToLog = $userMentionsToLog->filter(function (User $user) use ($previouslyNotifiedUserIds) { return !in_array($user->id, $previouslyNotifiedUserIds); }); } $this->logMentions($userMentionsToLog, $detail, $user); $this->sendNotificationToUserIds(CommentMentionNotification::class, $receivingNotificationsUserIds, $user, $detail, $page); } /** * @param Collection<User> $mentionedUsers */ protected function logMentions(Collection $mentionedUsers, Comment $comment, User $fromUser): void { $mentions = []; $now = Carbon::now(); foreach ($mentionedUsers as $mentionedUser) { $mentions[] = [ 'mentionable_type' => $comment->getMorphClass(), 'mentionable_id' => $comment->id, 'from_user_id' => $fromUser->id, 'to_user_id' => $mentionedUser->id, 'created_at' => $now, 'updated_at' => $now, ]; } MentionHistory::query()->insert($mentions); } protected function getPreviouslyNotifiedUserIds(Comment $comment): array { return MentionHistory::query() ->where('mentionable_id', $comment->id) ->where('mentionable_type', $comment->getMorphClass()) ->pluck('to_user_id') ->toArray(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/Handlers/PageUpdateNotificationHandler.php
app/Activity/Notifications/Handlers/PageUpdateNotificationHandler.php
<?php namespace BookStack\Activity\Notifications\Handlers; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\Activity; use BookStack\Activity\Models\Loggable; use BookStack\Activity\Notifications\Messages\PageUpdateNotification; use BookStack\Activity\Tools\EntityWatchers; use BookStack\Activity\WatchLevels; use BookStack\Entities\Models\Page; use BookStack\Settings\UserNotificationPreferences; use BookStack\Users\Models\User; class PageUpdateNotificationHandler extends BaseNotificationHandler { public function handle(Activity $activity, Loggable|string $detail, User $user): void { if (!($detail instanceof Page)) { throw new \InvalidArgumentException("Detail for page update notifications must be a page"); } // Get the last update from activity /** @var ?Activity $lastUpdate */ $lastUpdate = $detail->activity() ->where('type', '=', ActivityType::PAGE_UPDATE) ->where('id', '!=', $activity->id) ->latest('created_at') ->first(); // Return if the same user has already updated the page in the last 15 mins if ($lastUpdate && $lastUpdate->user_id === $user->id) { if ($lastUpdate->created_at->gt(now()->subMinutes(15))) { return; } } // Get active watchers $watchers = new EntityWatchers($detail, WatchLevels::UPDATES); $watcherIds = $watchers->getWatcherUserIds(); // Add the page owner if preferences allow if ($detail->owned_by && !$watchers->isUserIgnoring($detail->owned_by) && $detail->ownedBy) { $userNotificationPrefs = new UserNotificationPreferences($detail->ownedBy); if ($userNotificationPrefs->notifyOnOwnPageChanges()) { $watcherIds[] = $detail->owned_by; } } $this->sendNotificationToUserIds(PageUpdateNotification::class, $watcherIds, $user, $detail, $detail); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/Handlers/PageCreationNotificationHandler.php
app/Activity/Notifications/Handlers/PageCreationNotificationHandler.php
<?php namespace BookStack\Activity\Notifications\Handlers; use BookStack\Activity\Models\Activity; use BookStack\Activity\Models\Loggable; use BookStack\Activity\Notifications\Messages\PageCreationNotification; use BookStack\Activity\Tools\EntityWatchers; use BookStack\Activity\WatchLevels; use BookStack\Entities\Models\Page; use BookStack\Users\Models\User; class PageCreationNotificationHandler extends BaseNotificationHandler { public function handle(Activity $activity, Loggable|string $detail, User $user): void { if (!($detail instanceof Page)) { throw new \InvalidArgumentException("Detail for page create notifications must be a page"); } $watchers = new EntityWatchers($detail, WatchLevels::NEW); $this->sendNotificationToUserIds(PageCreationNotification::class, $watchers->getWatcherUserIds(), $user, $detail, $detail); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Notifications/Handlers/BaseNotificationHandler.php
app/Activity/Notifications/Handlers/BaseNotificationHandler.php
<?php namespace BookStack\Activity\Notifications\Handlers; use BookStack\Activity\Models\Loggable; use BookStack\Activity\Notifications\Messages\BaseActivityNotification; use BookStack\Entities\Models\Entity; use BookStack\Permissions\Permission; use BookStack\Permissions\PermissionApplicator; use BookStack\Users\Models\User; use Illuminate\Support\Facades\Log; abstract class BaseNotificationHandler implements NotificationHandler { /** * @param class-string<BaseActivityNotification> $notification * @param int[] $userIds */ protected function sendNotificationToUserIds(string $notification, array $userIds, User $initiator, string|Loggable $detail, Entity $relatedModel): void { $users = User::query()->whereIn('id', array_unique($userIds))->get(); /** @var User $user */ foreach ($users as $user) { // Prevent sending to the user that initiated the activity if ($user->id === $initiator->id) { continue; } // Prevent sending of the user does not have notification permissions if (!$user->can(Permission::ReceiveNotifications)) { continue; } // Prevent sending if the user does not have access to the related content $permissions = new PermissionApplicator($user); if (!$permissions->checkOwnableUserAccess($relatedModel, 'view')) { continue; } // Send the notification try { $user->notify(new $notification($detail, $initiator)); } catch (\Exception $exception) { Log::error("Failed to send email notification to user [id:{$user->id}] with error: {$exception->getMessage()}"); } } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Models/Favourite.php
app/Activity/Models/Favourite.php
<?php namespace BookStack\Activity\Models; use BookStack\App\Model; use BookStack\Permissions\Models\JointPermission; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphTo; class Favourite extends Model { use HasFactory; protected $fillable = ['user_id']; /** * Get the related model that can be favourited. */ public function favouritable(): MorphTo { return $this->morphTo(); } public function jointPermissions(): HasMany { return $this->hasMany(JointPermission::class, 'entity_id', 'favouritable_id') ->whereColumn('favourites.favouritable_type', '=', 'joint_permissions.entity_type'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Models/Tag.php
app/Activity/Models/Tag.php
<?php namespace BookStack\Activity\Models; use BookStack\App\Model; use BookStack\Permissions\Models\JointPermission; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphTo; /** * @property int $id * @property string $name * @property string $value * @property int $entity_id * @property string $entity_type * @property int $order */ class Tag extends Model { use HasFactory; protected $fillable = ['name', 'value', 'order']; protected $hidden = ['id', 'entity_id', 'entity_type', 'created_at', 'updated_at']; /** * Get the entity that this tag belongs to. */ public function entity(): MorphTo { return $this->morphTo('entity'); } public function jointPermissions(): HasMany { return $this->hasMany(JointPermission::class, 'entity_id', 'entity_id') ->whereColumn('tags.entity_type', '=', 'joint_permissions.entity_type'); } /** * Get a full URL to start a tag name search for this tag name. */ public function nameUrl(): string { return url('/search?term=%5B' . urlencode($this->name) . '%5D'); } /** * Get a full URL to start a tag name and value search for this tag's values. */ public function valueUrl(): string { return url('/search?term=%5B' . urlencode($this->name) . '%3D' . urlencode($this->value) . '%5D'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Models/Webhook.php
app/Activity/Models/Webhook.php
<?php namespace BookStack\Activity\Models; use BookStack\Activity\ActivityType; use Carbon\Carbon; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; /** * @property int $id * @property string $name * @property string $endpoint * @property Collection $trackedEvents * @property bool $active * @property int $timeout * @property string $last_error * @property Carbon $last_called_at * @property Carbon $last_errored_at */ class Webhook extends Model implements Loggable { use HasFactory; protected $fillable = ['name', 'endpoint', 'timeout']; protected $casts = [ 'last_called_at' => 'datetime', 'last_errored_at' => 'datetime', ]; /** * Define the tracked event relation a webhook. */ public function trackedEvents(): HasMany { return $this->hasMany(WebhookTrackedEvent::class); } /** * Update the tracked events for a webhook from the given list of event types. */ public function updateTrackedEvents(array $events): void { $this->trackedEvents()->delete(); $eventsToStore = array_intersect($events, array_values(ActivityType::all())); if (in_array('all', $events)) { $eventsToStore = ['all']; } $trackedEvents = []; foreach ($eventsToStore as $event) { $trackedEvents[] = new WebhookTrackedEvent(['event' => $event]); } $this->trackedEvents()->saveMany($trackedEvents); } /** * Check if this webhook tracks the given event. */ public function tracksEvent(string $event): bool { return $this->trackedEvents->pluck('event')->contains($event); } /** * Get a URL for this webhook within the settings interface. */ public function getUrl(string $path = ''): string { return url('/settings/webhooks/' . $this->id . '/' . ltrim($path, '/')); } /** * Get the string descriptor for this item. */ public function logDescriptor(): string { return "({$this->id}) {$this->name}"; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Models/Comment.php
app/Activity/Models/Comment.php
<?php namespace BookStack\Activity\Models; use BookStack\App\Model; use BookStack\Permissions\Models\JointPermission; use BookStack\Permissions\PermissionApplicator; use BookStack\Users\Models\HasCreatorAndUpdater; use BookStack\Users\Models\OwnableInterface; use BookStack\Util\HtmlContentFilter; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphTo; /** * @property int $id * @property string $html * @property int|null $parent_id - Relates to local_id, not id * @property int $local_id * @property string $commentable_type * @property int $commentable_id * @property string $content_ref * @property bool $archived */ class Comment extends Model implements Loggable, OwnableInterface { use HasFactory; use HasCreatorAndUpdater; protected $fillable = ['parent_id']; protected $hidden = ['html']; protected $casts = [ 'archived' => 'boolean', ]; /** * Get the entity that this comment belongs to. */ public function entity(): MorphTo { // We specifically define null here to avoid the different name (commentable) // being used by Laravel eager loading instead of the method name, which it was doing // in some scenarios like when deserialized when going through the queue system. // So we instead specify the type and id column names to use. // Related to: // https://github.com/laravel/framework/pull/24815 // https://github.com/laravel/framework/issues/27342 // https://github.com/laravel/framework/issues/47953 // (and probably more) // Ultimately, we could just align the method name to 'commentable' but that would be a potential // breaking change and not really worthwhile in a patch due to the risk of creating extra problems. return $this->morphTo(null, 'commentable_type', 'commentable_id'); } /** * Get the parent comment this is in reply to (if existing). * @return BelongsTo<Comment, $this> */ public function parent(): BelongsTo { return $this->belongsTo(Comment::class, 'parent_id', 'local_id', 'parent') ->where('commentable_type', '=', $this->commentable_type) ->where('commentable_id', '=', $this->commentable_id); } /** * Check if a comment has been updated since creation. */ public function isUpdated(): bool { return $this->updated_at->timestamp > $this->created_at->timestamp; } public function logDescriptor(): string { return "Comment #{$this->local_id} (ID: {$this->id}) for {$this->commentable_type} (ID: {$this->commentable_id})"; } public function safeHtml(): string { return HtmlContentFilter::removeScriptsFromHtmlString($this->html ?? ''); } public function jointPermissions(): HasMany { return $this->hasMany(JointPermission::class, 'entity_id', 'commentable_id') ->whereColumn('joint_permissions.entity_type', '=', 'comments.commentable_type'); } /** * Scope the query to just the comments visible to the user based upon the * user visibility of what has been commented on. */ public function scopeVisible(Builder $query): Builder { return app()->make(PermissionApplicator::class) ->restrictEntityRelationQuery($query, 'comments', 'commentable_id', 'commentable_type'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Models/Loggable.php
app/Activity/Models/Loggable.php
<?php namespace BookStack\Activity\Models; interface Loggable { /** * Get the string descriptor for this item. */ public function logDescriptor(): string; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Models/MentionHistory.php
app/Activity/Models/MentionHistory.php
<?php namespace BookStack\Activity\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Carbon; /** * @property int $id * @property string $mentionable_type * @property int $mentionable_id * @property int $from_user_id * @property int $to_user_id * @property Carbon $created_at * @property Carbon $updated_at */ class MentionHistory extends Model { protected $table = 'mention_history'; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Models/Activity.php
app/Activity/Models/Activity.php
<?php namespace BookStack\Activity\Models; use BookStack\App\Model; use BookStack\Entities\Models\Entity; use BookStack\Permissions\Models\JointPermission; use BookStack\Users\Models\User; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Support\Carbon; use Illuminate\Support\Str; /** * @property string $type * @property User $user * @property Entity $loggable * @property string $detail * @property string $loggable_type * @property int $loggable_id * @property int $user_id * @property Carbon $created_at */ class Activity extends Model { use HasFactory; /** * Get the loggable model related to this activity. * Currently only used for entities (previously entity_[id/type] columns). * Could be used for others but will need an audit of uses where assumed * to be entities. */ public function loggable(): MorphTo { return $this->morphTo('loggable'); } /** * Get the user this activity relates to. */ public function user(): BelongsTo { return $this->belongsTo(User::class); } public function jointPermissions(): HasMany { return $this->hasMany(JointPermission::class, 'entity_id', 'loggable_id') ->whereColumn('activities.loggable_type', '=', 'joint_permissions.entity_type'); } /** * Returns text from the language files, Looks up by using the activity key. */ public function getText(): string { return trans('activities.' . $this->type); } /** * Check if this activity is intended to be for an entity. */ public function isForEntity(): bool { return Str::startsWith($this->type, [ 'page_', 'chapter_', 'book_', 'bookshelf_', ]); } /** * Checks if another Activity matches the general information of another. */ public function isSimilarTo(self $activityB): bool { return [$this->type, $this->loggable_type, $this->loggable_id] === [$activityB->type, $activityB->loggable_type, $activityB->loggable_id]; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Models/Viewable.php
app/Activity/Models/Viewable.php
<?php namespace BookStack\Activity\Models; use Illuminate\Database\Eloquent\Relations\MorphMany; interface Viewable { /** * Get all view instances for this viewable model. */ public function views(): MorphMany; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Models/WebhookTrackedEvent.php
app/Activity/Models/WebhookTrackedEvent.php
<?php namespace BookStack\Activity\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; /** * @property int $id * @property int $webhook_id * @property string $event */ class WebhookTrackedEvent extends Model { use HasFactory; protected $fillable = ['event']; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Models/Watch.php
app/Activity/Models/Watch.php
<?php namespace BookStack\Activity\Models; use BookStack\Activity\WatchLevels; use BookStack\Permissions\Models\JointPermission; use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphTo; /** * @property int $id * @property int $user_id * @property int $watchable_id * @property string $watchable_type * @property int $level * @property Carbon $created_at * @property Carbon $updated_at */ class Watch extends Model { use HasFactory; protected $guarded = []; public function watchable(): MorphTo { return $this->morphTo(); } public function jointPermissions(): HasMany { return $this->hasMany(JointPermission::class, 'entity_id', 'watchable_id') ->whereColumn('watches.watchable_type', '=', 'joint_permissions.entity_type'); } public function getLevelName(): string { return WatchLevels::levelValueToName($this->level); } public function ignoring(): bool { return $this->level === WatchLevels::IGNORE; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Models/View.php
app/Activity/Models/View.php
<?php namespace BookStack\Activity\Models; use BookStack\App\Model; use BookStack\Permissions\Models\JointPermission; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphTo; /** * Class View * Views are stored per-item per-person within the database. * They can be used to find popular items or recently viewed items * at a per-person level. They do not record every view instance as an * activity. Only the latest and original view times could be recognised. * * @property int $views * @property int $user_id */ class View extends Model { protected $fillable = ['user_id', 'views']; /** * Get all owning viewable models. */ public function viewable(): MorphTo { return $this->morphTo(); } public function jointPermissions(): HasMany { return $this->hasMany(JointPermission::class, 'entity_id', 'viewable_id') ->whereColumn('views.viewable_type', '=', 'joint_permissions.entity_type'); } /** * Increment the current user's view count for the given viewable model. */ public static function incrementFor(Viewable $viewable): int { $user = user(); if ($user->isGuest()) { return 0; } /** @var View $view */ $view = $viewable->views()->firstOrNew([ 'user_id' => $user->id, ], ['views' => 0]); $view->forceFill(['views' => $view->views + 1])->save(); return $view->views; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Models/Favouritable.php
app/Activity/Models/Favouritable.php
<?php namespace BookStack\Activity\Models; use Illuminate\Database\Eloquent\Relations\MorphMany; interface Favouritable { /** * Get the related favourite instances. */ public function favourites(): MorphMany; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Tools/CommentTree.php
app/Activity/Tools/CommentTree.php
<?php namespace BookStack\Activity\Tools; use BookStack\Activity\Models\Comment; use BookStack\Entities\Models\Page; use BookStack\Permissions\Permission; class CommentTree { /** * The built nested tree structure array. * @var CommentTreeNode[] */ protected array $tree; /** * A linear array of loaded comments. * @var Comment[] */ protected array $comments; public function __construct( protected Page $page ) { $this->comments = $this->loadComments(); $this->tree = $this->createTree($this->comments); } public function enabled(): bool { return !setting('app-disable-comments'); } public function empty(): bool { return count($this->getActive()) === 0; } public function count(): int { return count($this->comments); } public function getActive(): array { return array_values(array_filter($this->tree, fn (CommentTreeNode $node) => !$node->comment->archived)); } public function activeThreadCount(): int { return count($this->getActive()); } public function getArchived(): array { return array_values(array_filter($this->tree, fn (CommentTreeNode $node) => $node->comment->archived)); } public function archivedThreadCount(): int { return count($this->getArchived()); } public function getCommentNodeForId(int $commentId): ?CommentTreeNode { foreach ($this->tree as $node) { if ($node->comment->id === $commentId) { return $node; } } return null; } public function canUpdateAny(): bool { foreach ($this->comments as $comment) { if (userCan(Permission::CommentUpdate, $comment)) { return true; } } return false; } public function loadVisibleHtml(): void { foreach ($this->comments as $comment) { $comment->setAttribute('html', $comment->safeHtml()); $comment->makeVisible('html'); } } /** * @param Comment[] $comments * @return CommentTreeNode[] */ protected function createTree(array $comments): array { $byId = []; foreach ($comments as $comment) { $byId[$comment->local_id] = $comment; } $childMap = []; foreach ($comments as $comment) { $parent = $comment->parent_id; if (is_null($parent) || !isset($byId[$parent])) { $parent = 0; } if (!isset($childMap[$parent])) { $childMap[$parent] = []; } $childMap[$parent][] = $comment->local_id; } $tree = []; foreach ($childMap[0] ?? [] as $childId) { $tree[] = $this->createTreeNodeForId($childId, 0, $byId, $childMap); } return $tree; } protected function createTreeNodeForId(int $id, int $depth, array &$byId, array &$childMap): CommentTreeNode { $childIds = $childMap[$id] ?? []; $children = []; foreach ($childIds as $childId) { $children[] = $this->createTreeNodeForId($childId, $depth + 1, $byId, $childMap); } return new CommentTreeNode($byId[$id], $depth, $children); } /** * @return Comment[] */ protected function loadComments(): array { if (!$this->enabled()) { return []; } return $this->page->comments() ->with('createdBy') ->get() ->all(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Tools/MentionParser.php
app/Activity/Tools/MentionParser.php
<?php namespace BookStack\Activity\Tools; use BookStack\Util\HtmlDocument; use DOMElement; class MentionParser { public function parseUserIdsFromHtml(string $html): array { $doc = new HtmlDocument($html); $ids = []; $mentionLinks = $doc->queryXPath('//a[@data-mention-user-id]'); foreach ($mentionLinks as $link) { if ($link instanceof DOMElement) { $id = intval($link->getAttribute('data-mention-user-id')); if ($id > 0) { $ids[] = $id; } } } return array_values(array_unique($ids)); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Tools/WatchedParentDetails.php
app/Activity/Tools/WatchedParentDetails.php
<?php namespace BookStack\Activity\Tools; use BookStack\Activity\WatchLevels; class WatchedParentDetails { public function __construct( public string $type, public int $level, ) { } public function ignoring(): bool { return $this->level === WatchLevels::IGNORE; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Tools/WebhookFormatter.php
app/Activity/Tools/WebhookFormatter.php
<?php namespace BookStack\Activity\Tools; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\Loggable; use BookStack\Activity\Models\Webhook; use BookStack\App\Model; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Users\Models\User; use Illuminate\Support\Carbon; class WebhookFormatter { protected Webhook $webhook; protected string $event; protected User $initiator; protected int $initiatedTime; protected string|Loggable $detail; /** * @var array{condition: callable(string, Model):bool, format: callable(Model):void}[] */ protected $modelFormatters = []; public function __construct(string $event, Webhook $webhook, string|Loggable $detail, User $initiator, int $initiatedTime) { $this->webhook = $webhook; $this->event = $event; $this->initiator = $initiator; $this->initiatedTime = $initiatedTime; $this->detail = is_object($detail) ? clone $detail : $detail; } public function format(): array { $data = [ 'event' => $this->event, 'text' => $this->formatText(), 'triggered_at' => Carbon::createFromTimestampUTC($this->initiatedTime)->toISOString(), 'triggered_by' => $this->initiator->attributesToArray(), 'triggered_by_profile_url' => $this->initiator->getProfileUrl(), 'webhook_id' => $this->webhook->id, 'webhook_name' => $this->webhook->name, ]; if (method_exists($this->detail, 'getUrl')) { $data['url'] = $this->detail->getUrl(); } if ($this->detail instanceof Model) { $data['related_item'] = $this->formatModel($this->detail); } return $data; } /** * @param callable(string, Model):bool $condition * @param callable(Model):void $format */ public function addModelFormatter(callable $condition, callable $format): void { $this->modelFormatters[] = [ 'condition' => $condition, 'format' => $format, ]; } public function addDefaultModelFormatters(): void { // Load entity owner, creator, updater details $this->addModelFormatter( fn ($event, $model) => ($model instanceof Entity), fn ($model) => $model->load(['ownedBy', 'createdBy', 'updatedBy']) ); // Load revision detail for page update and create events $this->addModelFormatter( fn ($event, $model) => ($model instanceof Page && ($event === ActivityType::PAGE_CREATE || $event === ActivityType::PAGE_UPDATE)), fn ($model) => $model->load('currentRevision') ); } protected function formatModel(Model $model): array { $model->unsetRelations(); foreach ($this->modelFormatters as $formatter) { if ($formatter['condition']($this->event, $model)) { $formatter['format']($model); } } return $model->toArray(); } protected function formatText(): string { $textParts = [ $this->initiator->name, trans('activities.' . $this->event), ]; if ($this->detail instanceof Entity) { $textParts[] = '"' . $this->detail->name . '"'; } return implode(' ', $textParts); } public static function getDefault(string $event, Webhook $webhook, $detail, User $initiator, int $initiatedTime): self { $instance = new self($event, $webhook, $detail, $initiator, $initiatedTime); $instance->addDefaultModelFormatters(); return $instance; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Tools/IpFormatter.php
app/Activity/Tools/IpFormatter.php
<?php namespace BookStack\Activity\Tools; class IpFormatter { protected string $ip; protected int $precision; public function __construct(string $ip, int $precision) { $this->ip = trim($ip); $this->precision = max(0, min($precision, 4)); } public function format(): string { if (empty($this->ip) || $this->precision === 4) { return $this->ip; } return $this->isIpv6() ? $this->maskIpv6() : $this->maskIpv4(); } protected function maskIpv4(): string { $exploded = $this->explodeAndExpandIp('.', 4); $maskGroupCount = min(4 - $this->precision, count($exploded)); for ($i = 0; $i < $maskGroupCount; $i++) { $exploded[3 - $i] = 'x'; } return implode('.', $exploded); } protected function maskIpv6(): string { $exploded = $this->explodeAndExpandIp(':', 8); $maskGroupCount = min(8 - ($this->precision * 2), count($exploded)); for ($i = 0; $i < $maskGroupCount; $i++) { $exploded[7 - $i] = 'x'; } return implode(':', $exploded); } protected function isIpv6(): bool { return strpos($this->ip, ':') !== false; } protected function explodeAndExpandIp(string $separator, int $targetLength): array { $exploded = explode($separator, $this->ip); while (count($exploded) < $targetLength) { $emptyIndex = array_search('', $exploded) ?: count($exploded) - 1; array_splice($exploded, $emptyIndex, 0, '0'); } $emptyIndex = array_search('', $exploded); if ($emptyIndex !== false) { $exploded[$emptyIndex] = '0'; } return $exploded; } public static function fromCurrentRequest(): self { $ip = request()->ip() ?? ''; if (config('app.env') === 'demo') { $ip = '127.0.0.1'; } return new self($ip, config('app.ip_address_precision')); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Tools/UserEntityWatchOptions.php
app/Activity/Tools/UserEntityWatchOptions.php
<?php namespace BookStack\Activity\Tools; use BookStack\Activity\Models\Watch; use BookStack\Activity\WatchLevels; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Permissions\Permission; use BookStack\Users\Models\User; use Illuminate\Database\Eloquent\Builder; class UserEntityWatchOptions { protected ?array $watchMap = null; public function __construct( protected User $user, protected Entity $entity, ) { } public function canWatch(): bool { return $this->user->can(Permission::ReceiveNotifications) && !$this->user->isGuest(); } public function getWatchLevel(): string { return WatchLevels::levelValueToName($this->getWatchLevelValue()); } public function isWatching(): bool { return $this->getWatchLevelValue() !== WatchLevels::DEFAULT; } public function getWatchedParent(): ?WatchedParentDetails { $watchMap = $this->getWatchMap(); unset($watchMap[$this->entity->getMorphClass()]); if (isset($watchMap['chapter'])) { return new WatchedParentDetails('chapter', $watchMap['chapter']); } if (isset($watchMap['book'])) { return new WatchedParentDetails('book', $watchMap['book']); } return null; } public function updateLevelByName(string $level): void { $levelValue = WatchLevels::levelNameToValue($level); $this->updateLevelByValue($levelValue); } public function updateLevelByValue(int $level): void { if ($level < 0) { $this->remove(); return; } $this->updateLevel($level); } public function getWatchMap(): array { if (!is_null($this->watchMap)) { return $this->watchMap; } $entities = [$this->entity]; if ($this->entity instanceof BookChild) { $entities[] = $this->entity->book; } if ($this->entity instanceof Page && $this->entity->chapter) { $entities[] = $this->entity->chapter; } $query = Watch::query() ->where('user_id', '=', $this->user->id) ->where(function (Builder $subQuery) use ($entities) { foreach ($entities as $entity) { $subQuery->orWhere(function (Builder $whereQuery) use ($entity) { $whereQuery->where('watchable_type', '=', $entity->getMorphClass()) ->where('watchable_id', '=', $entity->id); }); } }); $this->watchMap = $query->get(['watchable_type', 'level']) ->pluck('level', 'watchable_type') ->toArray(); return $this->watchMap; } protected function getWatchLevelValue() { return $this->getWatchMap()[$this->entity->getMorphClass()] ?? WatchLevels::DEFAULT; } protected function updateLevel(int $levelValue): void { Watch::query()->updateOrCreate([ 'watchable_id' => $this->entity->id, 'watchable_type' => $this->entity->getMorphClass(), 'user_id' => $this->user->id, ], [ 'level' => $levelValue, ]); $this->watchMap = null; } protected function remove(): void { $this->entityQuery()->delete(); $this->watchMap = null; } protected function entityQuery(): Builder { return Watch::query()->where('watchable_id', '=', $this->entity->id) ->where('watchable_type', '=', $this->entity->getMorphClass()) ->where('user_id', '=', $this->user->id); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Tools/TagClassGenerator.php
app/Activity/Tools/TagClassGenerator.php
<?php namespace BookStack\Activity\Tools; use BookStack\Activity\Models\Tag; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Permissions\Permission; class TagClassGenerator { public function __construct( protected Entity $entity ) { } /** * @return string[] */ public function generate(): array { $classes = []; $tags = $this->entity->tags->all(); foreach ($tags as $tag) { array_push($classes, ...$this->generateClassesForTag($tag)); } if ($this->entity instanceof BookChild && userCan(Permission::BookView, $this->entity->book)) { $bookTags = $this->entity->book->tags; foreach ($bookTags as $bookTag) { array_push($classes, ...$this->generateClassesForTag($bookTag, 'book-')); } } if ($this->entity instanceof Page && $this->entity->chapter && userCan(Permission::ChapterView, $this->entity->chapter)) { $chapterTags = $this->entity->chapter->tags; foreach ($chapterTags as $chapterTag) { array_push($classes, ...$this->generateClassesForTag($chapterTag, 'chapter-')); } } return array_unique($classes); } public function generateAsString(): string { return implode(' ', $this->generate()); } /** * @return string[] */ protected function generateClassesForTag(Tag $tag, string $prefix = ''): array { $classes = []; $name = $this->normalizeTagClassString($tag->name); $value = $this->normalizeTagClassString($tag->value); $classes[] = "{$prefix}tag-name-{$name}"; if ($value) { $classes[] = "{$prefix}tag-value-{$value}"; $classes[] = "{$prefix}tag-pair-{$name}-{$value}"; } return $classes; } protected function normalizeTagClassString(string $value): string { $value = str_replace(' ', '', strtolower($value)); $value = str_replace('-', '', strtolower($value)); return $value; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Tools/CommentTreeNode.php
app/Activity/Tools/CommentTreeNode.php
<?php namespace BookStack\Activity\Tools; use BookStack\Activity\Models\Comment; class CommentTreeNode { public Comment $comment; public int $depth; /** * @var CommentTreeNode[] */ public array $children; public function __construct(Comment $comment, int $depth, array $children) { $this->comment = $comment; $this->depth = $depth; $this->children = $children; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Tools/ActivityLogger.php
app/Activity/Tools/ActivityLogger.php
<?php namespace BookStack\Activity\Tools; use BookStack\Activity\DispatchWebhookJob; use BookStack\Activity\Models\Activity; use BookStack\Activity\Models\Loggable; use BookStack\Activity\Models\Webhook; use BookStack\Activity\Notifications\NotificationManager; use BookStack\Entities\Models\Entity; use BookStack\Facades\Theme; use BookStack\Theming\ThemeEvents; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Facades\Log; class ActivityLogger { public function __construct( protected NotificationManager $notifications ) { $this->notifications->loadDefaultHandlers(); } /** * Add a generic activity event to the database. */ public function add(string $type, string|Loggable $detail = ''): void { $detailToStore = ($detail instanceof Loggable) ? $detail->logDescriptor() : $detail; $activity = $this->newActivityForUser($type); $activity->detail = $detailToStore; if ($detail instanceof Entity) { $activity->loggable_id = $detail->id; $activity->loggable_type = $detail->getMorphClass(); } $activity->save(); $this->setNotification($type); $this->dispatchWebhooks($type, $detail); $this->notifications->handle($activity, $detail, user()); Theme::dispatch(ThemeEvents::ACTIVITY_LOGGED, $type, $detail); } /** * Get a new activity instance for the current user. */ protected function newActivityForUser(string $type): Activity { return (new Activity())->forceFill([ 'type' => strtolower($type), 'user_id' => user()->id, 'ip' => IpFormatter::fromCurrentRequest()->format(), ]); } /** * Removes the entity attachment from each of its activities * and instead uses the 'extra' field with the entities name. * Used when an entity is deleted. */ public function removeEntity(Entity $entity): void { $entity->activity()->update([ 'detail' => $entity->name, 'loggable_id' => null, 'loggable_type' => null, ]); } /** * Flashes a notification message to the session if an appropriate message is available. */ protected function setNotification(string $type): void { $notificationTextKey = 'activities.' . $type . '_notification'; if (trans()->has($notificationTextKey)) { $message = trans($notificationTextKey); session()->flash('success', $message); } } protected function dispatchWebhooks(string $type, string|Loggable $detail): void { $webhooks = Webhook::query() ->whereHas('trackedEvents', function (Builder $query) use ($type) { $query->where('event', '=', $type) ->orWhere('event', '=', 'all'); }) ->where('active', '=', true) ->get(); foreach ($webhooks as $webhook) { dispatch(new DispatchWebhookJob($webhook, $type, $detail)); } } /** * Log out a failed login attempt, Providing the given username * as part of the message if the '%u' string is used. */ public function logFailedLogin(string $username): void { $message = config('logging.failed_login.message'); if (!$message) { return; } $message = str_replace('%u', $username, $message); $channel = config('logging.failed_login.channel'); Log::channel($channel)->warning($message); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Tools/EntityWatchers.php
app/Activity/Tools/EntityWatchers.php
<?php namespace BookStack\Activity\Tools; use BookStack\Activity\Models\Watch; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use Illuminate\Database\Eloquent\Builder; class EntityWatchers { /** * @var int[] */ protected array $watchers = []; /** * @var int[] */ protected array $ignorers = []; public function __construct( protected Entity $entity, protected int $watchLevel, ) { $this->build(); } public function getWatcherUserIds(): array { return $this->watchers; } public function isUserIgnoring(int $userId): bool { return in_array($userId, $this->ignorers); } protected function build(): void { $watches = $this->getRelevantWatches(); // Sort before de-duping, so that the order looped below follows book -> chapter -> page ordering usort($watches, function (Watch $watchA, Watch $watchB) { $entityTypeDiff = $watchA->watchable_type <=> $watchB->watchable_type; return $entityTypeDiff === 0 ? ($watchA->user_id <=> $watchB->user_id) : $entityTypeDiff; }); // De-dupe by user id to get their most relevant level $levelByUserId = []; foreach ($watches as $watch) { $levelByUserId[$watch->user_id] = $watch->level; } // Populate the class arrays $this->watchers = array_keys(array_filter($levelByUserId, fn(int $level) => $level >= $this->watchLevel)); $this->ignorers = array_keys(array_filter($levelByUserId, fn(int $level) => $level === 0)); } /** * @return Watch[] */ protected function getRelevantWatches(): array { /** @var Entity[] $entitiesInvolved */ $entitiesInvolved = array_filter([ $this->entity, $this->entity instanceof BookChild ? $this->entity->book : null, $this->entity instanceof Page ? $this->entity->chapter : null, ]); $query = Watch::query()->where(function (Builder $query) use ($entitiesInvolved) { foreach ($entitiesInvolved as $entity) { $query->orWhere(function (Builder $query) use ($entity) { $query->where('watchable_type', '=', $entity->getMorphClass()) ->where('watchable_id', '=', $entity->id); }); } }); return $query->get([ 'level', 'watchable_id', 'watchable_type', 'user_id' ])->all(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Activity/Queries/WebhooksAllPaginatedAndSorted.php
app/Activity/Queries/WebhooksAllPaginatedAndSorted.php
<?php namespace BookStack\Activity\Queries; use BookStack\Activity\Models\Webhook; use BookStack\Util\SimpleListOptions; use Illuminate\Pagination\LengthAwarePaginator; /** * Get all the webhooks in the system in a paginated format. */ class WebhooksAllPaginatedAndSorted { public function run(int $count, SimpleListOptions $listOptions): LengthAwarePaginator { $query = Webhook::query()->select(['*']) ->withCount(['trackedEvents']) ->orderBy($listOptions->getSort(), $listOptions->getOrder()); if ($listOptions->getSearch()) { $term = '%' . $listOptions->getSearch() . '%'; $query->where(function ($query) use ($term) { $query->where('name', 'like', $term) ->orWhere('endpoint', 'like', $term); }); } return $query->paginate($count); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/ImageResizer.php
app/Uploads/ImageResizer.php
<?php namespace BookStack\Uploads; use BookStack\Exceptions\ImageUploadException; use Exception; use GuzzleHttp\Psr7\Utils; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; use Intervention\Image\Decoders\BinaryImageDecoder; use Intervention\Image\Drivers\Gd\Decoders\NativeObjectDecoder; use Intervention\Image\Drivers\Gd\Driver; use Intervention\Image\Encoders\AutoEncoder; use Intervention\Image\Encoders\PngEncoder; use Intervention\Image\Interfaces\ImageInterface as InterventionImage; use Intervention\Image\ImageManager; use Intervention\Image\Origin; class ImageResizer { protected const THUMBNAIL_CACHE_TIME = 604_800; // 1 week public function __construct( protected ImageStorage $storage, ) { } /** * Load gallery thumbnails for a set of images. * @param iterable<Image> $images */ public function loadGalleryThumbnailsForMany(iterable $images, bool $shouldCreate = false): void { foreach ($images as $image) { $this->loadGalleryThumbnailsForImage($image, $shouldCreate); } } /** * Load gallery thumbnails into the given image instance. */ public function loadGalleryThumbnailsForImage(Image $image, bool $shouldCreate): void { $thumbs = ['gallery' => null, 'display' => null]; try { $thumbs['gallery'] = $this->resizeToThumbnailUrl($image, 150, 150, false, $shouldCreate); $thumbs['display'] = $this->resizeToThumbnailUrl($image, 1680, null, true, $shouldCreate); } catch (Exception $exception) { // Prevent thumbnail errors from stopping execution } $image->setAttribute('thumbs', $thumbs); } /** * Get the thumbnail for an image. * If $keepRatio is true, only the width will be used. * Checks the cache then storage to avoid creating / accessing the filesystem on every check. * * @throws Exception */ public function resizeToThumbnailUrl( Image $image, ?int $width, ?int $height, bool $keepRatio = false, bool $shouldCreate = false ): ?string { // Do not resize GIF images where we're not cropping if ($keepRatio && $this->isGif($image)) { return $this->storage->getPublicUrl($image->path); } $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/'; $imagePath = $image->path; $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath); $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath; // Return path if in cache $cachedThumbPath = Cache::get($thumbCacheKey); if ($cachedThumbPath && !$shouldCreate) { return $this->storage->getPublicUrl($cachedThumbPath); } // If a thumbnail has already been generated, serve that and cache path $disk = $this->storage->getDisk($image->type); if (!$shouldCreate && $disk->exists($thumbFilePath)) { Cache::put($thumbCacheKey, $thumbFilePath, static::THUMBNAIL_CACHE_TIME); return $this->storage->getPublicUrl($thumbFilePath); } $imageData = $disk->get($imagePath); // Do not resize animated images where we're not cropping if ($keepRatio && $this->isAnimated($image, $imageData)) { Cache::put($thumbCacheKey, $image->path, static::THUMBNAIL_CACHE_TIME); return $this->storage->getPublicUrl($image->path); } // If not in cache and thumbnail does not exist, generate thumb and cache path $thumbData = $this->resizeImageData($imageData, $width, $height, $keepRatio, $this->getExtension($image)); $disk->put($thumbFilePath, $thumbData, true); Cache::put($thumbCacheKey, $thumbFilePath, static::THUMBNAIL_CACHE_TIME); return $this->storage->getPublicUrl($thumbFilePath); } /** * Resize the image of given data to the specified size and return the new image data. * Format will remain the same as the input format, unless specified. * * @throws ImageUploadException */ public function resizeImageData( string $imageData, ?int $width, ?int $height, bool $keepRatio, ?string $format = null, ): string { try { $thumb = $this->interventionFromImageData($imageData, $format); } catch (Exception $e) { Log::error('Failed to resize image with error:' . $e->getMessage()); throw new ImageUploadException(trans('errors.cannot_create_thumbs')); } $this->orientImageToOriginalExif($thumb, $imageData); if ($keepRatio) { $thumb->scaleDown($width, $height); } else { $thumb->cover($width, $height); } $encoder = match ($format) { 'png' => new PngEncoder(), default => new AutoEncoder(), }; $thumbData = (string) $thumb->encode($encoder); // Use original image data if we're keeping the ratio // and the resizing does not save any space. if ($keepRatio && strlen($thumbData) > strlen($imageData)) { return $imageData; } return $thumbData; } /** * Create an intervention image instance from the given image data. * Performs some manual library usage to ensure the image is specifically loaded * from given binary data instead of data being misinterpreted. */ protected function interventionFromImageData(string $imageData, ?string $fileType): InterventionImage { if (!extension_loaded('gd')) { throw new ImageUploadException('The PHP "gd" extension is required to resize images, but is missing.'); } $manager = new ImageManager( new Driver(), autoOrientation: false, ); // Ensure GIF images are decoded natively instead of deferring to intervention GIF // handling since we don't need the added animation support. $isGif = $fileType === 'gif'; $decoder = $isGif ? NativeObjectDecoder::class : BinaryImageDecoder::class; $input = $isGif ? @imagecreatefromstring($imageData) : $imageData; $image = $manager->read($input, $decoder); if ($isGif) { $image->setOrigin(new Origin('image/gif')); } return $image; } /** * Orientate the given intervention image based upon the given original image data. * Intervention does have an `orientate` method but the exif data it needs is lost before it * can be used (At least when created using binary string data) so we need to do some * implementation on our side to use the original image data. * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php * Copyright (c) Oliver Vogel, MIT License. */ protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void { if (!extension_loaded('exif')) { return; } $stream = Utils::streamFor($originalData)->detach(); $exif = @exif_read_data($stream); $orientation = $exif ? ($exif['Orientation'] ?? null) : null; switch ($orientation) { case 2: $image->flip(); break; case 3: $image->rotate(180); break; case 4: $image->rotate(180)->flip(); break; case 5: $image->rotate(270)->flip(); break; case 6: $image->rotate(270); break; case 7: $image->rotate(90)->flip(); break; case 8: $image->rotate(90); break; } } /** * Checks if the image is a GIF. Returns true if it is, else false. */ protected function isGif(Image $image): bool { return $this->getExtension($image) === 'gif'; } /** * Get the extension for the given image, normalised to lower-case. */ protected function getExtension(Image $image): string { return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)); } /** * Check if the given image and image data is apng. */ protected function isApngData(string &$imageData): bool { $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT')); return str_contains($initialHeader, 'acTL'); } /** * Check if the given avif image data represents an animated image. * This is based upon the answer here: https://stackoverflow.com/a/79457313 */ protected function isAnimatedAvifData(string &$imageData): bool { $stszPos = strpos($imageData, 'stsz'); if ($stszPos === false) { return false; } // Look 12 bytes after the start of 'stsz' $start = $stszPos + 12; $end = $start + 4; if ($end > strlen($imageData) - 1) { return false; } $data = substr($imageData, $start, 4); $count = unpack('Nvalue', $data)['value']; return $count > 1; } /** * Check if the given image is animated. */ protected function isAnimated(Image $image, string &$imageData): bool { $extension = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)); if ($extension === 'png') { return $this->isApngData($imageData); } if ($extension === 'avif') { return $this->isAnimatedAvifData($imageData); } return false; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/Attachment.php
app/Uploads/Attachment.php
<?php namespace BookStack\Uploads; use BookStack\App\Model; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Permissions\Models\JointPermission; use BookStack\Permissions\PermissionApplicator; use BookStack\Users\Models\HasCreatorAndUpdater; use BookStack\Users\Models\OwnableInterface; use BookStack\Users\Models\User; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; /** * @property int $id * @property string $name * @property string $path * @property string $extension * @property ?Page $page * @property bool $external * @property int $uploaded_to * @property User $updatedBy * @property User $createdBy * * @method static Entity|Builder visible() */ class Attachment extends Model implements OwnableInterface { use HasCreatorAndUpdater; use HasFactory; protected $fillable = ['name', 'order']; protected $hidden = ['path', 'page']; protected $casts = [ 'external' => 'bool', ]; /** * Get the downloadable file name for this upload. */ public function getFileName(): string { if (str_contains($this->name, '.')) { return $this->name; } return $this->name . '.' . $this->extension; } /** * Get the page this file was uploaded to. */ public function page(): BelongsTo { return $this->belongsTo(Page::class, 'uploaded_to'); } public function jointPermissions(): HasMany { return $this->hasMany(JointPermission::class, 'entity_id', 'uploaded_to') ->where('joint_permissions.entity_type', '=', 'page'); } /** * Get the url of this file. */ public function getUrl($openInline = false): string { if ($this->external && !str_starts_with($this->path, 'http')) { return $this->path; } return url('/attachments/' . $this->id . ($openInline ? '?open=true' : '')); } /** * Get the representation of this attachment in a format suitable for the page editors. * Detects and adapts video content to use an inline video embed. */ public function editorContent(): array { $videoExtensions = ['mp4', 'webm', 'mkv', 'ogg', 'avi']; if (in_array(strtolower($this->extension), $videoExtensions)) { $html = '<video src="' . e($this->getUrl(true)) . '" controls width="480" height="270"></video>'; return ['text/html' => $html, 'text/plain' => $html]; } return ['text/html' => $this->htmlLink(), 'text/plain' => $this->markdownLink()]; } /** * Generate the HTML link to this attachment. */ public function htmlLink(): string { return '<a target="_blank" href="' . e($this->getUrl()) . '">' . e($this->name) . '</a>'; } /** * Generate a MarkDown link to this attachment. */ public function markdownLink(): string { return '[' . $this->name . '](' . $this->getUrl() . ')'; } /** * Scope the query to those attachments that are visible based upon related page permissions. */ public function scopeVisible(): Builder { $permissions = app()->make(PermissionApplicator::class); return $permissions->restrictPageRelationQuery( self::query(), 'attachments', 'uploaded_to' ); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/ImageStorage.php
app/Uploads/ImageStorage.php
<?php namespace BookStack\Uploads; use Illuminate\Filesystem\FilesystemManager; use Illuminate\Support\Str; class ImageStorage { public function __construct( protected FilesystemManager $fileSystem, ) { } /** * Get the storage disk for the given image type. */ public function getDisk(string $imageType = ''): ImageStorageDisk { $diskName = $this->getDiskName($imageType); return new ImageStorageDisk( $diskName, $this->fileSystem->disk($diskName), ); } /** * Check if "local secure restricted" (Fetched behind auth, with permissions enforced) * is currently active in the instance. */ public function usingSecureRestrictedImages(): bool { return config('filesystems.images') === 'local_secure_restricted'; } /** * Check if "local secure" (Fetched behind auth, either with or without permissions enforced) * is currently active in the instance. */ public function usingSecureImages(): bool { return config('filesystems.images') === 'local_secure' || $this->usingSecureRestrictedImages(); } /** * Clean up an image file name to be both URL and storage safe. */ public function cleanImageFileName(string $name): string { $name = str_replace(' ', '-', $name); $nameParts = explode('.', $name); $extension = array_pop($nameParts); $name = implode('-', $nameParts); $name = Str::slug($name); if (strlen($name) === 0) { $name = Str::random(10); } return $name . '.' . $extension; } /** * Get the name of the storage disk to use. */ protected function getDiskName(string $imageType): string { $storageType = strtolower(config('filesystems.images')); $localSecureInUse = ($storageType === 'local_secure' || $storageType === 'local_secure_restricted'); // Ensure system images (App logo) are uploaded to a public space if ($imageType === 'system' && $localSecureInUse) { return 'local'; } // Rename local_secure options to get our image-specific storage driver, which // is scoped to the relevant image directories. if ($localSecureInUse) { return 'local_secure_images'; } return $storageType; } /** * Get a storage path for the given image URL. * Ensures the path will start with "uploads/images". * Returns null if the url cannot be resolved to a local URL. */ public function urlToPath(string $url): ?string { $url = ltrim(trim($url), '/'); // Handle potential relative paths $isRelative = !str_starts_with($url, 'http'); if ($isRelative) { if (str_starts_with(strtolower($url), 'uploads/images')) { return trim($url, '/'); } return null; } // Handle local images based on paths on the same domain $potentialHostPaths = [ url('uploads/images/'), $this->getPublicUrl('/uploads/images/'), ]; foreach ($potentialHostPaths as $potentialBasePath) { $potentialBasePath = strtolower($potentialBasePath); if (str_starts_with(strtolower($url), $potentialBasePath)) { return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/'); } } return null; } /** * Gets a public facing url for an image or location at the given path. */ public static function getPublicUrl(string $filePath): string { return static::getPublicBaseUrl() . '/' . ltrim($filePath, '/'); } /** * Get the public base URL used for images. * Will not include any path element of the image file, just the base part * from where the path is then expected to start from. * If s3-style store is in use it will default to guessing a public bucket URL. */ protected static function getPublicBaseUrl(): string { $storageUrl = config('filesystems.url'); // Get the standard public s3 url if s3 is set as storage type // Uses the nice, short URL if bucket name has no periods in otherwise the longer // region-based url will be used to prevent http issues. if (!$storageUrl && config('filesystems.images') === 's3') { $storageDetails = config('filesystems.disks.s3'); if (!str_contains($storageDetails['bucket'], '.')) { $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com'; } else { $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket']; } } $basePath = $storageUrl ?: url('/'); return rtrim($basePath, '/'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/Image.php
app/Uploads/Image.php
<?php namespace BookStack\Uploads; use BookStack\App\Model; use BookStack\Entities\Models\Page; use BookStack\Permissions\Models\JointPermission; use BookStack\Permissions\PermissionApplicator; use BookStack\Users\Models\HasCreatorAndUpdater; use BookStack\Users\Models\OwnableInterface; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\HasMany; /** * @property int $id * @property string $name * @property string $url * @property string $path * @property string $type * @property int|null $uploaded_to * @property int $created_by * @property int $updated_by */ class Image extends Model implements OwnableInterface { use HasFactory; use HasCreatorAndUpdater; protected $fillable = ['name']; protected $hidden = []; public function jointPermissions(): HasMany { return $this->hasMany(JointPermission::class, 'entity_id', 'uploaded_to') ->where('joint_permissions.entity_type', '=', 'page'); } /** * Scope the query to just the images visible to the user based upon the * user visibility of the uploaded_to page. */ public function scopeVisible(Builder $query): Builder { return app()->make(PermissionApplicator::class) ->restrictPageRelationQuery($query, 'images', 'uploaded_to') ->whereIn('type', ['gallery', 'drawio']); } /** * Get a thumbnail URL for this image. * Attempts to generate the thumbnail if not already existing. * * @throws \Exception */ public function getThumb(?int $width, ?int $height, bool $keepRatio = false): ?string { return app()->make(ImageResizer::class)->resizeToThumbnailUrl($this, $width, $height, $keepRatio, false); } /** * Get the page this image has been uploaded to. * Only applicable to gallery or drawio image types. */ public function getPage(): ?Page { return $this->belongsTo(Page::class, 'uploaded_to')->first(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/AttachmentService.php
app/Uploads/AttachmentService.php
<?php namespace BookStack\Uploads; use BookStack\Exceptions\FileUploadException; use Exception; use Symfony\Component\HttpFoundation\File\UploadedFile; class AttachmentService { public function __construct( protected FileStorage $storage, ) { } /** * Stream an attachment from storage. * * @return resource|null */ public function streamAttachmentFromStorage(Attachment $attachment) { return $this->storage->getReadStream($attachment->path); } /** * Read the file size of an attachment from storage, in bytes. */ public function getAttachmentFileSize(Attachment $attachment): int { return $this->storage->getSize($attachment->path); } /** * Store a new attachment upon user upload. * * @throws FileUploadException */ public function saveNewUpload(UploadedFile $uploadedFile, int $pageId): Attachment { $attachmentName = $uploadedFile->getClientOriginalName(); $attachmentPath = $this->putFileInStorage($uploadedFile); $largestExistingOrder = Attachment::query()->where('uploaded_to', '=', $pageId)->max('order'); /** @var Attachment $attachment */ $attachment = Attachment::query()->forceCreate([ 'name' => $attachmentName, 'path' => $attachmentPath, 'extension' => $uploadedFile->getClientOriginalExtension(), 'uploaded_to' => $pageId, 'created_by' => user()->id, 'updated_by' => user()->id, 'order' => $largestExistingOrder + 1, ]); return $attachment; } /** * Store an upload, saving to a file and deleting any existing uploads * attached to that file. * * @throws FileUploadException */ public function saveUpdatedUpload(UploadedFile $uploadedFile, Attachment $attachment): Attachment { if (!$attachment->external) { $this->deleteFileInStorage($attachment); } $attachmentName = $uploadedFile->getClientOriginalName(); $attachmentPath = $this->putFileInStorage($uploadedFile); $attachment->name = $attachmentName; $attachment->path = $attachmentPath; $attachment->external = false; $attachment->extension = $uploadedFile->getClientOriginalExtension(); $attachment->save(); return $attachment; } /** * Save a new File attachment from a given link and name. */ public function saveNewFromLink(string $name, string $link, int $page_id): Attachment { $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order'); return Attachment::forceCreate([ 'name' => $name, 'path' => $link, 'external' => true, 'extension' => '', 'uploaded_to' => $page_id, 'created_by' => user()->id, 'updated_by' => user()->id, 'order' => $largestExistingOrder + 1, ]); } /** * Updates the ordering for a listing of attached files. */ public function updateFileOrderWithinPage(array $attachmentOrder, string $pageId) { foreach ($attachmentOrder as $index => $attachmentId) { Attachment::query()->where('uploaded_to', '=', $pageId) ->where('id', '=', $attachmentId) ->update(['order' => $index]); } } /** * Update the details of a file. */ public function updateFile(Attachment $attachment, array $requestData): Attachment { if (isset($requestData['name'])) { $attachment->name = $requestData['name']; } $link = trim($requestData['link'] ?? ''); if (!empty($link)) { if (!$attachment->external) { $this->deleteFileInStorage($attachment); $attachment->external = true; $attachment->extension = ''; } $attachment->path = $link; } $attachment->save(); return $attachment->refresh(); } /** * Delete a File from the database and storage. * * @throws Exception */ public function deleteFile(Attachment $attachment) { if (!$attachment->external) { $this->deleteFileInStorage($attachment); } $attachment->delete(); } /** * Delete a file from the filesystem it sits on. * Cleans any empty leftover folders. */ public function deleteFileInStorage(Attachment $attachment): void { $this->storage->delete($attachment->path); } /** * Store a file in storage with the given filename. * * @throws FileUploadException */ protected function putFileInStorage(UploadedFile $uploadedFile): string { $basePath = 'uploads/files/' . date('Y-m-M') . '/'; return $this->storage->uploadFile( $uploadedFile, $basePath, $uploadedFile->getClientOriginalExtension(), '' ); } /** * Get the file validation rules for attachments. */ public static function getFileValidationRules(): array { return ['file', 'max:' . (config('app.upload_limit') * 1000)]; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/UserAvatars.php
app/Uploads/UserAvatars.php
<?php namespace BookStack\Uploads; use BookStack\Exceptions\HttpFetchException; use BookStack\Http\HttpRequestService; use BookStack\Users\Models\User; use BookStack\Util\WebSafeMimeSniffer; use Exception; use GuzzleHttp\Psr7\Request; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; use Psr\Http\Client\ClientExceptionInterface; class UserAvatars { public function __construct( protected ImageService $imageService, protected HttpRequestService $http ) { } /** * Fetch and assign an avatar image to the given user. */ public function fetchAndAssignToUser(User $user): void { if (!$this->avatarFetchEnabled()) { return; } try { $this->destroyAllForUser($user); $avatar = $this->saveAvatarImage($user); $user->avatar()->associate($avatar); $user->save(); } catch (Exception $e) { Log::error('Failed to save user avatar image', ['exception' => $e]); } } /** * Assign a new avatar image to the given user using the given image data. */ public function assignToUserFromExistingData(User $user, string $imageData, string $extension): void { try { $this->destroyAllForUser($user); $avatar = $this->createAvatarImageFromData($user, $imageData, $extension); $user->avatar()->associate($avatar); $user->save(); } catch (Exception $e) { Log::error('Failed to save user avatar image', ['exception' => $e]); } } /** * Assign a new avatar image to the given user by fetching from a remote URL. */ public function assignToUserFromUrl(User $user, string $avatarUrl): void { try { $this->destroyAllForUser($user); $imageData = $this->getAvatarImageData($avatarUrl); $mime = (new WebSafeMimeSniffer())->sniff($imageData); [$format, $type] = explode('/', $mime, 2); if ($format !== 'image' || !ImageService::isExtensionSupported($type)) { return; } $avatar = $this->createAvatarImageFromData($user, $imageData, $type); $user->avatar()->associate($avatar); $user->save(); } catch (Exception $e) { Log::error('Failed to save user avatar image from URL', [ 'exception' => $e->getMessage(), 'url' => $avatarUrl, 'user_id' => $user->id, ]); } } /** * Destroy all user avatars uploaded to the given user. */ public function destroyAllForUser(User $user): void { $profileImages = Image::query()->where('type', '=', 'user') ->where('uploaded_to', '=', $user->id) ->get(); foreach ($profileImages as $image) { $this->imageService->destroy($image); } } /** * Save an avatar image from an external service. * * @throws HttpFetchException */ protected function saveAvatarImage(User $user, int $size = 500): Image { $avatarUrl = $this->getAvatarUrl(); $email = strtolower(trim($user->email)); $replacements = [ '${hash}' => md5($email), '${size}' => $size, '${email}' => urlencode($email), ]; $userAvatarUrl = strtr($avatarUrl, $replacements); $imageData = $this->getAvatarImageData($userAvatarUrl); return $this->createAvatarImageFromData($user, $imageData, 'png'); } /** * Creates a new image instance and saves it in the system as a new user avatar image. */ protected function createAvatarImageFromData(User $user, string $imageData, string $extension): Image { $imageName = Str::random(10) . '-avatar.' . $extension; $image = $this->imageService->saveNew($imageName, $imageData, 'user', $user->id); $image->created_by = $user->id; $image->updated_by = $user->id; $image->save(); return $image; } /** * Get an image from a URL and return it as a string of image data. * * @throws HttpFetchException */ protected function getAvatarImageData(string $url): string { try { $client = $this->http->buildClient(5); $responseCount = 0; do { $response = $client->sendRequest(new Request('GET', $url)); $responseCount++; $isRedirect = ($response->getStatusCode() === 301 || $response->getStatusCode() === 302); $url = $response->getHeader('Location')[0] ?? ''; } while ($responseCount < 3 && $isRedirect && is_string($url) && str_starts_with($url, 'http')); if ($responseCount === 3) { throw new HttpFetchException("Failed to fetch image, max redirect limit of 3 tries reached. Last fetched URL: {$url}"); } if ($response->getStatusCode() !== 200) { throw new HttpFetchException(trans('errors.cannot_get_image_from_url', ['url' => $url])); } return (string) $response->getBody(); } catch (ClientExceptionInterface $exception) { throw new HttpFetchException(trans('errors.cannot_get_image_from_url', ['url' => $url]), $exception->getCode(), $exception); } } /** * Check if fetching external avatars is enabled. */ public function avatarFetchEnabled(): bool { $fetchUrl = $this->getAvatarUrl(); return str_starts_with($fetchUrl, 'http'); } /** * Get the URL to fetch avatars from. */ public function getAvatarUrl(): string { $configOption = config('services.avatar_url'); if ($configOption === false) { return ''; } $url = trim($configOption); if (empty($url) && !config('services.disable_services')) { $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon'; } return $url; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/FaviconHandler.php
app/Uploads/FaviconHandler.php
<?php namespace BookStack\Uploads; use Illuminate\Http\UploadedFile; class FaviconHandler { protected string $path; public function __construct( protected ImageResizer $imageResizer, ) { $this->path = public_path('favicon.ico'); } /** * Save the given UploadedFile instance as the application favicon. */ public function saveForUploadedImage(UploadedFile $file): void { if (!is_writeable($this->path)) { return; } $imageData = file_get_contents($file->getRealPath()); $pngData = $this->imageResizer->resizeImageData($imageData, 32, 32, false, 'png'); $icoData = $this->pngToIco($pngData, 32, 32); file_put_contents($this->path, $icoData); } /** * Restore the original favicon image. * Returned boolean indicates if the copy occurred. */ public function restoreOriginal(): bool { $permissionItem = file_exists($this->path) ? $this->path : dirname($this->path); if (!is_writeable($permissionItem)) { return false; } return copy($this->getOriginalPath(), $this->path); } /** * Restore the original favicon image if no favicon image is already in use. * Returns a boolean to indicate if the file exists. */ public function restoreOriginalIfNotExists(): bool { if (file_exists($this->path)) { return true; } return $this->restoreOriginal(); } /** * Get the path to the favicon file. */ public function getPath(): string { return $this->path; } /** * Get the path of the original favicon copy. */ public function getOriginalPath(): string { return public_path('icon.ico'); } /** * Convert PNG image data to ICO file format. * Built following the file format info from Wikipedia: * https://en.wikipedia.org/wiki/ICO_(file_format) */ protected function pngToIco(string $pngData, int $width, int $height): string { // ICO header $header = pack('v', 0x00); // Reserved. Must always be 0 $header .= pack('v', 0x01); // Specifies ico image $header .= pack('v', 0x01); // Specifies number of images // ICO Image Directory $entry = hex2bin(dechex($width)); // Image width $entry .= hex2bin(dechex($height)); // Image height $entry .= "\0"; // Color palette, typically 0 $entry .= "\0"; // Reserved // Color planes, Appears to remain 1 for bmp image data $entry .= pack('v', 0x01); // Bits per pixel, can range from 1 to 32. From testing conversion // via intervention from png typically provides this as 24. $entry .= pack('v', 0x00); // Size of the image data in bytes $entry .= pack('V', strlen($pngData)); // Offset of the bmp data from file start $entry .= pack('V', strlen($header) + strlen($entry) + 4); // Join & return the combined parts of the ICO image data return $header . $entry . $pngData; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/ImageStorageDisk.php
app/Uploads/ImageStorageDisk.php
<?php namespace BookStack\Uploads; use BookStack\Util\FilePathNormalizer; use Illuminate\Contracts\Filesystem\Filesystem; use Illuminate\Filesystem\FilesystemAdapter; use Illuminate\Support\Facades\Log; use League\Flysystem\UnableToSetVisibility; use League\Flysystem\Visibility; use Symfony\Component\HttpFoundation\StreamedResponse; class ImageStorageDisk { public function __construct( protected string $diskName, protected Filesystem $filesystem, ) { } /** * Check if local secure image storage (Fetched behind authentication) * is currently active in the instance. */ public function usingSecureImages(): bool { return $this->diskName === 'local_secure_images'; } /** * Change the originally provided path to fit any disk-specific requirements. * This also ensures the path is kept to the expected root folders. */ protected function adjustPathForDisk(string $path): string { $trimmed = str_replace('uploads/images/', '', $path); $normalized = FilePathNormalizer::normalize($trimmed); if ($this->usingSecureImages()) { return $normalized; } return 'uploads/images/' . $normalized; } /** * Check if a file at the given path exists. */ public function exists(string $path): bool { return $this->filesystem->exists($this->adjustPathForDisk($path)); } /** * Get the file at the given path. */ public function get(string $path): ?string { return $this->filesystem->get($this->adjustPathForDisk($path)); } /** * Get a stream to the file at the given path. * @return ?resource */ public function stream(string $path): mixed { return $this->filesystem->readStream($this->adjustPathForDisk($path)); } /** * Save the given image data at the given path. Can choose to set * the image as public which will update its visibility after saving. */ public function put(string $path, string $data, bool $makePublic = false): void { $path = $this->adjustPathForDisk($path); $this->filesystem->put($path, $data); // Set public visibility to ensure public access on S3, or that the file is accessible // to other processes (like web-servers) for local file storage options. // We avoid attempting this for (non-AWS) s3-like systems (even in a try-catch) as // we've always avoided setting permissions for s3-like due to potential issues, // with docs advising setting pre-configured permissions instead. // We also don't do this as the default filesystem/driver level as that can technically // require different ACLs for S3, and this provides us more logical control. if ($makePublic && !$this->isS3Like()) { try { $this->filesystem->setVisibility($path, Visibility::PUBLIC); } catch (UnableToSetVisibility $e) { Log::warning("Unable to set visibility for image upload with relative path: {$path}"); } } } /** * Destroys an image at the given path. * Searches for image thumbnails in addition to main provided path. */ public function destroyAllMatchingNameFromPath(string $path): void { $path = $this->adjustPathForDisk($path); $imageFolder = dirname($path); $imageFileName = basename($path); $allImages = collect($this->filesystem->allFiles($imageFolder)); // Delete image files $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) { return basename($imagePath) === $imageFileName; }); $this->filesystem->delete($imagesToDelete->all()); // Cleanup of empty folders $foldersInvolved = array_merge([$imageFolder], $this->filesystem->directories($imageFolder)); foreach ($foldersInvolved as $directory) { if ($this->isFolderEmpty($directory)) { $this->filesystem->deleteDirectory($directory); } } } /** * Get the mime type of the file at the given path. * Only works for local filesystem adapters. */ public function mimeType(string $path): string { $path = $this->adjustPathForDisk($path); return $this->filesystem instanceof FilesystemAdapter ? $this->filesystem->mimeType($path) : ''; } /** * Get a stream response for the image at the given path. */ public function response(string $path): StreamedResponse { return $this->filesystem->response($this->adjustPathForDisk($path)); } /** * Check if the image storage in use is an S3-like (but not likely S3) external system. */ protected function isS3Like(): bool { $usingS3 = $this->diskName === 's3'; return $usingS3 && !is_null(config('filesystems.disks.s3.endpoint')); } /** * Check whether a folder is empty. */ protected function isFolderEmpty(string $path): bool { $files = $this->filesystem->files($path); $folders = $this->filesystem->directories($path); return count($files) === 0 && count($folders) === 0; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/FileStorage.php
app/Uploads/FileStorage.php
<?php namespace BookStack\Uploads; use BookStack\Exceptions\FileUploadException; use BookStack\Util\FilePathNormalizer; use Exception; use Illuminate\Contracts\Filesystem\Filesystem as Storage; use Illuminate\Filesystem\FilesystemManager; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; use Symfony\Component\HttpFoundation\File\UploadedFile; class FileStorage { public function __construct( protected FilesystemManager $fileSystem, ) { } /** * @return resource|null */ public function getReadStream(string $path) { return $this->getStorageDisk()->readStream($this->adjustPathForStorageDisk($path)); } public function getSize(string $path): int { return $this->getStorageDisk()->size($this->adjustPathForStorageDisk($path)); } public function delete(string $path, bool $removeEmptyDir = false): void { $storage = $this->getStorageDisk(); $adjustedPath = $this->adjustPathForStorageDisk($path); $dir = dirname($adjustedPath); $storage->delete($adjustedPath); if ($removeEmptyDir && count($storage->allFiles($dir)) === 0) { $storage->deleteDirectory($dir); } } /** * @throws FileUploadException */ public function uploadFile(UploadedFile $file, string $subDirectory, string $suffix, string $extension): string { $storage = $this->getStorageDisk(); $basePath = trim($subDirectory, '/') . '/'; $uploadFileName = Str::random(16) . ($suffix ? "-{$suffix}" : '') . ($extension ? ".{$extension}" : ''); while ($storage->exists($this->adjustPathForStorageDisk($basePath . $uploadFileName))) { $uploadFileName = Str::random(3) . $uploadFileName; } $fileStream = fopen($file->getRealPath(), 'r'); $filePath = $basePath . $uploadFileName; try { $storage->writeStream($this->adjustPathForStorageDisk($filePath), $fileStream); } catch (Exception $e) { Log::error('Error when attempting file upload:' . $e->getMessage()); throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $filePath])); } return $filePath; } /** * Check whether the configured storage is remote from the host of this app. */ public function isRemote(): bool { return $this->getStorageDiskName() === 's3'; } /** * Get the actual path on system for the given relative file path. */ public function getSystemPath(string $filePath): string { if ($this->isRemote()) { return ''; } return storage_path('uploads/files/' . ltrim($this->adjustPathForStorageDisk($filePath), '/')); } /** * Get the storage that will be used for storing files. */ protected function getStorageDisk(): Storage { return $this->fileSystem->disk($this->getStorageDiskName()); } /** * Get the name of the storage disk to use. */ protected function getStorageDiskName(): string { $storageType = trim(strtolower(config('filesystems.attachments'))); // Change to our secure-attachment disk if any of the local options // are used to prevent escaping that location. if ($storageType === 'local' || $storageType === 'local_secure' || $storageType === 'local_secure_restricted') { $storageType = 'local_secure_attachments'; } return $storageType; } /** * Change the originally provided path to fit any disk-specific requirements. * This also ensures the path is kept to the expected root folders. */ protected function adjustPathForStorageDisk(string $path): string { $trimmed = str_replace('uploads/files/', '', $path); $normalized = FilePathNormalizer::normalize($trimmed); if ($this->getStorageDiskName() === 'local_secure_attachments') { return $normalized; } return 'uploads/files/' . $normalized; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/ImageRepo.php
app/Uploads/ImageRepo.php
<?php namespace BookStack\Uploads; use BookStack\Entities\Queries\PageQueries; use BookStack\Exceptions\ImageUploadException; use BookStack\Permissions\PermissionApplicator; use Exception; use Illuminate\Database\Eloquent\Builder; use Symfony\Component\HttpFoundation\File\UploadedFile; class ImageRepo { public function __construct( protected ImageService $imageService, protected PermissionApplicator $permissions, protected ImageResizer $imageResizer, protected PageQueries $pageQueries, ) { } /** * Get an image with the given id. */ public function getById($id): Image { return Image::query()->findOrFail($id); } /** * Execute a paginated query, returning in a standard format. * Also runs the query through the restriction system. */ protected function returnPaginated(Builder $query, int $page = 1, int $pageSize = 24): array { $images = $query->orderBy('created_at', 'desc')->skip($pageSize * ($page - 1))->take($pageSize + 1)->get(); return [ 'images' => $images->take($pageSize), 'has_more' => count($images) > $pageSize, ]; } /** * Fetch a list of images in a paginated format, filtered by image type. * Can be filtered by uploaded to and also by name. */ public function getPaginatedByType( string $type, int $page = 0, int $pageSize = 24, ?int $uploadedTo = null, ?string $search = null, ?callable $whereClause = null ): array { $imageQuery = Image::query()->where('type', '=', strtolower($type)); if ($uploadedTo !== null) { $imageQuery = $imageQuery->where('uploaded_to', '=', $uploadedTo); } if ($search !== null) { $imageQuery = $imageQuery->where('name', 'LIKE', '%' . $search . '%'); } // Filter by page access $imageQuery = $this->permissions->restrictPageRelationQuery($imageQuery, 'images', 'uploaded_to'); if ($whereClause !== null) { $imageQuery = $imageQuery->where($whereClause); } return $this->returnPaginated($imageQuery, $page, $pageSize); } /** * Get paginated gallery images within a specific page or book. */ public function getEntityFiltered( string $type, ?string $filterType, int $page, int $pageSize, int $uploadedTo, ?string $search ): array { $contextPage = $this->pageQueries->findVisibleByIdOrFail($uploadedTo); $parentFilter = null; if ($filterType === 'book' || $filterType === 'page') { $parentFilter = function (Builder $query) use ($filterType, $contextPage) { if ($filterType === 'page') { $query->where('uploaded_to', '=', $contextPage->id); } else if ($filterType === 'book') { $validPageIds = $contextPage->book->pages() ->scopes('visible') ->pluck('id') ->toArray(); $query->whereIn('uploaded_to', $validPageIds); } }; } return $this->getPaginatedByType($type, $page, $pageSize, null, $search, $parentFilter); } /** * Save a new image into storage and return the new image. * * @throws ImageUploadException */ public function saveNew( UploadedFile $uploadFile, string $type, int $uploadedTo = 0, ?int $resizeWidth = null, ?int $resizeHeight = null, bool $keepRatio = true ): Image { $image = $this->imageService->saveNewFromUpload($uploadFile, $type, $uploadedTo, $resizeWidth, $resizeHeight, $keepRatio); if ($type !== 'system') { $this->imageResizer->loadGalleryThumbnailsForImage($image, true); } return $image; } /** * Save a new image from an existing image data string. * * @throws ImageUploadException */ public function saveNewFromData(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image { $image = $this->imageService->saveNew($imageName, $imageData, $type, $uploadedTo); $this->imageResizer->loadGalleryThumbnailsForImage($image, true); return $image; } /** * Save a drawing in the database. * * @throws ImageUploadException */ public function saveDrawing(string $base64Uri, int $uploadedTo): Image { $name = 'Drawing-' . user()->id . '-' . time() . '.png'; return $this->imageService->saveNewFromBase64Uri($base64Uri, $name, 'drawio', $uploadedTo); } /** * Update the details of an image via an array of properties. * * @throws Exception */ public function updateImageDetails(Image $image, $updateDetails): Image { $image->fill($updateDetails); $image->updated_by = user()->id; $image->save(); $this->imageResizer->loadGalleryThumbnailsForImage($image, false); return $image; } /** * Update the image file of an existing image in the system. * @throws ImageUploadException */ public function updateImageFile(Image $image, UploadedFile $file): void { if (strtolower($file->getClientOriginalExtension()) !== strtolower(pathinfo($image->path, PATHINFO_EXTENSION))) { throw new ImageUploadException(trans('errors.image_upload_replace_type')); } $image->refresh(); $image->updated_by = user()->id; $image->touch(); $image->save(); $this->imageService->replaceExistingFromUpload($image->path, $image->type, $file); $this->imageResizer->loadGalleryThumbnailsForImage($image, true); } /** * Destroys an Image object along with its revisions, files and thumbnails. * * @throws Exception */ public function destroyImage(?Image $image = null): void { if ($image) { $this->imageService->destroy($image); } } /** * Destroy images that have a specific URL and type combination. * * @throws Exception */ public function destroyByUrlAndType(string $url, string $imageType): void { $images = Image::query() ->where('url', '=', $url) ->where('type', '=', $imageType) ->get(); foreach ($images as $image) { $this->destroyImage($image); } } /** * Get the raw image data from an Image. */ public function getImageData(Image $image): ?string { try { return $this->imageService->getImageData($image); } catch (Exception $exception) { return null; } } /** * Get the user visible pages using the given image. */ public function getPagesUsingImage(Image $image): array { $pages = $this->pageQueries->visibleForList() ->where('html', 'like', '%' . $image->url . '%') ->get(); foreach ($pages as $page) { $page->setAttribute('url', $page->getUrl()); } return $pages->all(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/ImageService.php
app/Uploads/ImageService.php
<?php namespace BookStack\Uploads; use BookStack\Entities\Queries\EntityQueries; use BookStack\Exceptions\ImageUploadException; use Exception; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\StreamedResponse; class ImageService { protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif']; public function __construct( protected ImageStorage $storage, protected ImageResizer $resizer, protected EntityQueries $queries, ) { } /** * Saves a new image from an upload. * * @throws ImageUploadException */ public function saveNewFromUpload( UploadedFile $uploadedFile, string $type, int $uploadedTo = 0, ?int $resizeWidth = null, ?int $resizeHeight = null, bool $keepRatio = true, string $imageName = '', ): Image { $imageName = $imageName ?: $uploadedFile->getClientOriginalName(); $imageData = file_get_contents($uploadedFile->getRealPath()); if ($resizeWidth !== null || $resizeHeight !== null) { $imageData = $this->resizer->resizeImageData($imageData, $resizeWidth, $resizeHeight, $keepRatio); } return $this->saveNew($imageName, $imageData, $type, $uploadedTo); } /** * Save a new image from a uri-encoded base64 string of data. * * @throws ImageUploadException */ public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image { $splitData = explode(';base64,', $base64Uri); if (count($splitData) < 2) { throw new ImageUploadException('Invalid base64 image data provided'); } $data = base64_decode($splitData[1]); return $this->saveNew($name, $data, $type, $uploadedTo); } /** * Save a new image into storage. * * @throws ImageUploadException */ public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image { $disk = $this->storage->getDisk($type); $secureUploads = setting('app-secure-images'); $fileName = $this->storage->cleanImageFileName($imageName); $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/'; while ($disk->exists($imagePath . $fileName)) { $fileName = Str::random(3) . $fileName; } $fullPath = $imagePath . $fileName; if ($secureUploads) { $fullPath = $imagePath . Str::random(16) . '-' . $fileName; } try { $disk->put($fullPath, $imageData, true); } catch (Exception $e) { Log::error('Error when attempting image upload:' . $e->getMessage()); throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath])); } $imageDetails = [ 'name' => $imageName, 'path' => $fullPath, 'url' => $this->storage->getPublicUrl($fullPath), 'type' => $type, 'uploaded_to' => $uploadedTo, ]; if (user()->id !== 0) { $userId = user()->id; $imageDetails['created_by'] = $userId; $imageDetails['updated_by'] = $userId; } $image = (new Image())->forceFill($imageDetails); $image->save(); return $image; } /** * Replace an existing image file in the system using the given file. */ public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void { $imageData = file_get_contents($file->getRealPath()); $disk = $this->storage->getDisk($type); $disk->put($path, $imageData); } /** * Get the raw data content from an image. * * @throws Exception */ public function getImageData(Image $image): string { $disk = $this->storage->getDisk(); return $disk->get($image->path); } /** * Get the raw data content from an image. * * @throws Exception * @return ?resource */ public function getImageStream(Image $image): mixed { $disk = $this->storage->getDisk(); return $disk->stream($image->path); } /** * Destroy an image along with its revisions, thumbnails, and remaining folders. * * @throws Exception */ public function destroy(Image $image): void { $this->destroyFileAtPath($image->type, $image->path); $image->delete(); } /** * Destroy the underlying image file at the given path. */ public function destroyFileAtPath(string $type, string $path): void { $disk = $this->storage->getDisk($type); $disk->destroyAllMatchingNameFromPath($path); } /** * Delete gallery and drawings that are not within HTML content of pages or page revisions. * Checks based off of only the image name. * Could be much improved to be more specific but kept it generic for now to be safe. * * Returns the path of the images that would be/have been deleted. */ public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true): array { $types = ['gallery', 'drawio']; $deletedPaths = []; Image::query()->whereIn('type', $types) ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) { /** @var Image $image */ foreach ($images as $image) { $searchQuery = '%' . basename($image->path) . '%'; $inPage = DB::table('entity_page_data') ->where('html', 'like', $searchQuery)->count() > 0; $inRevision = false; if ($checkRevisions) { $inRevision = DB::table('page_revisions') ->where('html', 'like', $searchQuery)->count() > 0; } if (!$inPage && !$inRevision) { $deletedPaths[] = $image->path; if (!$dryRun) { $this->destroy($image); } } } }); return $deletedPaths; } /** * Convert an image URI to a Base64 encoded string. * Attempts to convert the URL to a system storage url then * fetch the data from the disk or storage location. * Returns null if the image data cannot be fetched from storage. */ public function imageUrlToBase64(string $url): ?string { $storagePath = $this->storage->urlToPath($url); if (empty($url) || is_null($storagePath)) { return null; } // Apply access control when local_secure_restricted images are active if ($this->storage->usingSecureRestrictedImages()) { if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) { return null; } } $disk = $this->storage->getDisk(); $imageData = null; if ($disk->exists($storagePath)) { $imageData = $disk->get($storagePath); } if (is_null($imageData)) { return null; } $extension = pathinfo($url, PATHINFO_EXTENSION); if ($extension === 'svg') { $extension = 'svg+xml'; } return 'data:image/' . $extension . ';base64,' . base64_encode($imageData); } /** * Check if the given path exists and is accessible in the local secure image system. * Returns false if local_secure is not in use, if the file does not exist, if the * file is likely not a valid image, or if permission does not allow access. */ public function pathAccessibleInLocalSecure(string $imagePath): bool { $disk = $this->storage->getDisk('gallery'); return $disk->usingSecureImages() && $this->pathAccessible($imagePath); } /** * Check if the given path exists and is accessible depending on the current settings. */ public function pathAccessible(string $imagePath): bool { if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) { return false; } if ($this->blockedBySecureImages()) { return false; } return $this->imageFileExists($imagePath, 'gallery'); } /** * Check if the given image should be accessible to the current user. */ public function imageAccessible(Image $image): bool { if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImage($image)) { return false; } if ($this->blockedBySecureImages()) { return false; } return $this->imageFileExists($image->path, $image->type); } /** * Check if the current user should be blocked from accessing images based on if secure images are enabled * and if public access is enabled for the application. */ protected function blockedBySecureImages(): bool { $enforced = $this->storage->usingSecureImages() && !setting('app-public'); return $enforced && user()->isGuest(); } /** * Check if the given image path exists for the given image type and that it is likely an image file. */ protected function imageFileExists(string $imagePath, string $imageType): bool { $disk = $this->storage->getDisk($imageType); return $disk->exists($imagePath) && str_starts_with($disk->mimeType($imagePath), 'image/'); } /** * Check that the current user has access to the relation * of the image at the given path. */ protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool { if (str_starts_with($path, 'uploads/images/')) { $path = substr($path, 15); } // Strip thumbnail element from path if existing $originalPathSplit = array_filter(explode('/', $path), function (string $part) { $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-')); $missingExtension = !str_contains($part, '.'); return !($resizedDir && $missingExtension); }); // Build a database-format image path and search for the image entry $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/'); $image = Image::query()->where('path', '=', $fullPath)->first(); if (is_null($image)) { return false; } return $this->checkUserHasAccessToRelationOfImage($image); } protected function checkUserHasAccessToRelationOfImage(Image $image): bool { $imageType = $image->type; // Allow user or system (logo) images // (No specific relation control but may still have access controlled by auth) if ($imageType === 'user' || $imageType === 'system') { return true; } if ($imageType === 'gallery' || $imageType === 'drawio') { return $this->queries->pages->visibleForList()->where('id', '=', $image->uploaded_to)->exists(); } if ($imageType === 'cover_book') { return $this->queries->books->visibleForList()->where('id', '=', $image->uploaded_to)->exists(); } if ($imageType === 'cover_bookshelf') { return $this->queries->shelves->visibleForList()->where('id', '=', $image->uploaded_to)->exists(); } return false; } /** * For the given path, if existing, provide a response that will stream the image contents. */ public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse { $disk = $this->storage->getDisk($imageType); return $disk->response($path); } /** * Check if the given image extension is supported by BookStack. * The extension must not be altered in this function. This check should provide a guarantee * that the provided extension is safe to use for the image to be saved. */ public static function isExtensionSupported(string $extension): bool { return in_array($extension, static::$supportedExtensions); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/Controllers/AttachmentApiController.php
app/Uploads/Controllers/AttachmentApiController.php
<?php namespace BookStack\Uploads\Controllers; use BookStack\Entities\EntityExistsRule; use BookStack\Entities\Queries\PageQueries; use BookStack\Exceptions\FileUploadException; use BookStack\Http\ApiController; use BookStack\Permissions\Permission; use BookStack\Uploads\Attachment; use BookStack\Uploads\AttachmentService; use Exception; use Illuminate\Contracts\Filesystem\FileNotFoundException; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; class AttachmentApiController extends ApiController { public function __construct( protected AttachmentService $attachmentService, protected PageQueries $pageQueries, ) { } /** * Get a listing of attachments visible to the user. * The external property indicates whether the attachment is simple a link. * A false value for the external property would indicate a file upload. */ public function list() { return $this->apiListingResponse(Attachment::visible(), [ 'id', 'name', 'extension', 'uploaded_to', 'external', 'order', 'created_at', 'updated_at', 'created_by', 'updated_by', ]); } /** * Create a new attachment in the system. * An uploaded_to value must be provided containing an ID of the page * that this upload will be related to. * * If you're uploading a file the POST data should be provided via * a multipart/form-data type request instead of JSON. * * @throws ValidationException * @throws FileUploadException */ public function create(Request $request) { $this->checkPermission(Permission::AttachmentCreateAll); $requestData = $this->validate($request, $this->rules()['create']); $pageId = $request->get('uploaded_to'); $page = $this->pageQueries->findVisibleByIdOrFail($pageId); $this->checkOwnablePermission(Permission::PageUpdate, $page); if ($request->hasFile('file')) { $uploadedFile = $request->file('file'); $attachment = $this->attachmentService->saveNewUpload($uploadedFile, $page->id); } else { $attachment = $this->attachmentService->saveNewFromLink( $requestData['name'], $requestData['link'], $page->id ); } $this->attachmentService->updateFile($attachment, $requestData); return response()->json($attachment); } /** * Get the details & content of a single attachment of the given ID. * The attachment link or file content is provided via a 'content' property. * For files the content will be base64 encoded. * * @throws FileNotFoundException */ public function read(string $id) { /** @var Attachment $attachment */ $attachment = Attachment::visible() ->with(['createdBy', 'updatedBy']) ->findOrFail($id); $attachment->setAttribute('links', [ 'html' => $attachment->htmlLink(), 'markdown' => $attachment->markdownLink(), ]); // Simply return a JSON response of the attachment for link-based attachments if ($attachment->external) { $attachment->setAttribute('content', $attachment->path); return response()->json($attachment); } // Build and split our core JSON, at point of content. $splitter = 'CONTENT_SPLIT_LOCATION_' . time() . '_' . rand(1, 40000); $attachment->setAttribute('content', $splitter); $json = $attachment->toJson(); $jsonParts = explode($splitter, $json); // Get a stream for the file data from storage $stream = $this->attachmentService->streamAttachmentFromStorage($attachment); return response()->stream(function () use ($jsonParts, $stream) { // Output the pre-content JSON data echo $jsonParts[0]; // Stream out our attachment data as base64 content stream_filter_append($stream, 'convert.base64-encode', STREAM_FILTER_READ); fpassthru($stream); fclose($stream); // Output our post-content JSON data echo $jsonParts[1]; }, 200, ['Content-Type' => 'application/json']); } /** * Update the details of a single attachment. * As per the create endpoint, if a file is being provided as the attachment content * the request should be formatted as a multipart/form-data request instead of JSON. * * @throws ValidationException * @throws FileUploadException */ public function update(Request $request, string $id) { $requestData = $this->validate($request, $this->rules()['update']); /** @var Attachment $attachment */ $attachment = Attachment::visible()->findOrFail($id); $page = $attachment->page; if ($requestData['uploaded_to'] ?? false) { $pageId = $request->get('uploaded_to'); $page = $this->pageQueries->findVisibleByIdOrFail($pageId); $attachment->uploaded_to = $requestData['uploaded_to']; } $this->checkOwnablePermission(Permission::PageView, $page); $this->checkOwnablePermission(Permission::PageUpdate, $page); $this->checkOwnablePermission(Permission::AttachmentUpdate, $attachment); if ($request->hasFile('file')) { $uploadedFile = $request->file('file'); $attachment = $this->attachmentService->saveUpdatedUpload($uploadedFile, $attachment); } $this->attachmentService->updateFile($attachment, $requestData); return response()->json($attachment); } /** * Delete an attachment of the given ID. * * @throws Exception */ public function delete(string $id) { /** @var Attachment $attachment */ $attachment = Attachment::visible()->findOrFail($id); $this->checkOwnablePermission(Permission::AttachmentDelete, $attachment); $this->attachmentService->deleteFile($attachment); return response('', 204); } protected function rules(): array { return [ 'create' => [ 'name' => ['required', 'string', 'min:1', 'max:255'], 'uploaded_to' => ['required', 'integer', new EntityExistsRule('page')], 'file' => array_merge(['required_without:link'], $this->attachmentService->getFileValidationRules()), 'link' => ['required_without:file', 'string', 'min:1', 'max:2000', 'safe_url'], ], 'update' => [ 'name' => ['string', 'min:1', 'max:255'], 'uploaded_to' => ['integer', new EntityExistsRule('page')], 'file' => $this->attachmentService->getFileValidationRules(), 'link' => ['string', 'min:1', 'max:2000', 'safe_url'], ], ]; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/Controllers/GalleryImageController.php
app/Uploads/Controllers/GalleryImageController.php
<?php namespace BookStack\Uploads\Controllers; use BookStack\Exceptions\ImageUploadException; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use BookStack\Uploads\ImageRepo; use BookStack\Uploads\ImageResizer; use BookStack\Util\OutOfMemoryHandler; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; class GalleryImageController extends Controller { public function __construct( protected ImageRepo $imageRepo ) { } /** * Get a list of gallery images, in a list. * Can be paged and filtered by entity. */ public function list(Request $request, ImageResizer $resizer) { $page = $request->get('page', 1); $searchTerm = $request->get('search', null); $uploadedToFilter = $request->get('uploaded_to', null); $parentTypeFilter = $request->get('filter_type', null); $imgData = $this->imageRepo->getEntityFiltered('gallery', $parentTypeFilter, $page, 30, $uploadedToFilter, $searchTerm); $viewData = [ 'warning' => '', 'images' => $imgData['images'], 'hasMore' => $imgData['has_more'], ]; new OutOfMemoryHandler(function () use ($viewData) { $viewData['warning'] = trans('errors.image_gallery_thumbnail_memory_limit'); return response()->view('pages.parts.image-manager-list', $viewData, 200); }); $resizer->loadGalleryThumbnailsForMany($imgData['images']); return view('pages.parts.image-manager-list', $viewData); } /** * Store a new gallery image in the system. * * @throws ValidationException */ public function create(Request $request) { $this->checkPermission(Permission::ImageCreateAll); try { $this->validate($request, [ 'file' => $this->getImageValidationRules(), ]); } catch (ValidationException $exception) { return $this->jsonError(implode("\n", $exception->errors()['file'])); } new OutOfMemoryHandler(function () { return $this->jsonError(trans('errors.image_upload_memory_limit')); }); try { $imageUpload = $request->file('file'); $uploadedTo = $request->get('uploaded_to', 0); $image = $this->imageRepo->saveNew($imageUpload, 'gallery', $uploadedTo); } catch (ImageUploadException $e) { return response($e->getMessage(), 500); } return response()->json($image); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/Controllers/ImageController.php
app/Uploads/Controllers/ImageController.php
<?php namespace BookStack\Uploads\Controllers; use BookStack\Exceptions\ImageUploadException; use BookStack\Exceptions\NotFoundException; use BookStack\Exceptions\NotifyException; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use BookStack\Uploads\Image; use BookStack\Uploads\ImageRepo; use BookStack\Uploads\ImageResizer; use BookStack\Uploads\ImageService; use BookStack\Util\OutOfMemoryHandler; use Exception; use Illuminate\Http\Request; class ImageController extends Controller { public function __construct( protected ImageRepo $imageRepo, protected ImageService $imageService, protected ImageResizer $imageResizer, ) { } /** * Provide an image file from storage. * * @throws NotFoundException */ public function showImage(string $path) { if (!$this->imageService->pathAccessibleInLocalSecure($path)) { throw (new NotFoundException(trans('errors.image_not_found'))) ->setSubtitle(trans('errors.image_not_found_subtitle')) ->setDetails(trans('errors.image_not_found_details')); } return $this->imageService->streamImageFromStorageResponse('gallery', $path); } /** * Update image details. */ public function update(Request $request, string $id) { $data = $this->validate($request, [ 'name' => ['required', 'min:2', 'string'], ]); $image = $this->imageRepo->getById($id); $this->checkImagePermission($image); $this->checkOwnablePermission(Permission::ImageUpdate, $image); $image = $this->imageRepo->updateImageDetails($image, $data); return view('pages.parts.image-manager-form', [ 'image' => $image, 'dependantPages' => null, ]); } /** * Update the file for an existing image. */ public function updateFile(Request $request, string $id) { $this->validate($request, [ 'file' => ['required', 'file', ...$this->getImageValidationRules()], ]); $image = $this->imageRepo->getById($id); $this->checkImagePermission($image); $this->checkOwnablePermission(Permission::ImageUpdate, $image); $file = $request->file('file'); new OutOfMemoryHandler(function () { return $this->jsonError(trans('errors.image_upload_memory_limit')); }); try { $this->imageRepo->updateImageFile($image, $file); } catch (ImageUploadException $exception) { return $this->jsonError($exception->getMessage()); } return response(''); } /** * Get the form for editing the given image. * * @throws Exception */ public function edit(Request $request, string $id) { $image = $this->imageRepo->getById($id); $this->checkImagePermission($image); if ($request->has('delete')) { $dependantPages = $this->imageRepo->getPagesUsingImage($image); } $viewData = [ 'image' => $image, 'dependantPages' => $dependantPages ?? null, 'warning' => '', ]; new OutOfMemoryHandler(function () use ($viewData) { $viewData['warning'] = trans('errors.image_thumbnail_memory_limit'); return response()->view('pages.parts.image-manager-form', $viewData); }); $this->imageResizer->loadGalleryThumbnailsForImage($image, false); return view('pages.parts.image-manager-form', $viewData); } /** * Deletes an image and all thumbnail/image files. * * @throws Exception */ public function destroy(string $id) { $image = $this->imageRepo->getById($id); $this->checkOwnablePermission(Permission::ImageDelete, $image); $this->checkImagePermission($image); $this->imageRepo->destroyImage($image); return response(''); } /** * Rebuild the thumbnails for the given image. */ public function rebuildThumbnails(string $id) { $image = $this->imageRepo->getById($id); $this->checkImagePermission($image); $this->checkOwnablePermission(Permission::ImageUpdate, $image); new OutOfMemoryHandler(function () { return $this->jsonError(trans('errors.image_thumbnail_memory_limit')); }); $this->imageResizer->loadGalleryThumbnailsForImage($image, true); return response(trans('components.image_rebuild_thumbs_success')); } /** * Check related page permission and ensure type is drawio or gallery. * @throws NotifyException */ protected function checkImagePermission(Image $image): void { if ($image->type !== 'drawio' && $image->type !== 'gallery') { $this->showPermissionError(); } $relatedPage = $image->getPage(); if ($relatedPage) { $this->checkOwnablePermission(Permission::PageView, $relatedPage); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/Controllers/DrawioImageController.php
app/Uploads/Controllers/DrawioImageController.php
<?php namespace BookStack\Uploads\Controllers; use BookStack\Exceptions\ImageUploadException; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use BookStack\Uploads\ImageRepo; use BookStack\Uploads\ImageResizer; use BookStack\Util\OutOfMemoryHandler; use Exception; use Illuminate\Http\Request; class DrawioImageController extends Controller { public function __construct( protected ImageRepo $imageRepo ) { } /** * Get a list of gallery images, in a list. * Can be paged and filtered by entity. */ public function list(Request $request, ImageResizer $resizer) { $page = $request->get('page', 1); $searchTerm = $request->get('search', null); $uploadedToFilter = $request->get('uploaded_to', null); $parentTypeFilter = $request->get('filter_type', null); $imgData = $this->imageRepo->getEntityFiltered('drawio', $parentTypeFilter, $page, 24, $uploadedToFilter, $searchTerm); $viewData = [ 'warning' => '', 'images' => $imgData['images'], 'hasMore' => $imgData['has_more'], ]; new OutOfMemoryHandler(function () use ($viewData) { $viewData['warning'] = trans('errors.image_gallery_thumbnail_memory_limit'); return response()->view('pages.parts.image-manager-list', $viewData, 200); }); $resizer->loadGalleryThumbnailsForMany($imgData['images']); return view('pages.parts.image-manager-list', $viewData); } /** * Store a new gallery image in the system. * * @throws Exception */ public function create(Request $request) { $this->validate($request, [ 'image' => ['required', 'string'], 'uploaded_to' => ['required', 'integer'], ]); $this->checkPermission(Permission::ImageCreateAll); $imageBase64Data = $request->get('image'); try { $uploadedTo = $request->get('uploaded_to', 0); $image = $this->imageRepo->saveDrawing($imageBase64Data, $uploadedTo); } catch (ImageUploadException $e) { return response($e->getMessage(), 500); } return response()->json($image); } /** * Get the content of an image based64 encoded. */ public function getAsBase64($id) { try { $image = $this->imageRepo->getById($id); } catch (Exception $exception) { return $this->jsonError(trans('errors.drawing_data_not_found'), 404); } if ($image->type !== 'drawio' || !userCan(Permission::PageView, $image->getPage())) { return $this->jsonError(trans('errors.drawing_data_not_found'), 404); } $imageData = $this->imageRepo->getImageData($image); if (is_null($imageData)) { return $this->jsonError(trans('errors.drawing_data_not_found'), 404); } return response()->json([ 'content' => base64_encode($imageData), ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/Controllers/ImageGalleryApiController.php
app/Uploads/Controllers/ImageGalleryApiController.php
<?php namespace BookStack\Uploads\Controllers; use BookStack\Entities\Queries\PageQueries; use BookStack\Exceptions\NotFoundException; use BookStack\Http\ApiController; use BookStack\Permissions\Permission; use BookStack\Uploads\Image; use BookStack\Uploads\ImageRepo; use BookStack\Uploads\ImageResizer; use BookStack\Uploads\ImageService; use Illuminate\Http\Request; class ImageGalleryApiController extends ApiController { protected array $fieldsToExpose = [ 'id', 'name', 'url', 'path', 'type', 'uploaded_to', 'created_by', 'updated_by', 'created_at', 'updated_at', ]; public function __construct( protected ImageRepo $imageRepo, protected ImageResizer $imageResizer, protected PageQueries $pageQueries, protected ImageService $imageService, ) { } protected function rules(): array { return [ 'create' => [ 'type' => ['required', 'string', 'in:gallery,drawio'], 'uploaded_to' => ['required', 'integer'], 'image' => ['required', 'file', ...$this->getImageValidationRules()], 'name' => ['string', 'max:180'], ], 'readDataForUrl' => [ 'url' => ['required', 'string', 'url'], ], 'update' => [ 'name' => ['string', 'max:180'], 'image' => ['file', ...$this->getImageValidationRules()], ] ]; } /** * Get a listing of images in the system. Includes gallery (page content) images and drawings. * Requires visibility of the page they're originally uploaded to. */ public function list() { $images = Image::query()->scopes(['visible']) ->select($this->fieldsToExpose) ->whereIn('type', ['gallery', 'drawio']); return $this->apiListingResponse($images, [ ...$this->fieldsToExpose ]); } /** * Create a new image in the system. * * Since "image" is expected to be a file, this needs to be a 'multipart/form-data' type request. * The provided "uploaded_to" should be an existing page ID in the system. * * If the "name" parameter is omitted, the filename of the provided image file will be used instead. * The "type" parameter should be 'gallery' for page content images, and 'drawio' should only be used * when the file is a PNG file with diagrams.net image data embedded within. */ public function create(Request $request) { $this->checkPermission(Permission::ImageCreateAll); $data = $this->validate($request, $this->rules()['create']); $page = $this->pageQueries->findVisibleByIdOrFail($data['uploaded_to']); $image = $this->imageRepo->saveNew($data['image'], $data['type'], $page->id); if (isset($data['name'])) { $image->refresh(); $image->update(['name' => $data['name']]); } return response()->json($this->formatForSingleResponse($image)); } /** * View the details of a single image. * The "thumbs" response property contains links to scaled variants that BookStack may use in its UI. * The "content" response property provides HTML and Markdown content, in the format that BookStack * would typically use by default to add the image in page content, as a convenience. * Actual image file data is not provided but can be fetched via the "url" response property or by * using the "read-data" endpoint. */ public function read(string $id) { $image = Image::query()->scopes(['visible'])->findOrFail($id); return response()->json($this->formatForSingleResponse($image)); } /** * Read the image file data for a single image in the system. * The returned response will be a stream of image data instead of a JSON response. */ public function readData(string $id) { $image = Image::query()->scopes(['visible'])->findOrFail($id); return $this->imageService->streamImageFromStorageResponse('gallery', $image->path); } /** * Read the image file data for a single image in the system, using the provided URL * to identify the image instead of its ID, which is provided as a "URL" query parameter. * The returned response will be a stream of image data instead of a JSON response. */ public function readDataForUrl(Request $request) { $data = $this->validate($request, $this->rules()['readDataForUrl']); $basePath = url('/uploads/images/'); $imagePath = str_replace($basePath, '', $data['url']); if (!$this->imageService->pathAccessible($imagePath)) { throw (new NotFoundException(trans('errors.image_not_found'))) ->setSubtitle(trans('errors.image_not_found_subtitle')) ->setDetails(trans('errors.image_not_found_details')); } return $this->imageService->streamImageFromStorageResponse('gallery', $imagePath); } /** * Update the details of an existing image in the system. * Since "image" is expected to be a file, this needs to be a 'multipart/form-data' type request if providing a * new image file. Updated image files should be of the same file type as the original image. */ public function update(Request $request, string $id) { $data = $this->validate($request, $this->rules()['update']); $image = $this->imageRepo->getById($id); $this->checkOwnablePermission(Permission::PageView, $image->getPage()); $this->checkOwnablePermission(Permission::ImageUpdate, $image); $this->imageRepo->updateImageDetails($image, $data); if (isset($data['image'])) { $this->imageRepo->updateImageFile($image, $data['image']); } return response()->json($this->formatForSingleResponse($image)); } /** * Delete an image from the system. * Will also delete thumbnails for the image. * Does not check or handle image usage so this could leave pages with broken image references. */ public function delete(string $id) { $image = $this->imageRepo->getById($id); $this->checkOwnablePermission(Permission::PageView, $image->getPage()); $this->checkOwnablePermission(Permission::ImageDelete, $image); $this->imageRepo->destroyImage($image); return response('', 204); } /** * Format the given image model for single-result display. */ protected function formatForSingleResponse(Image $image): array { $this->imageResizer->loadGalleryThumbnailsForImage($image, false); $data = $image->toArray(); $data['created_by'] = $image->createdBy; $data['updated_by'] = $image->updatedBy; $data['content'] = []; $escapedUrl = htmlentities($image->url); $escapedName = htmlentities($image->name); if ($image->type === 'drawio') { $data['content']['html'] = "<div drawio-diagram=\"{$image->id}\"><img src=\"{$escapedUrl}\"></div>"; $data['content']['markdown'] = $data['content']['html']; } else { $escapedDisplayThumb = htmlentities($image->getAttribute('thumbs')['display']); $data['content']['html'] = "<a href=\"{$escapedUrl}\" target=\"_blank\"><img src=\"{$escapedDisplayThumb}\" alt=\"{$escapedName}\"></a>"; $mdEscapedName = str_replace(']', '', str_replace('[', '', $image->name)); $mdEscapedThumb = str_replace(']', '', str_replace('[', '', $image->getAttribute('thumbs')['display'])); $data['content']['markdown'] = "![{$mdEscapedName}]({$mdEscapedThumb})"; } return $data; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Uploads/Controllers/AttachmentController.php
app/Uploads/Controllers/AttachmentController.php
<?php namespace BookStack\Uploads\Controllers; use BookStack\Entities\EntityExistsRule; use BookStack\Entities\Queries\PageQueries; use BookStack\Entities\Repos\PageRepo; use BookStack\Exceptions\FileUploadException; use BookStack\Exceptions\NotFoundException; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use BookStack\Uploads\Attachment; use BookStack\Uploads\AttachmentService; use Exception; use Illuminate\Contracts\Filesystem\FileNotFoundException; use Illuminate\Http\Request; use Illuminate\Support\MessageBag; use Illuminate\Validation\ValidationException; class AttachmentController extends Controller { public function __construct( protected AttachmentService $attachmentService, protected PageQueries $pageQueries, protected PageRepo $pageRepo ) { } /** * Endpoint at which attachments are uploaded to. * * @throws ValidationException * @throws NotFoundException */ public function upload(Request $request) { $this->validate($request, [ 'uploaded_to' => ['required', 'integer', new EntityExistsRule('page')], 'file' => array_merge(['required'], $this->attachmentService->getFileValidationRules()), ]); $pageId = $request->get('uploaded_to'); $page = $this->pageQueries->findVisibleByIdOrFail($pageId); $this->checkPermission(Permission::AttachmentCreateAll); $this->checkOwnablePermission(Permission::PageUpdate, $page); $uploadedFile = $request->file('file'); try { $attachment = $this->attachmentService->saveNewUpload($uploadedFile, $pageId); } catch (FileUploadException $e) { return response($e->getMessage(), 500); } return response()->json($attachment); } /** * Update an uploaded attachment. * * @throws ValidationException */ public function uploadUpdate(Request $request, $attachmentId) { $this->validate($request, [ 'file' => array_merge(['required'], $this->attachmentService->getFileValidationRules()), ]); /** @var Attachment $attachment */ $attachment = Attachment::query()->findOrFail($attachmentId); $this->checkOwnablePermission(Permission::PageView, $attachment->page); $this->checkOwnablePermission(Permission::PageUpdate, $attachment->page); $this->checkOwnablePermission(Permission::AttachmentUpdate, $attachment); $uploadedFile = $request->file('file'); try { $attachment = $this->attachmentService->saveUpdatedUpload($uploadedFile, $attachment); } catch (FileUploadException $e) { return response($e->getMessage(), 500); } return response()->json($attachment); } /** * Get the update form for an attachment. */ public function getUpdateForm(string $attachmentId) { /** @var Attachment $attachment */ $attachment = Attachment::query()->findOrFail($attachmentId); $this->checkOwnablePermission(Permission::PageUpdate, $attachment->page); $this->checkOwnablePermission(Permission::AttachmentCreate, $attachment); return view('attachments.manager-edit-form', [ 'attachment' => $attachment, ]); } /** * Update the details of an existing file. */ public function update(Request $request, string $attachmentId) { /** @var Attachment $attachment */ $attachment = Attachment::query()->findOrFail($attachmentId); try { $this->validate($request, [ 'attachment_edit_name' => ['required', 'string', 'min:1', 'max:255'], 'attachment_edit_url' => ['string', 'min:1', 'max:2000', 'safe_url'], ]); } catch (ValidationException $exception) { return response()->view('attachments.manager-edit-form', array_merge($request->only(['attachment_edit_name', 'attachment_edit_url']), [ 'attachment' => $attachment, 'errors' => new MessageBag($exception->errors()), ]), 422); } $this->checkOwnablePermission(Permission::PageView, $attachment->page); $this->checkOwnablePermission(Permission::PageUpdate, $attachment->page); $this->checkOwnablePermission(Permission::AttachmentUpdate, $attachment); $attachment = $this->attachmentService->updateFile($attachment, [ 'name' => $request->get('attachment_edit_name'), 'link' => $request->get('attachment_edit_url'), ]); return view('attachments.manager-edit-form', [ 'attachment' => $attachment, ]); } /** * Attach a link to a page. * * @throws NotFoundException */ public function attachLink(Request $request) { $pageId = $request->get('attachment_link_uploaded_to'); try { $this->validate($request, [ 'attachment_link_uploaded_to' => ['required', 'integer', new EntityExistsRule('page')], 'attachment_link_name' => ['required', 'string', 'min:1', 'max:255'], 'attachment_link_url' => ['required', 'string', 'min:1', 'max:2000', 'safe_url'], ]); } catch (ValidationException $exception) { return response()->view('attachments.manager-link-form', array_merge($request->only(['attachment_link_name', 'attachment_link_url']), [ 'pageId' => $pageId, 'errors' => new MessageBag($exception->errors()), ]), 422); } $page = $this->pageQueries->findVisibleByIdOrFail($pageId); $this->checkPermission(Permission::AttachmentCreateAll); $this->checkOwnablePermission(Permission::PageUpdate, $page); $attachmentName = $request->get('attachment_link_name'); $link = $request->get('attachment_link_url'); $this->attachmentService->saveNewFromLink($attachmentName, $link, intval($pageId)); return view('attachments.manager-link-form', [ 'pageId' => $pageId, ]); } /** * Get the attachments for a specific page. * * @throws NotFoundException */ public function listForPage(int $pageId) { $page = $this->pageQueries->findVisibleByIdOrFail($pageId); return view('attachments.manager-list', [ 'attachments' => $page->attachments->all(), ]); } /** * Update the attachment sorting. * * @throws ValidationException * @throws NotFoundException */ public function sortForPage(Request $request, int $pageId) { $this->validate($request, [ 'order' => ['required', 'array'], ]); $page = $this->pageQueries->findVisibleByIdOrFail($pageId); $this->checkOwnablePermission(Permission::PageUpdate, $page); $attachmentOrder = $request->get('order'); $this->attachmentService->updateFileOrderWithinPage($attachmentOrder, $pageId); return response()->json(['message' => trans('entities.attachments_order_updated')]); } /** * Get an attachment from storage. * * @throws FileNotFoundException * @throws NotFoundException */ public function get(Request $request, string $attachmentId) { /** @var Attachment $attachment */ $attachment = Attachment::query()->findOrFail($attachmentId); try { $page = $this->pageQueries->findVisibleByIdOrFail($attachment->uploaded_to); } catch (NotFoundException $exception) { throw new NotFoundException(trans('errors.attachment_not_found')); } $this->checkOwnablePermission(Permission::PageView, $page); if ($attachment->external) { return redirect($attachment->path); } $fileName = $attachment->getFileName(); $attachmentStream = $this->attachmentService->streamAttachmentFromStorage($attachment); $attachmentSize = $this->attachmentService->getAttachmentFileSize($attachment); if ($request->get('open') === 'true') { return $this->download()->streamedInline($attachmentStream, $fileName, $attachmentSize); } return $this->download()->streamedDirectly($attachmentStream, $fileName, $attachmentSize); } /** * Delete a specific attachment in the system. * * @throws Exception */ public function delete(string $attachmentId) { /** @var Attachment $attachment */ $attachment = Attachment::query()->findOrFail($attachmentId); $this->checkOwnablePermission(Permission::AttachmentDelete, $attachment); $this->attachmentService->deleteFile($attachment); return response()->json(['message' => trans('entities.attachments_deleted')]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Theming/CustomHtmlHeadContentProvider.php
app/Theming/CustomHtmlHeadContentProvider.php
<?php namespace BookStack\Theming; use BookStack\Util\CspService; use BookStack\Util\HtmlContentFilter; use BookStack\Util\HtmlNonceApplicator; use Illuminate\Contracts\Cache\Repository as Cache; class CustomHtmlHeadContentProvider { /** * @var CspService */ protected $cspService; /** * @var Cache */ protected $cache; public function __construct(CspService $cspService, Cache $cache) { $this->cspService = $cspService; $this->cache = $cache; } /** * Fetch our custom HTML head content prepared for use on web pages. * Content has a nonce applied for CSP. */ public function forWeb(): string { $content = $this->getSourceContent(); $hash = md5($content); $html = $this->cache->remember('custom-head-web:' . $hash, 86400, function () use ($content) { return HtmlNonceApplicator::prepare($content); }); return HtmlNonceApplicator::apply($html, $this->cspService->getNonce()); } /** * Fetch our custom HTML head content prepared for use in export formats. * Scripts are stripped to avoid potential issues. */ public function forExport(): string { $content = $this->getSourceContent(); $hash = md5($content); return $this->cache->remember('custom-head-export:' . $hash, 86400, function () use ($content) { return HtmlContentFilter::removeScriptsFromHtmlString($content); }); } /** * Get the original custom head content to use. */ protected function getSourceContent(): string { return setting('app-custom-head', ''); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Theming/ThemeController.php
app/Theming/ThemeController.php
<?php namespace BookStack\Theming; use BookStack\Facades\Theme; use BookStack\Http\Controller; use BookStack\Util\FilePathNormalizer; class ThemeController extends Controller { /** * Serve a public file from the configured theme. */ public function publicFile(string $theme, string $path) { $cleanPath = FilePathNormalizer::normalize($path); if ($theme !== Theme::getTheme() || !$cleanPath) { abort(404); } $filePath = theme_path("public/{$cleanPath}"); if (!file_exists($filePath)) { abort(404); } $response = $this->download()->streamedFileInline($filePath); $response->setMaxAge(86400); return $response; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Theming/ThemeService.php
app/Theming/ThemeService.php
<?php namespace BookStack\Theming; use BookStack\Access\SocialDriverManager; use BookStack\Exceptions\ThemeException; use Illuminate\Console\Application; use Illuminate\Console\Application as Artisan; use Symfony\Component\Console\Command\Command; class ThemeService { /** * @var array<string, callable[]> */ protected array $listeners = []; /** * Get the currently configured theme. * Returns an empty string if not configured. */ public function getTheme(): string { return config('view.theme') ?? ''; } /** * Listen to a given custom theme event, * setting up the action to be ran when the event occurs. */ public function listen(string $event, callable $action): void { if (!isset($this->listeners[$event])) { $this->listeners[$event] = []; } $this->listeners[$event][] = $action; } /** * Dispatch the given event name. * Runs any registered listeners for that event name, * passing all additional variables to the listener action. * * If a callback returns a non-null value, this method will * stop and return that value itself. */ public function dispatch(string $event, ...$args): mixed { foreach ($this->listeners[$event] ?? [] as $action) { $result = call_user_func_array($action, $args); if (!is_null($result)) { return $result; } } return null; } /** * Check if there are listeners registered for the given event name. */ public function hasListeners(string $event): bool { return count($this->listeners[$event] ?? []) > 0; } /** * Register a new custom artisan command to be available. */ public function registerCommand(Command $command): void { Artisan::starting(function (Application $application) use ($command) { $application->addCommands([$command]); }); } /** * Read any actions from the set theme path if the 'functions.php' file exists. */ public function readThemeActions(): void { $themeActionsFile = theme_path('functions.php'); if ($themeActionsFile && file_exists($themeActionsFile)) { try { require $themeActionsFile; } catch (\Error $exception) { throw new ThemeException("Failed loading theme functions file at \"{$themeActionsFile}\" with error: {$exception->getMessage()}"); } } } /** * @see SocialDriverManager::addSocialDriver */ public function addSocialDriver(string $driverName, array $config, string $socialiteHandler, ?callable $configureForRedirect = null): void { $driverManager = app()->make(SocialDriverManager::class); $driverManager->addSocialDriver($driverName, $config, $socialiteHandler, $configureForRedirect); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Theming/ThemeEvents.php
app/Theming/ThemeEvents.php
<?php namespace BookStack\Theming; /** * The ThemeEvents used within BookStack. * * This file details the events that BookStack may fire via the custom * theme system, including event names, parameters and expected return types. * * This system is regarded as semi-stable. * We'll look to fix issues with it or migrate old event types but * events and their signatures may change in new versions of BookStack. * We'd advise testing any usage of these events upon upgrade. */ class ThemeEvents { /** * Activity logged event. * Runs right after an activity is logged by bookstack. * These are the activities that can be seen in the audit log area of BookStack. * Activity types can be seen listed in the \BookStack\Actions\ActivityType class. * The provided $detail can be a string or a loggable type of model. You should check * the type before making use of this parameter. * * @param string $type * @param string|\BookStack\Activity\Models\Loggable $detail */ const ACTIVITY_LOGGED = 'activity_logged'; /** * Application boot-up. * After main services are registered. * * @param \BookStack\App\Application $app */ const APP_BOOT = 'app_boot'; /** * Auth login event. * Runs right after a user is logged-in to the application by any authentication * system as a standard app user. This includes a user becoming logged in * after registration. This is not emitted upon API usage. * * @param string $authSystem * @param \BookStack\Users\Models\User $user */ const AUTH_LOGIN = 'auth_login'; /** * Auth pre-register event. * Runs right before a new user account is registered in the system by any authentication * system as a standard app user including auto-registration systems used by LDAP, * SAML, OIDC and social systems. It only includes self-registrations, * not accounts created by others in the UI or via the REST API. * It runs after any other normal validation steps. * Any account/email confirmation occurs post-registration. * The provided $userData contains the main details that would be used to create * the account, and may depend on authentication method. * If false is returned from the event, registration will be prevented and the user * will be returned to the login page. * * @param string $authSystem * @param array $userData * @return bool|null */ const AUTH_PRE_REGISTER = 'auth_pre_register'; /** * Auth register event. * Runs right after a user is newly registered to the application by any authentication * system as a standard app user. This includes auto-registration systems used * by LDAP, SAML, OIDC and social systems. It only includes self-registrations. * * @param string $authSystem * @param \BookStack\Users\Models\User $user */ const AUTH_REGISTER = 'auth_register'; /** * Commonmark environment configure. * Provides the commonmark library environment for customization before it's used to render markdown content. * If the listener returns a non-null value, that will be used as an environment instead. * * @param \League\CommonMark\Environment\Environment $environment * @return \League\CommonMark\Environment\Environment|null */ const COMMONMARK_ENVIRONMENT_CONFIGURE = 'commonmark_environment_configure'; /** * OIDC ID token pre-validate event. * Runs just before BookStack validates the user ID token data upon login. * Provides the existing found set of claims for the user as a key-value array, * along with an array of the proceeding access token data provided by the identity platform. * If the listener returns a non-null value, that will replace the existing ID token claim data. * * @param array $idTokenData * @param array $accessTokenData * @return array|null */ const OIDC_ID_TOKEN_PRE_VALIDATE = 'oidc_id_token_pre_validate'; /** * Page include parse event. * Runs when a page include tag is being parsed, typically when page content is being processed for viewing. * Provides the "include tag" reference string, the default BookStack replacement content for the tag, * the current page being processed, and the page that's being referenced by the include tag. * The referenced page may be null where the page does not exist or where permissions prevent visibility. * If the listener returns a non-null value, that will be used as the replacement HTML content instead. * * @param string $tagReference * @param string $replacementHTML * @param \BookStack\Entities\Models\Page $currentPage * @param ?\BookStack\Entities\Models\Page $referencedPage */ const PAGE_INCLUDE_PARSE = 'page_include_parse'; /** * Routes register web event. * Called when standard web (browser/non-api) app routes are registered. * Provides an app router, so you can register your own web routes. * * @param \Illuminate\Routing\Router $router */ const ROUTES_REGISTER_WEB = 'routes_register_web'; /** * Routes register web auth event. * Called when auth-required web (browser/non-api) app routes can be registered. * These are routes that typically require login to access (unless the instance is made public). * Provides an app router, so you can register your own web routes. * * @param \Illuminate\Routing\Router $router */ const ROUTES_REGISTER_WEB_AUTH = 'routes_register_web_auth'; /** * Web before middleware action. * Runs before the request is handled but after all other middleware apart from those * that depend on the current session user (Localization for example). * Provides the original request to use. * Return values, if provided, will be used as a new response to use. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response|null */ const WEB_MIDDLEWARE_BEFORE = 'web_middleware_before'; /** * Web after middleware action. * Runs after the request is handled but before the response is sent. * Provides both the original request and the currently resolved response. * Return values, if provided, will be used as a new response to use. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\BinaryFileResponse $response * @return \Illuminate\Http\Response|null */ const WEB_MIDDLEWARE_AFTER = 'web_middleware_after'; /** * Webhook call before event. * Runs before a webhook endpoint is called. Allows for customization * of the data format & content within the webhook POST request. * Provides the original event name as a string (see \BookStack\Actions\ActivityType) * along with the webhook instance along with the event detail which may be a * "Loggable" model type or a string. * If the listener returns a non-null value, that will be used as the POST data instead * of the system default. * * @param string $event * @param \BookStack\Activity\Models\Webhook $webhook * @param string|\BookStack\Activity\Models\Loggable $detail * @param \BookStack\Users\Models\User $initiator * @param int $initiatedTime * @return array|null */ const WEBHOOK_CALL_BEFORE = 'webhook_call_before'; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/EntityExistsRule.php
app/Entities/EntityExistsRule.php
<?php namespace BookStack\Entities; use Illuminate\Validation\Rules\Exists; class EntityExistsRule implements \Stringable { public function __construct( protected string $type, ) { } public function __toString() { $existsRule = (new Exists('entities', 'id')) ->where('type', $this->type); return $existsRule->__toString(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/EntityProvider.php
app/Entities/EntityProvider.php
<?php namespace BookStack\Entities; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\Page; use BookStack\Entities\Models\PageRevision; /** * Class EntityProvider. * * Provides access to the core entity models. * Wrapped up in this provider since they are often used together * so this is a neater alternative to injecting all in individually. */ class EntityProvider { public Bookshelf $bookshelf; public Book $book; public Chapter $chapter; public Page $page; public PageRevision $pageRevision; public function __construct() { $this->bookshelf = new Bookshelf(); $this->book = new Book(); $this->chapter = new Chapter(); $this->page = new Page(); $this->pageRevision = new PageRevision(); } /** * Fetch all core entity types as an associated array * with their basic names as the keys. * * @return array<string, Entity> */ public function all(): array { return [ 'bookshelf' => $this->bookshelf, 'book' => $this->book, 'chapter' => $this->chapter, 'page' => $this->page, ]; } /** * Get an entity instance by its basic name. */ public function get(string $type): Entity { $type = strtolower($type); $instance = $this->all()[$type] ?? null; if (is_null($instance)) { throw new \InvalidArgumentException("Provided type \"{$type}\" is not a valid entity type"); } return $instance; } /** * Get the morph classes, as an array, for a single or multiple types. */ public function getMorphClasses(array $types): array { $morphClasses = []; foreach ($types as $type) { $model = $this->get($type); $morphClasses[] = $model->getMorphClass(); } return $morphClasses; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/BreadcrumbsViewComposer.php
app/Entities/BreadcrumbsViewComposer.php
<?php namespace BookStack\Entities; use BookStack\Entities\Models\Book; use BookStack\Entities\Tools\ShelfContext; use Illuminate\View\View; class BreadcrumbsViewComposer { public function __construct( protected ShelfContext $shelfContext ) { } /** * Modify data when the view is composed. */ public function compose(View $view): void { $crumbs = $view->getData()['crumbs']; $firstCrumb = $crumbs[0] ?? null; if ($firstCrumb instanceof Book) { $shelf = $this->shelfContext->getContextualShelfForBook($firstCrumb); if ($shelf) { array_unshift($crumbs, $shelf); $view->with('crumbs', $crumbs); } } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Controllers/BookApiController.php
app/Entities/Controllers/BookApiController.php
<?php namespace BookStack\Entities\Controllers; use BookStack\Api\ApiEntityListFormatter; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Entity; use BookStack\Entities\Queries\BookQueries; use BookStack\Entities\Queries\PageQueries; use BookStack\Entities\Repos\BookRepo; use BookStack\Entities\Tools\BookContents; use BookStack\Http\ApiController; use BookStack\Permissions\Permission; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; class BookApiController extends ApiController { public function __construct( protected BookRepo $bookRepo, protected BookQueries $queries, protected PageQueries $pageQueries, ) { } /** * Get a listing of books visible to the user. */ public function list() { $books = $this->queries ->visibleForList() ->with(['cover:id,name,url']) ->addSelect(['created_by', 'updated_by']); return $this->apiListingResponse($books, [ 'id', 'name', 'slug', 'description', 'created_at', 'updated_at', 'created_by', 'updated_by', 'owned_by', ]); } /** * Create a new book in the system. * The cover image of a book can be set by sending a file via an 'image' property within a 'multipart/form-data' request. * If the 'image' property is null then the book cover image will be removed. * * @throws ValidationException */ public function create(Request $request) { $this->checkPermission(Permission::BookCreateAll); $requestData = $this->validate($request, $this->rules()['create']); $book = $this->bookRepo->create($requestData); return response()->json($this->forJsonDisplay($book)); } /** * View the details of a single book. * The response data will contain a 'content' property listing the chapter and pages directly within, in * the same structure as you'd see within the BookStack interface when viewing a book. Top-level * contents will have a 'type' property to distinguish between pages & chapters. */ public function read(string $id) { $book = $this->queries->findVisibleByIdOrFail(intval($id)); $book = $this->forJsonDisplay($book); $book->load(['createdBy', 'updatedBy', 'ownedBy']); $contents = (new BookContents($book))->getTree(true, false)->all(); $contentsApiData = (new ApiEntityListFormatter($contents)) ->withType() ->withField('pages', function (Entity $entity) { if ($entity instanceof Chapter) { $pages = $this->pageQueries->visibleForChapterList($entity->id)->get()->all(); return (new ApiEntityListFormatter($pages))->format(); } return null; })->format(); $book->setAttribute('contents', $contentsApiData); return response()->json($book); } /** * Update the details of a single book. * The cover image of a book can be set by sending a file via an 'image' property within a 'multipart/form-data' request. * If the 'image' property is null then the book cover image will be removed. * * @throws ValidationException */ public function update(Request $request, string $id) { $book = $this->queries->findVisibleByIdOrFail(intval($id)); $this->checkOwnablePermission(Permission::BookUpdate, $book); $requestData = $this->validate($request, $this->rules()['update']); $book = $this->bookRepo->update($book, $requestData); return response()->json($this->forJsonDisplay($book)); } /** * Delete a single book. * This will typically send the book to the recycle bin. * * @throws \Exception */ public function delete(string $id) { $book = $this->queries->findVisibleByIdOrFail(intval($id)); $this->checkOwnablePermission(Permission::BookDelete, $book); $this->bookRepo->destroy($book); return response('', 204); } protected function forJsonDisplay(Book $book): Book { $book = clone $book; $book->unsetRelations()->refresh(); $book->load(['tags']); $book->makeVisible(['cover', 'description_html']) ->setAttribute('description_html', $book->descriptionInfo()->getHtml()) ->setAttribute('cover', $book->coverInfo()->getImage()); return $book; } protected function rules(): array { return [ 'create' => [ 'name' => ['required', 'string', 'max:255'], 'description' => ['string', 'max:1900'], 'description_html' => ['string', 'max:2000'], 'tags' => ['array'], 'image' => array_merge(['nullable'], $this->getImageValidationRules()), 'default_template_id' => ['nullable', 'integer'], ], 'update' => [ 'name' => ['string', 'min:1', 'max:255'], 'description' => ['string', 'max:1900'], 'description_html' => ['string', 'max:2000'], 'tags' => ['array'], 'image' => array_merge(['nullable'], $this->getImageValidationRules()), 'default_template_id' => ['nullable', 'integer'], ], ]; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Controllers/PageRevisionController.php
app/Entities/Controllers/PageRevisionController.php
<?php namespace BookStack\Entities\Controllers; use BookStack\Activity\ActivityType; use BookStack\Entities\Models\PageRevision; use BookStack\Entities\Queries\PageQueries; use BookStack\Entities\Repos\PageRepo; use BookStack\Entities\Repos\RevisionRepo; use BookStack\Entities\Tools\PageContent; use BookStack\Exceptions\NotFoundException; use BookStack\Facades\Activity; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use BookStack\Util\SimpleListOptions; use Illuminate\Http\Request; use Ssddanbrown\HtmlDiff\Diff; class PageRevisionController extends Controller { public function __construct( protected PageRepo $pageRepo, protected PageQueries $pageQueries, protected RevisionRepo $revisionRepo, ) { } /** * Shows the last revisions for this page. * * @throws NotFoundException */ public function index(Request $request, string $bookSlug, string $pageSlug) { $page = $this->pageQueries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $listOptions = SimpleListOptions::fromRequest($request, 'page_revisions', true)->withSortOptions([ 'id' => trans('entities.pages_revisions_sort_number') ]); $revisions = $page->revisions()->select([ 'id', 'page_id', 'name', 'created_at', 'created_by', 'updated_at', 'type', 'revision_number', 'summary', ]) ->selectRaw("IF(markdown = '', false, true) as is_markdown") ->with(['page.book', 'createdBy']) ->reorder('id', $listOptions->getOrder()) ->paginate(50); $this->setPageTitle(trans('entities.pages_revisions_named', ['pageName' => $page->getShortName()])); return view('pages.revisions', [ 'revisions' => $revisions, 'page' => $page, 'listOptions' => $listOptions, 'oldestRevisionId' => $page->revisions()->min('id'), ]); } /** * Shows a preview of a single revision. * * @throws NotFoundException */ public function show(string $bookSlug, string $pageSlug, int $revisionId) { $page = $this->pageQueries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); /** @var ?PageRevision $revision */ $revision = $page->revisions()->where('id', '=', $revisionId)->first(); if ($revision === null) { throw new NotFoundException(); } $page->fill($revision->toArray()); // TODO - Refactor PageContent so we don't need to juggle this $page->html = $revision->html; $page->html = (new PageContent($page))->render(); $this->setPageTitle(trans('entities.pages_revision_named', ['pageName' => $page->getShortName()])); return view('pages.revision', [ 'page' => $page, 'book' => $page->book, 'diff' => null, 'revision' => $revision, ]); } /** * Shows the changes of a single revision. * * @throws NotFoundException */ public function changes(string $bookSlug, string $pageSlug, int $revisionId) { $page = $this->pageQueries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); /** @var ?PageRevision $revision */ $revision = $page->revisions()->where('id', '=', $revisionId)->first(); if ($revision === null) { throw new NotFoundException(); } $prev = $revision->getPreviousRevision(); $prevContent = $prev->html ?? ''; $diff = Diff::excecute($prevContent, $revision->html); $page->fill($revision->toArray()); // TODO - Refactor PageContent so we don't need to juggle this $page->html = $revision->html; $page->html = (new PageContent($page))->render(); $this->setPageTitle(trans('entities.pages_revision_named', ['pageName' => $page->getShortName()])); return view('pages.revision', [ 'page' => $page, 'book' => $page->book, 'diff' => $diff, 'revision' => $revision, ]); } /** * Restores a page using the content of the specified revision. * * @throws NotFoundException */ public function restore(string $bookSlug, string $pageSlug, int $revisionId) { $page = $this->pageQueries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $this->checkOwnablePermission(Permission::PageUpdate, $page); $page = $this->pageRepo->restoreRevision($page, $revisionId); return redirect($page->getUrl()); } /** * Deletes a revision using the id of the specified revision. * * @throws NotFoundException */ public function destroy(string $bookSlug, string $pageSlug, int $revId) { $page = $this->pageQueries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $this->checkOwnablePermission(Permission::PageDelete, $page); $revision = $page->revisions()->where('id', '=', $revId)->first(); if ($revision === null) { throw new NotFoundException("Revision #{$revId} not found"); } // Check if it's the latest revision, cannot delete the latest revision. if (intval($page->currentRevision->id ?? null) === intval($revId)) { $this->showErrorNotification(trans('entities.revision_cannot_delete_latest')); return redirect($page->getUrl('/revisions')); } $revision->delete(); Activity::add(ActivityType::REVISION_DELETE, $revision); return redirect($page->getUrl('/revisions')); } /** * Destroys existing drafts, belonging to the current user, for the given page. */ public function destroyUserDraft(string $pageId) { $page = $this->pageQueries->findVisibleByIdOrFail($pageId); $this->revisionRepo->deleteDraftsForCurrentUser($page); return response('', 200); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Controllers/BookshelfApiController.php
app/Entities/Controllers/BookshelfApiController.php
<?php namespace BookStack\Entities\Controllers; use BookStack\Entities\Models\Bookshelf; use BookStack\Entities\Queries\BookshelfQueries; use BookStack\Entities\Repos\BookshelfRepo; use BookStack\Http\ApiController; use BookStack\Permissions\Permission; use Exception; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; class BookshelfApiController extends ApiController { public function __construct( protected BookshelfRepo $bookshelfRepo, protected BookshelfQueries $queries, ) { } /** * Get a listing of shelves visible to the user. */ public function list() { $shelves = $this->queries ->visibleForList() ->with(['cover:id,name,url']) ->addSelect(['created_by', 'updated_by']); return $this->apiListingResponse($shelves, [ 'id', 'name', 'slug', 'description', 'created_at', 'updated_at', 'created_by', 'updated_by', 'owned_by', ]); } /** * Create a new shelf in the system. * An array of books IDs can be provided in the request. These * will be added to the shelf in the same order as provided. * The cover image of a shelf can be set by sending a file via an 'image' property within a 'multipart/form-data' request. * If the 'image' property is null then the shelf cover image will be removed. * * @throws ValidationException */ public function create(Request $request) { $this->checkPermission(Permission::BookshelfCreateAll); $requestData = $this->validate($request, $this->rules()['create']); $bookIds = $request->get('books', []); $shelf = $this->bookshelfRepo->create($requestData, $bookIds); return response()->json($this->forJsonDisplay($shelf)); } /** * View the details of a single shelf. */ public function read(string $id) { $shelf = $this->queries->findVisibleByIdOrFail(intval($id)); $shelf = $this->forJsonDisplay($shelf); $shelf->load([ 'createdBy', 'updatedBy', 'ownedBy', 'books' => function (BelongsToMany $query) { $query->scopes('visible')->get(['id', 'name', 'slug']); }, ]); return response()->json($shelf); } /** * Update the details of a single shelf. * An array of books IDs can be provided in the request. These * will be added to the shelf in the same order as provided and overwrite * any existing book assignments. * The cover image of a shelf can be set by sending a file via an 'image' property within a 'multipart/form-data' request. * If the 'image' property is null then the shelf cover image will be removed. * * @throws ValidationException */ public function update(Request $request, string $id) { $shelf = $this->queries->findVisibleByIdOrFail(intval($id)); $this->checkOwnablePermission(Permission::BookshelfUpdate, $shelf); $requestData = $this->validate($request, $this->rules()['update']); $bookIds = $request->get('books', null); $shelf = $this->bookshelfRepo->update($shelf, $requestData, $bookIds); return response()->json($this->forJsonDisplay($shelf)); } /** * Delete a single shelf. * This will typically send the shelf to the recycle bin. * * @throws Exception */ public function delete(string $id) { $shelf = $this->queries->findVisibleByIdOrFail(intval($id)); $this->checkOwnablePermission(Permission::BookshelfDelete, $shelf); $this->bookshelfRepo->destroy($shelf); return response('', 204); } protected function forJsonDisplay(Bookshelf $shelf): Bookshelf { $shelf = clone $shelf; $shelf->unsetRelations()->refresh(); $shelf->load(['tags']); $shelf->makeVisible(['cover', 'description_html']) ->setAttribute('description_html', $shelf->descriptionInfo()->getHtml()) ->setAttribute('cover', $shelf->coverInfo()->getImage()); return $shelf; } protected function rules(): array { return [ 'create' => [ 'name' => ['required', 'string', 'max:255'], 'description' => ['string', 'max:1900'], 'description_html' => ['string', 'max:2000'], 'books' => ['array'], 'tags' => ['array'], 'image' => array_merge(['nullable'], $this->getImageValidationRules()), ], 'update' => [ 'name' => ['string', 'min:1', 'max:255'], 'description' => ['string', 'max:1900'], 'description_html' => ['string', 'max:2000'], 'books' => ['array'], 'tags' => ['array'], 'image' => array_merge(['nullable'], $this->getImageValidationRules()), ], ]; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Controllers/ChapterApiController.php
app/Entities/Controllers/ChapterApiController.php
<?php namespace BookStack\Entities\Controllers; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Queries\ChapterQueries; use BookStack\Entities\Queries\EntityQueries; use BookStack\Entities\Repos\ChapterRepo; use BookStack\Exceptions\PermissionsException; use BookStack\Http\ApiController; use BookStack\Permissions\Permission; use Exception; use Illuminate\Http\Request; class ChapterApiController extends ApiController { protected array $rules = [ 'create' => [ 'book_id' => ['required', 'integer'], 'name' => ['required', 'string', 'max:255'], 'description' => ['string', 'max:1900'], 'description_html' => ['string', 'max:2000'], 'tags' => ['array'], 'priority' => ['integer'], 'default_template_id' => ['nullable', 'integer'], ], 'update' => [ 'book_id' => ['integer'], 'name' => ['string', 'min:1', 'max:255'], 'description' => ['string', 'max:1900'], 'description_html' => ['string', 'max:2000'], 'tags' => ['array'], 'priority' => ['integer'], 'default_template_id' => ['nullable', 'integer'], ], ]; public function __construct( protected ChapterRepo $chapterRepo, protected ChapterQueries $queries, protected EntityQueries $entityQueries, ) { } /** * Get a listing of chapters visible to the user. */ public function list() { $chapters = $this->queries->visibleForList() ->addSelect(['created_by', 'updated_by']); return $this->apiListingResponse($chapters, [ 'id', 'book_id', 'name', 'slug', 'description', 'priority', 'created_at', 'updated_at', 'created_by', 'updated_by', 'owned_by', ]); } /** * Create a new chapter in the system. */ public function create(Request $request) { $requestData = $this->validate($request, $this->rules['create']); $bookId = $request->get('book_id'); $book = $this->entityQueries->books->findVisibleByIdOrFail(intval($bookId)); $this->checkOwnablePermission(Permission::ChapterCreate, $book); $chapter = $this->chapterRepo->create($requestData, $book); return response()->json($this->forJsonDisplay($chapter)); } /** * View the details of a single chapter. */ public function read(string $id) { $chapter = $this->queries->findVisibleByIdOrFail(intval($id)); $chapter = $this->forJsonDisplay($chapter); $chapter->load(['createdBy', 'updatedBy', 'ownedBy']); // Note: More fields than usual here, for backwards compatibility, // due to previously accidentally including more fields that desired. $pages = $this->entityQueries->pages->visibleForChapterList($chapter->id) ->addSelect(['created_by', 'updated_by', 'revision_count', 'editor']) ->get(); $chapter->setRelation('pages', $pages); return response()->json($chapter); } /** * Update the details of a single chapter. * Providing a 'book_id' property will essentially move the chapter * into that parent element if you have permissions to do so. */ public function update(Request $request, string $id) { $requestData = $this->validate($request, $this->rules()['update']); $chapter = $this->queries->findVisibleByIdOrFail(intval($id)); $this->checkOwnablePermission(Permission::ChapterUpdate, $chapter); if ($request->has('book_id') && $chapter->book_id !== (intval($requestData['book_id']) ?: null)) { $this->checkOwnablePermission(Permission::ChapterDelete, $chapter); try { $this->chapterRepo->move($chapter, "book:{$requestData['book_id']}"); } catch (Exception $exception) { if ($exception instanceof PermissionsException) { $this->showPermissionError(); } return $this->jsonError(trans('errors.selected_book_not_found')); } } $updatedChapter = $this->chapterRepo->update($chapter, $requestData); return response()->json($this->forJsonDisplay($updatedChapter)); } /** * Delete a chapter. * This will typically send the chapter to the recycle bin. */ public function delete(string $id) { $chapter = $this->queries->findVisibleByIdOrFail(intval($id)); $this->checkOwnablePermission(Permission::ChapterDelete, $chapter); $this->chapterRepo->destroy($chapter); return response('', 204); } protected function forJsonDisplay(Chapter $chapter): Chapter { $chapter = clone $chapter; $chapter->unsetRelations()->refresh(); $chapter->load(['tags']); $chapter->makeVisible('description_html'); $chapter->setAttribute('description_html', $chapter->descriptionInfo()->getHtml()); /** @var Book $book */ $book = $chapter->book()->first(); $chapter->setAttribute('book_slug', $book->slug); return $chapter; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Controllers/RecycleBinController.php
app/Entities/Controllers/RecycleBinController.php
<?php namespace BookStack\Entities\Controllers; use BookStack\Activity\ActivityType; use BookStack\Entities\Models\Deletion; use BookStack\Entities\Models\Entity; use BookStack\Entities\Repos\DeletionRepo; use BookStack\Entities\Tools\TrashCan; use BookStack\Http\Controller; use BookStack\Permissions\Permission; class RecycleBinController extends Controller { protected string $recycleBinBaseUrl = '/settings/recycle-bin'; /** * On each request to a method of this controller check permissions * using a middleware closure. */ public function __construct() { $this->middleware(function ($request, $next) { $this->checkPermission(Permission::SettingsManage); $this->checkPermission(Permission::RestrictionsManageAll); return $next($request); }); } /** * Show the top-level listing for the recycle bin. */ public function index() { $deletions = Deletion::query()->with(['deletable', 'deleter'])->paginate(10); $this->setPageTitle(trans('settings.recycle_bin')); return view('settings.recycle-bin.index', [ 'deletions' => $deletions, ]); } /** * Show the page to confirm a restore of the deletion of the given id. */ public function showRestore(string $id) { /** @var Deletion $deletion */ $deletion = Deletion::query()->findOrFail($id); // Walk the parent chain to find any cascading parent deletions $currentDeletable = $deletion->deletable; $searching = true; while ($searching && $currentDeletable instanceof Entity) { $parent = $currentDeletable->getParent(); if ($parent && $parent->trashed()) { $currentDeletable = $parent; } else { $searching = false; } } /** @var ?Deletion $parentDeletion */ $parentDeletion = ($currentDeletable === $deletion->deletable) ? null : $currentDeletable->deletions()->first(); return view('settings.recycle-bin.restore', [ 'deletion' => $deletion, 'parentDeletion' => $parentDeletion, ]); } /** * Restore the element attached to the given deletion. * * @throws \Exception */ public function restore(DeletionRepo $deletionRepo, string $id) { $restoreCount = $deletionRepo->restore((int) $id); $this->showSuccessNotification(trans('settings.recycle_bin_restore_notification', ['count' => $restoreCount])); return redirect($this->recycleBinBaseUrl); } /** * Show the page to confirm a Permanent deletion of the element attached to the deletion of the given id. */ public function showDestroy(string $id) { /** @var Deletion $deletion */ $deletion = Deletion::query()->findOrFail($id); return view('settings.recycle-bin.destroy', [ 'deletion' => $deletion, ]); } /** * Permanently delete the content associated with the given deletion. * * @throws \Exception */ public function destroy(DeletionRepo $deletionRepo, string $id) { $deleteCount = $deletionRepo->destroy((int) $id); $this->showSuccessNotification(trans('settings.recycle_bin_destroy_notification', ['count' => $deleteCount])); return redirect($this->recycleBinBaseUrl); } /** * Empty out the recycle bin. * * @throws \Exception */ public function empty(TrashCan $trash) { $deleteCount = $trash->empty(); $this->logActivity(ActivityType::RECYCLE_BIN_EMPTY); $this->showSuccessNotification(trans('settings.recycle_bin_destroy_notification', ['count' => $deleteCount])); return redirect($this->recycleBinBaseUrl); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Controllers/BookController.php
app/Entities/Controllers/BookController.php
<?php namespace BookStack\Entities\Controllers; use BookStack\Activity\ActivityQueries; use BookStack\Activity\ActivityType; use BookStack\Activity\Models\View; use BookStack\Activity\Tools\UserEntityWatchOptions; use BookStack\Entities\Queries\BookQueries; use BookStack\Entities\Queries\BookshelfQueries; use BookStack\Entities\Queries\EntityQueries; use BookStack\Entities\Repos\BookRepo; use BookStack\Entities\Tools\BookContents; use BookStack\Entities\Tools\Cloner; use BookStack\Entities\Tools\HierarchyTransformer; use BookStack\Entities\Tools\ShelfContext; use BookStack\Exceptions\ImageUploadException; use BookStack\Exceptions\NotFoundException; use BookStack\Facades\Activity; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use BookStack\References\ReferenceFetcher; use BookStack\Util\DatabaseTransaction; use BookStack\Util\SimpleListOptions; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; use Throwable; class BookController extends Controller { public function __construct( protected ShelfContext $shelfContext, protected BookRepo $bookRepo, protected BookQueries $queries, protected EntityQueries $entityQueries, protected BookshelfQueries $shelfQueries, protected ReferenceFetcher $referenceFetcher, ) { } /** * Display a listing of the book. */ public function index(Request $request) { $view = setting()->getForCurrentUser('books_view_type'); $listOptions = SimpleListOptions::fromRequest($request, 'books')->withSortOptions([ 'name' => trans('common.sort_name'), 'created_at' => trans('common.sort_created_at'), 'updated_at' => trans('common.sort_updated_at'), ]); $books = $this->queries->visibleForListWithCover() ->orderBy($listOptions->getSort(), $listOptions->getOrder()) ->paginate(setting()->getInteger('lists-page-count-books', 18, 1, 1000)); $recents = $this->isSignedIn() ? $this->queries->recentlyViewedForCurrentUser()->take(4)->get() : false; $popular = $this->queries->popularForList()->take(4)->get(); $new = $this->queries->visibleForList()->orderBy('created_at', 'desc')->take(4)->get(); $this->shelfContext->clearShelfContext(); $this->setPageTitle(trans('entities.books')); return view('books.index', [ 'books' => $books, 'recents' => $recents, 'popular' => $popular, 'new' => $new, 'view' => $view, 'listOptions' => $listOptions, ]); } /** * Show the form for creating a new book. */ public function create(?string $shelfSlug = null) { $this->checkPermission(Permission::BookCreateAll); $bookshelf = null; if ($shelfSlug !== null) { $bookshelf = $this->shelfQueries->findVisibleBySlugOrFail($shelfSlug); $this->checkOwnablePermission(Permission::BookshelfUpdate, $bookshelf); } $this->setPageTitle(trans('entities.books_create')); return view('books.create', [ 'bookshelf' => $bookshelf, ]); } /** * Store a newly created book in storage. * * @throws ImageUploadException * @throws ValidationException */ public function store(Request $request, ?string $shelfSlug = null) { $this->checkPermission(Permission::BookCreateAll); $validated = $this->validate($request, [ 'name' => ['required', 'string', 'max:255'], 'description_html' => ['string', 'max:2000'], 'image' => array_merge(['nullable'], $this->getImageValidationRules()), 'tags' => ['array'], 'default_template_id' => ['nullable', 'integer'], ]); $bookshelf = null; if ($shelfSlug !== null) { $bookshelf = $this->shelfQueries->findVisibleBySlugOrFail($shelfSlug); $this->checkOwnablePermission(Permission::BookshelfUpdate, $bookshelf); } $book = $this->bookRepo->create($validated); if ($bookshelf) { $bookshelf->appendBook($book); Activity::add(ActivityType::BOOKSHELF_UPDATE, $bookshelf); } return redirect($book->getUrl()); } /** * Display the specified book. */ public function show(Request $request, ActivityQueries $activities, string $slug) { try { $book = $this->queries->findVisibleBySlugOrFail($slug); } catch (NotFoundException $exception) { $book = $this->entityQueries->findVisibleByOldSlugs('book', $slug); if (is_null($book)) { throw $exception; } return redirect($book->getUrl()); } $bookChildren = (new BookContents($book))->getTree(true); $bookParentShelves = $book->shelves()->scopes('visible')->get(); View::incrementFor($book); if ($request->has('shelf')) { $this->shelfContext->setShelfContext(intval($request->get('shelf'))); } $this->setPageTitle($book->getShortName()); return view('books.show', [ 'book' => $book, 'current' => $book, 'bookChildren' => $bookChildren, 'bookParentShelves' => $bookParentShelves, 'watchOptions' => new UserEntityWatchOptions(user(), $book), 'activity' => $activities->entityActivity($book, 20, 1), 'referenceCount' => $this->referenceFetcher->getReferenceCountToEntity($book), ]); } /** * Show the form for editing the specified book. */ public function edit(string $slug) { $book = $this->queries->findVisibleBySlugOrFail($slug); $this->checkOwnablePermission(Permission::BookUpdate, $book); $this->setPageTitle(trans('entities.books_edit_named', ['bookName' => $book->getShortName()])); return view('books.edit', ['book' => $book, 'current' => $book]); } /** * Update the specified book in storage. * * @throws ImageUploadException * @throws ValidationException * @throws Throwable */ public function update(Request $request, string $slug) { $book = $this->queries->findVisibleBySlugOrFail($slug); $this->checkOwnablePermission(Permission::BookUpdate, $book); $validated = $this->validate($request, [ 'name' => ['required', 'string', 'max:255'], 'description_html' => ['string', 'max:2000'], 'image' => array_merge(['nullable'], $this->getImageValidationRules()), 'tags' => ['array'], 'default_template_id' => ['nullable', 'integer'], ]); if ($request->has('image_reset')) { $validated['image'] = null; } elseif (array_key_exists('image', $validated) && is_null($validated['image'])) { unset($validated['image']); } $book = $this->bookRepo->update($book, $validated); return redirect($book->getUrl()); } /** * Shows the page to confirm deletion. */ public function showDelete(string $bookSlug) { $book = $this->queries->findVisibleBySlugOrFail($bookSlug); $this->checkOwnablePermission(Permission::BookDelete, $book); $this->setPageTitle(trans('entities.books_delete_named', ['bookName' => $book->getShortName()])); return view('books.delete', ['book' => $book, 'current' => $book]); } /** * Remove the specified book from the system. * * @throws Throwable */ public function destroy(string $bookSlug) { $book = $this->queries->findVisibleBySlugOrFail($bookSlug); $this->checkOwnablePermission(Permission::BookDelete, $book); $this->bookRepo->destroy($book); return redirect('/books'); } /** * Show the view to copy a book. * * @throws NotFoundException */ public function showCopy(string $bookSlug) { $book = $this->queries->findVisibleBySlugOrFail($bookSlug); $this->checkOwnablePermission(Permission::BookView, $book); session()->flashInput(['name' => $book->name]); return view('books.copy', [ 'book' => $book, ]); } /** * Create a copy of a book within the requested target destination. * * @throws NotFoundException */ public function copy(Request $request, Cloner $cloner, string $bookSlug) { $book = $this->queries->findVisibleBySlugOrFail($bookSlug); $this->checkOwnablePermission(Permission::BookView, $book); $this->checkPermission(Permission::BookCreateAll); $newName = $request->get('name') ?: $book->name; $bookCopy = $cloner->cloneBook($book, $newName); $this->showSuccessNotification(trans('entities.books_copy_success')); return redirect($bookCopy->getUrl()); } /** * Convert the chapter to a book. */ public function convertToShelf(HierarchyTransformer $transformer, string $bookSlug) { $book = $this->queries->findVisibleBySlugOrFail($bookSlug); $this->checkOwnablePermission(Permission::BookUpdate, $book); $this->checkOwnablePermission(Permission::BookDelete, $book); $this->checkPermission(Permission::BookshelfCreateAll); $this->checkPermission(Permission::BookCreateAll); $shelf = (new DatabaseTransaction(function () use ($book, $transformer) { return $transformer->transformBookToShelf($book); }))->run(); return redirect($shelf->getUrl()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Controllers/PageTemplateController.php
app/Entities/Controllers/PageTemplateController.php
<?php namespace BookStack\Entities\Controllers; use BookStack\Entities\Queries\PageQueries; use BookStack\Entities\Repos\PageRepo; use BookStack\Exceptions\NotFoundException; use BookStack\Http\Controller; use Illuminate\Http\Request; class PageTemplateController extends Controller { public function __construct( protected PageRepo $pageRepo, protected PageQueries $pageQueries, ) { } /** * Fetch a list of templates from the system. */ public function list(Request $request) { $page = $request->get('page', 1); $search = $request->get('search', ''); $count = 10; $query = $this->pageQueries->visibleTemplates() ->orderBy('name', 'asc') ->skip(($page - 1) * $count) ->take($count); if ($search) { $query->where('name', 'like', '%' . $search . '%'); } $templates = $query->paginate($count, ['*'], 'page', $page); $templates->withPath('/templates'); if ($search) { $templates->appends(['search' => $search]); } return view('pages.parts.template-manager-list', [ 'templates' => $templates, ]); } /** * Get the content of a template. * * @throws NotFoundException */ public function get(int $templateId) { $page = $this->pageQueries->findVisibleByIdOrFail($templateId); if (!$page->template) { throw new NotFoundException(); } return response()->json([ 'html' => $page->html, 'markdown' => $page->markdown, ]); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Controllers/PageApiController.php
app/Entities/Controllers/PageApiController.php
<?php namespace BookStack\Entities\Controllers; use BookStack\Activity\Tools\CommentTree; use BookStack\Entities\Queries\EntityQueries; use BookStack\Entities\Queries\PageQueries; use BookStack\Entities\Repos\PageRepo; use BookStack\Exceptions\PermissionsException; use BookStack\Http\ApiController; use BookStack\Permissions\Permission; use Exception; use Illuminate\Http\Request; class PageApiController extends ApiController { protected array $rules = [ 'create' => [ 'book_id' => ['required_without:chapter_id', 'integer'], 'chapter_id' => ['required_without:book_id', 'integer'], 'name' => ['required', 'string', 'max:255'], 'html' => ['required_without:markdown', 'string'], 'markdown' => ['required_without:html', 'string'], 'tags' => ['array'], 'priority' => ['integer'], ], 'update' => [ 'book_id' => ['integer'], 'chapter_id' => ['integer'], 'name' => ['string', 'min:1', 'max:255'], 'html' => ['string'], 'markdown' => ['string'], 'tags' => ['array'], 'priority' => ['integer'], ], ]; public function __construct( protected PageRepo $pageRepo, protected PageQueries $queries, protected EntityQueries $entityQueries, ) { } /** * Get a listing of pages visible to the user. */ public function list() { $pages = $this->queries->visibleForList() ->addSelect(['created_by', 'updated_by', 'revision_count', 'editor']); return $this->apiListingResponse($pages, [ 'id', 'book_id', 'chapter_id', 'name', 'slug', 'priority', 'draft', 'template', 'created_at', 'updated_at', 'created_by', 'updated_by', 'owned_by', ]); } /** * Create a new page in the system. * * The ID of a parent book or chapter is required to indicate * where this page should be located. * * Any HTML content provided should be kept to a single-block depth of plain HTML * elements to remain compatible with the BookStack front-end and editors. * Any images included via base64 data URIs will be extracted and saved as gallery * images against the page during upload. */ public function create(Request $request) { $this->validate($request, $this->rules['create']); if ($request->has('chapter_id')) { $parent = $this->entityQueries->chapters->findVisibleByIdOrFail(intval($request->get('chapter_id'))); } else { $parent = $this->entityQueries->books->findVisibleByIdOrFail(intval($request->get('book_id'))); } $this->checkOwnablePermission(Permission::PageCreate, $parent); $draft = $this->pageRepo->getNewDraftPage($parent); $this->pageRepo->publishDraft($draft, $request->only(array_keys($this->rules['create']))); return response()->json($draft->forJsonDisplay()); } /** * View the details of a single page. * Pages will always have HTML content. They may have markdown content * if the Markdown editor was used to last update the page. * * The 'html' property is the fully rendered and escaped HTML content that BookStack * would show on page view, with page includes handled. * The 'raw_html' property is the direct database stored HTML content, which would be * what BookStack shows on page edit. * * See the "Content Security" section of these docs for security considerations when using * the page content returned from this endpoint. * * Comments for the page are provided in a tree-structure representing the hierarchy of top-level * comments and replies, for both archived and active comments. */ public function read(string $id) { $page = $this->queries->findVisibleByIdOrFail($id); $page = $page->forJsonDisplay(); $commentTree = (new CommentTree($page)); $commentTree->loadVisibleHtml(); $page->setAttribute('comments', [ 'active' => $commentTree->getActive(), 'archived' => $commentTree->getArchived(), ]); return response()->json($page); } /** * Update the details of a single page. * * See the 'create' action for details on the provided HTML/Markdown. * Providing a 'book_id' or 'chapter_id' property will essentially move * the page into that parent element if you have permissions to do so. */ public function update(Request $request, string $id) { $requestData = $this->validate($request, $this->rules['update']); $page = $this->queries->findVisibleByIdOrFail($id); $this->checkOwnablePermission(Permission::PageUpdate, $page); $parent = null; if ($request->has('chapter_id')) { $parent = $this->entityQueries->chapters->findVisibleByIdOrFail(intval($request->get('chapter_id'))); } elseif ($request->has('book_id')) { $parent = $this->entityQueries->books->findVisibleByIdOrFail(intval($request->get('book_id'))); } if ($parent && !$parent->matches($page->getParent())) { $this->checkOwnablePermission(Permission::PageDelete, $page); try { $this->pageRepo->move($page, $parent->getType() . ':' . $parent->id); } catch (Exception $exception) { if ($exception instanceof PermissionsException) { $this->showPermissionError(); } return $this->jsonError(trans('errors.selected_book_chapter_not_found')); } } $updatedPage = $this->pageRepo->update($page, $requestData); return response()->json($updatedPage->forJsonDisplay()); } /** * Delete a page. * This will typically send the page to the recycle bin. */ public function delete(string $id) { $page = $this->queries->findVisibleByIdOrFail($id); $this->checkOwnablePermission(Permission::PageDelete, $page); $this->pageRepo->destroy($page); return response('', 204); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Controllers/RecycleBinApiController.php
app/Entities/Controllers/RecycleBinApiController.php
<?php namespace BookStack\Entities\Controllers; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\BookChild; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Deletion; use BookStack\Entities\Models\Page; use BookStack\Entities\Repos\DeletionRepo; use BookStack\Http\ApiController; use BookStack\Permissions\Permission; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Relations\HasMany; class RecycleBinApiController extends ApiController { public function __construct() { $this->middleware(function ($request, $next) { $this->checkPermission(Permission::SettingsManage); $this->checkPermission(Permission::RestrictionsManageAll); return $next($request); }); } /** * Get a top-level listing of the items in the recycle bin. * The "deletable" property will reflect the main item deleted. * For books and chapters, counts of child pages/chapters will * be loaded within this "deletable" data. * For chapters & pages, the parent item will be loaded within this "deletable" data. * Requires permission to manage both system settings and permissions. */ public function list() { return $this->apiListingResponse(Deletion::query()->with('deletable'), [ 'id', 'deleted_by', 'created_at', 'updated_at', 'deletable_type', 'deletable_id', ], [$this->listFormatter(...)]); } /** * Restore a single deletion from the recycle bin. * Requires permission to manage both system settings and permissions. */ public function restore(DeletionRepo $deletionRepo, string $deletionId) { $restoreCount = $deletionRepo->restore(intval($deletionId)); return response()->json(['restore_count' => $restoreCount]); } /** * Remove a single deletion from the recycle bin. * Use this endpoint carefully as it will entirely remove the underlying deleted items from the system. * Requires permission to manage both system settings and permissions. */ public function destroy(DeletionRepo $deletionRepo, string $deletionId) { $deleteCount = $deletionRepo->destroy(intval($deletionId)); return response()->json(['delete_count' => $deleteCount]); } /** * Load some related details for the deletion listing. */ protected function listFormatter(Deletion $deletion): void { $deletable = $deletion->deletable; if ($deletable instanceof BookChild) { $parent = $deletable->getParent(); $parent->setAttribute('type', $parent->getType()); $deletable->setRelation('parent', $parent); } if ($deletable instanceof Book || $deletable instanceof Chapter) { $countsToLoad = ['pages' => static::withTrashedQuery(...)]; if ($deletable instanceof Book) { $countsToLoad['chapters'] = static::withTrashedQuery(...); } $deletable->loadCount($countsToLoad); } } /** * @param Builder<Chapter|Page> $query */ protected static function withTrashedQuery(Builder $query): void { $query->withTrashed(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Controllers/ChapterController.php
app/Entities/Controllers/ChapterController.php
<?php namespace BookStack\Entities\Controllers; use BookStack\Activity\Models\View; use BookStack\Activity\Tools\UserEntityWatchOptions; use BookStack\Entities\Models\Book; use BookStack\Entities\Queries\ChapterQueries; use BookStack\Entities\Queries\EntityQueries; use BookStack\Entities\Repos\ChapterRepo; use BookStack\Entities\Tools\BookContents; use BookStack\Entities\Tools\Cloner; use BookStack\Entities\Tools\HierarchyTransformer; use BookStack\Entities\Tools\NextPreviousContentLocator; use BookStack\Exceptions\MoveOperationException; use BookStack\Exceptions\NotFoundException; use BookStack\Exceptions\NotifyException; use BookStack\Exceptions\PermissionsException; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use BookStack\References\ReferenceFetcher; use BookStack\Util\DatabaseTransaction; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; use Throwable; class ChapterController extends Controller { public function __construct( protected ChapterRepo $chapterRepo, protected ChapterQueries $queries, protected EntityQueries $entityQueries, protected ReferenceFetcher $referenceFetcher, ) { } /** * Show the form for creating a new chapter. */ public function create(string $bookSlug) { $book = $this->entityQueries->books->findVisibleBySlugOrFail($bookSlug); $this->checkOwnablePermission(Permission::ChapterCreate, $book); $this->setPageTitle(trans('entities.chapters_create')); return view('chapters.create', [ 'book' => $book, 'current' => $book, ]); } /** * Store a newly created chapter in storage. * * @throws ValidationException */ public function store(Request $request, string $bookSlug) { $validated = $this->validate($request, [ 'name' => ['required', 'string', 'max:255'], 'description_html' => ['string', 'max:2000'], 'tags' => ['array'], 'default_template_id' => ['nullable', 'integer'], ]); $book = $this->entityQueries->books->findVisibleBySlugOrFail($bookSlug); $this->checkOwnablePermission(Permission::ChapterCreate, $book); $chapter = $this->chapterRepo->create($validated, $book); return redirect($chapter->getUrl()); } /** * Display the specified chapter. */ public function show(string $bookSlug, string $chapterSlug) { try { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); } catch (NotFoundException $exception) { $chapter = $this->entityQueries->findVisibleByOldSlugs('chapter', $chapterSlug, $bookSlug); if (is_null($chapter)) { throw $exception; } return redirect($chapter->getUrl()); } $sidebarTree = (new BookContents($chapter->book))->getTree(); $pages = $this->entityQueries->pages->visibleForChapterList($chapter->id)->get(); $nextPreviousLocator = new NextPreviousContentLocator($chapter, $sidebarTree); View::incrementFor($chapter); $this->setPageTitle($chapter->getShortName()); return view('chapters.show', [ 'book' => $chapter->book, 'chapter' => $chapter, 'current' => $chapter, 'sidebarTree' => $sidebarTree, 'watchOptions' => new UserEntityWatchOptions(user(), $chapter), 'pages' => $pages, 'next' => $nextPreviousLocator->getNext(), 'previous' => $nextPreviousLocator->getPrevious(), 'referenceCount' => $this->referenceFetcher->getReferenceCountToEntity($chapter), ]); } /** * Show the form for editing the specified chapter. */ public function edit(string $bookSlug, string $chapterSlug) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $this->checkOwnablePermission(Permission::ChapterUpdate, $chapter); $this->setPageTitle(trans('entities.chapters_edit_named', ['chapterName' => $chapter->getShortName()])); return view('chapters.edit', ['book' => $chapter->book, 'chapter' => $chapter, 'current' => $chapter]); } /** * Update the specified chapter in storage. * * @throws NotFoundException */ public function update(Request $request, string $bookSlug, string $chapterSlug) { $validated = $this->validate($request, [ 'name' => ['required', 'string', 'max:255'], 'description_html' => ['string', 'max:2000'], 'tags' => ['array'], 'default_template_id' => ['nullable', 'integer'], ]); $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $this->checkOwnablePermission(Permission::ChapterUpdate, $chapter); $chapter = $this->chapterRepo->update($chapter, $validated); return redirect($chapter->getUrl()); } /** * Shows the page to confirm deletion of this chapter. * * @throws NotFoundException */ public function showDelete(string $bookSlug, string $chapterSlug) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $this->checkOwnablePermission(Permission::ChapterDelete, $chapter); $this->setPageTitle(trans('entities.chapters_delete_named', ['chapterName' => $chapter->getShortName()])); return view('chapters.delete', ['book' => $chapter->book, 'chapter' => $chapter, 'current' => $chapter]); } /** * Remove the specified chapter from storage. * * @throws NotFoundException * @throws Throwable */ public function destroy(string $bookSlug, string $chapterSlug) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $this->checkOwnablePermission(Permission::ChapterDelete, $chapter); $this->chapterRepo->destroy($chapter); return redirect($chapter->book->getUrl()); } /** * Show the page for moving a chapter. * * @throws NotFoundException */ public function showMove(string $bookSlug, string $chapterSlug) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $this->setPageTitle(trans('entities.chapters_move_named', ['chapterName' => $chapter->getShortName()])); $this->checkOwnablePermission(Permission::ChapterUpdate, $chapter); $this->checkOwnablePermission(Permission::ChapterDelete, $chapter); return view('chapters.move', [ 'chapter' => $chapter, 'book' => $chapter->book, ]); } /** * Perform the move action for a chapter. * * @throws NotFoundException|NotifyException */ public function move(Request $request, string $bookSlug, string $chapterSlug) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $this->checkOwnablePermission(Permission::ChapterUpdate, $chapter); $this->checkOwnablePermission(Permission::ChapterDelete, $chapter); $entitySelection = $request->get('entity_selection', null); if ($entitySelection === null || $entitySelection === '') { return redirect($chapter->getUrl()); } try { $this->chapterRepo->move($chapter, $entitySelection); } catch (PermissionsException $exception) { $this->showPermissionError(); } catch (MoveOperationException $exception) { $this->showErrorNotification(trans('errors.selected_book_not_found')); return redirect($chapter->getUrl('/move')); } return redirect($chapter->getUrl()); } /** * Show the view to copy a chapter. * * @throws NotFoundException */ public function showCopy(string $bookSlug, string $chapterSlug) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); session()->flashInput(['name' => $chapter->name]); return view('chapters.copy', [ 'book' => $chapter->book, 'chapter' => $chapter, ]); } /** * Create a copy of a chapter within the requested target destination. * * @throws NotFoundException * @throws Throwable */ public function copy(Request $request, Cloner $cloner, string $bookSlug, string $chapterSlug) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $entitySelection = $request->get('entity_selection') ?: null; $newParentBook = $entitySelection ? $this->entityQueries->findVisibleByStringIdentifier($entitySelection) : $chapter->getParent(); if (!$newParentBook instanceof Book) { $this->showErrorNotification(trans('errors.selected_book_not_found')); return redirect($chapter->getUrl('/copy')); } $this->checkOwnablePermission(Permission::ChapterCreate, $newParentBook); $newName = $request->get('name') ?: $chapter->name; $chapterCopy = $cloner->cloneChapter($chapter, $newParentBook, $newName); $this->showSuccessNotification(trans('entities.chapters_copy_success')); return redirect($chapterCopy->getUrl()); } /** * Convert the chapter to a book. */ public function convertToBook(HierarchyTransformer $transformer, string $bookSlug, string $chapterSlug) { $chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); $this->checkOwnablePermission(Permission::ChapterUpdate, $chapter); $this->checkOwnablePermission(Permission::ChapterDelete, $chapter); $this->checkPermission(Permission::BookCreateAll); $book = (new DatabaseTransaction(function () use ($chapter, $transformer) { return $transformer->transformChapterToBook($chapter); }))->run(); return redirect($book->getUrl()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Controllers/PageController.php
app/Entities/Controllers/PageController.php
<?php namespace BookStack\Entities\Controllers; use BookStack\Activity\Models\View; use BookStack\Activity\Tools\CommentTree; use BookStack\Activity\Tools\UserEntityWatchOptions; use BookStack\Entities\Models\Book; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Queries\EntityQueries; use BookStack\Entities\Queries\PageQueries; use BookStack\Entities\Repos\PageRepo; use BookStack\Entities\Tools\BookContents; use BookStack\Entities\Tools\Cloner; use BookStack\Entities\Tools\NextPreviousContentLocator; use BookStack\Entities\Tools\PageContent; use BookStack\Entities\Tools\PageEditActivity; use BookStack\Entities\Tools\PageEditorData; use BookStack\Exceptions\NotFoundException; use BookStack\Exceptions\PermissionsException; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use BookStack\References\ReferenceFetcher; use Exception; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; use Throwable; class PageController extends Controller { public function __construct( protected PageRepo $pageRepo, protected PageQueries $queries, protected EntityQueries $entityQueries, protected ReferenceFetcher $referenceFetcher ) { } /** * Show the form for creating a new page. * * @throws Throwable */ public function create(string $bookSlug, ?string $chapterSlug = null) { if ($chapterSlug) { $parent = $this->entityQueries->chapters->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); } else { $parent = $this->entityQueries->books->findVisibleBySlugOrFail($bookSlug); } $this->checkOwnablePermission(Permission::PageCreate, $parent); // Redirect to draft edit screen if signed in if ($this->isSignedIn()) { $draft = $this->pageRepo->getNewDraftPage($parent); return redirect($draft->getUrl()); } // Otherwise show the edit view if they're a guest $this->setPageTitle(trans('entities.pages_new')); return view('pages.guest-create', ['parent' => $parent]); } /** * Create a new page as a guest user. * * @throws ValidationException */ public function createAsGuest(Request $request, string $bookSlug, ?string $chapterSlug = null) { $this->validate($request, [ 'name' => ['required', 'string', 'max:255'], ]); if ($chapterSlug) { $parent = $this->entityQueries->chapters->findVisibleBySlugsOrFail($bookSlug, $chapterSlug); } else { $parent = $this->entityQueries->books->findVisibleBySlugOrFail($bookSlug); } $this->checkOwnablePermission(Permission::PageCreate, $parent); $page = $this->pageRepo->getNewDraftPage($parent); $this->pageRepo->publishDraft($page, [ 'name' => $request->get('name'), ]); return redirect($page->getUrl('/edit')); } /** * Show form to continue editing a draft page. * * @throws NotFoundException */ public function editDraft(Request $request, string $bookSlug, int $pageId) { $draft = $this->queries->findVisibleByIdOrFail($pageId); $this->checkOwnablePermission(Permission::PageCreate, $draft->getParent()); $editorData = new PageEditorData($draft, $this->entityQueries, $request->query('editor', '')); $this->setPageTitle(trans('entities.pages_edit_draft')); return view('pages.edit', $editorData->getViewData()); } /** * Store a new page by changing a draft into a page. * * @throws NotFoundException * @throws ValidationException */ public function store(Request $request, string $bookSlug, int $pageId) { $this->validate($request, [ 'name' => ['required', 'string', 'max:255'], ]); $draftPage = $this->queries->findVisibleByIdOrFail($pageId); $this->checkOwnablePermission(Permission::PageCreate, $draftPage->getParent()); $page = $this->pageRepo->publishDraft($draftPage, $request->all()); return redirect($page->getUrl()); } /** * Display the specified page. * If the page is not found via the slug the revisions are searched for a match. * * @throws NotFoundException */ public function show(string $bookSlug, string $pageSlug) { try { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); } catch (NotFoundException $e) { $page = $this->entityQueries->findVisibleByOldSlugs('page', $pageSlug, $bookSlug); if (is_null($page)) { throw $e; } return redirect($page->getUrl()); } $pageContent = (new PageContent($page)); $page->html = $pageContent->render(); $pageNav = $pageContent->getNavigation($page->html); $sidebarTree = (new BookContents($page->book))->getTree(); $commentTree = (new CommentTree($page)); $nextPreviousLocator = new NextPreviousContentLocator($page, $sidebarTree); View::incrementFor($page); $this->setPageTitle($page->getShortName()); return view('pages.show', [ 'page' => $page, 'book' => $page->book, 'current' => $page, 'sidebarTree' => $sidebarTree, 'commentTree' => $commentTree, 'pageNav' => $pageNav, 'watchOptions' => new UserEntityWatchOptions(user(), $page), 'next' => $nextPreviousLocator->getNext(), 'previous' => $nextPreviousLocator->getPrevious(), 'referenceCount' => $this->referenceFetcher->getReferenceCountToEntity($page), ]); } /** * Get page from an ajax request. * * @throws NotFoundException */ public function getPageAjax(int $pageId) { $page = $this->queries->findVisibleByIdOrFail($pageId); $page->setHidden(array_diff($page->getHidden(), ['html', 'markdown'])); $page->makeHidden(['book']); return response()->json($page); } /** * Show the form for editing the specified page. * * @throws NotFoundException */ public function edit(Request $request, string $bookSlug, string $pageSlug) { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $this->checkOwnablePermission(Permission::PageUpdate, $page, $page->getUrl()); $editorData = new PageEditorData($page, $this->entityQueries, $request->query('editor', '')); if ($editorData->getWarnings()) { $this->showWarningNotification(implode("\n", $editorData->getWarnings())); } $this->setPageTitle(trans('entities.pages_editing_named', ['pageName' => $page->getShortName()])); return view('pages.edit', $editorData->getViewData()); } /** * Update the specified page in storage. * * @throws ValidationException * @throws NotFoundException */ public function update(Request $request, string $bookSlug, string $pageSlug) { $this->validate($request, [ 'name' => ['required', 'string', 'max:255'], ]); $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $this->checkOwnablePermission(Permission::PageUpdate, $page); $this->pageRepo->update($page, $request->all()); return redirect($page->getUrl()); } /** * Save a draft update as a revision. * * @throws NotFoundException */ public function saveDraft(Request $request, int $pageId) { $page = $this->queries->findVisibleByIdOrFail($pageId); $this->checkOwnablePermission(Permission::PageUpdate, $page); if (!$this->isSignedIn()) { return $this->jsonError(trans('errors.guests_cannot_save_drafts'), 500); } $draft = $this->pageRepo->updatePageDraft($page, $request->only(['name', 'html', 'markdown'])); $warnings = (new PageEditActivity($page))->getWarningMessagesForDraft($draft); return response()->json([ 'status' => 'success', 'message' => trans('entities.pages_edit_draft_save_at'), 'warning' => implode("\n", $warnings), 'timestamp' => $draft->updated_at->timestamp, ]); } /** * Redirect from a special link url which uses the page id rather than the name. * * @throws NotFoundException */ public function redirectFromLink(int $pageId) { $page = $this->queries->findVisibleByIdOrFail($pageId); return redirect($page->getUrl()); } /** * Show the deletion page for the specified page. * * @throws NotFoundException */ public function showDelete(string $bookSlug, string $pageSlug) { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $this->checkOwnablePermission(Permission::PageDelete, $page); $this->setPageTitle(trans('entities.pages_delete_named', ['pageName' => $page->getShortName()])); $usedAsTemplate = $this->entityQueries->books->start()->where('default_template_id', '=', $page->id)->count() > 0 || $this->entityQueries->chapters->start()->where('default_template_id', '=', $page->id)->count() > 0; return view('pages.delete', [ 'book' => $page->book, 'page' => $page, 'current' => $page, 'usedAsTemplate' => $usedAsTemplate, ]); } /** * Show the deletion page for the specified page. * * @throws NotFoundException */ public function showDeleteDraft(string $bookSlug, int $pageId) { $page = $this->queries->findVisibleByIdOrFail($pageId); $this->checkOwnablePermission(Permission::PageUpdate, $page); $this->setPageTitle(trans('entities.pages_delete_draft_named', ['pageName' => $page->getShortName()])); $usedAsTemplate = $this->entityQueries->books->start()->where('default_template_id', '=', $page->id)->count() > 0 || $this->entityQueries->chapters->start()->where('default_template_id', '=', $page->id)->count() > 0; return view('pages.delete', [ 'book' => $page->book, 'page' => $page, 'current' => $page, 'usedAsTemplate' => $usedAsTemplate, ]); } /** * Remove the specified page from storage. * * @throws NotFoundException * @throws Throwable */ public function destroy(string $bookSlug, string $pageSlug) { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $this->checkOwnablePermission(Permission::PageDelete, $page); $parent = $page->getParent(); $this->pageRepo->destroy($page); return redirect($parent->getUrl()); } /** * Remove the specified draft page from storage. * * @throws NotFoundException * @throws Throwable */ public function destroyDraft(string $bookSlug, int $pageId) { $page = $this->queries->findVisibleByIdOrFail($pageId); $book = $page->book; $chapter = $page->chapter; $this->checkOwnablePermission(Permission::PageUpdate, $page); $this->pageRepo->destroy($page); $this->showSuccessNotification(trans('entities.pages_delete_draft_success')); if ($chapter && userCan(Permission::ChapterView, $chapter)) { return redirect($chapter->getUrl()); } return redirect($book->getUrl()); } /** * Show a listing of recently created pages. */ public function showRecentlyUpdated() { $visibleBelongsScope = function (BelongsTo $query) { $query->scopes('visible'); }; $pages = $this->queries->visibleForList() ->addSelect('updated_by') ->with(['updatedBy', 'book' => $visibleBelongsScope, 'chapter' => $visibleBelongsScope]) ->orderBy('updated_at', 'desc') ->paginate(20) ->setPath(url('/pages/recently-updated')); $this->setPageTitle(trans('entities.recently_updated_pages')); return view('common.detailed-listing-paginated', [ 'title' => trans('entities.recently_updated_pages'), 'entities' => $pages, 'showUpdatedBy' => true, 'showPath' => true, ]); } /** * Show the view to choose a new parent to move a page into. * * @throws NotFoundException */ public function showMove(string $bookSlug, string $pageSlug) { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $this->checkOwnablePermission(Permission::PageUpdate, $page); $this->checkOwnablePermission(Permission::PageDelete, $page); return view('pages.move', [ 'book' => $page->book, 'page' => $page, ]); } /** * Does the action of moving the location of a page. * * @throws NotFoundException * @throws Throwable */ public function move(Request $request, string $bookSlug, string $pageSlug) { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $this->checkOwnablePermission(Permission::PageUpdate, $page); $this->checkOwnablePermission(Permission::PageDelete, $page); $entitySelection = $request->get('entity_selection', null); if ($entitySelection === null || $entitySelection === '') { return redirect($page->getUrl()); } try { $this->pageRepo->move($page, $entitySelection); } catch (PermissionsException $exception) { $this->showPermissionError(); } catch (Exception $exception) { $this->showErrorNotification(trans('errors.selected_book_chapter_not_found')); return redirect($page->getUrl('/move')); } return redirect($page->getUrl()); } /** * Show the view to copy a page. * * @throws NotFoundException */ public function showCopy(string $bookSlug, string $pageSlug) { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); session()->flashInput(['name' => $page->name]); return view('pages.copy', [ 'book' => $page->book, 'page' => $page, ]); } /** * Create a copy of a page within the requested target destination. * * @throws NotFoundException * @throws Throwable */ public function copy(Request $request, Cloner $cloner, string $bookSlug, string $pageSlug) { $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug); $this->checkOwnablePermission(Permission::PageView, $page); $entitySelection = $request->get('entity_selection') ?: null; $newParent = $entitySelection ? $this->entityQueries->findVisibleByStringIdentifier($entitySelection) : $page->getParent(); if (!$newParent instanceof Book && !$newParent instanceof Chapter) { $this->showErrorNotification(trans('errors.selected_book_chapter_not_found')); return redirect($page->getUrl('/copy')); } $this->checkOwnablePermission(Permission::PageCreate, $newParent); $newName = $request->get('name') ?: $page->name; $pageCopy = $cloner->clonePage($page, $newParent, $newName); $this->showSuccessNotification(trans('entities.pages_copy_success')); return redirect($pageCopy->getUrl()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Controllers/BookshelfController.php
app/Entities/Controllers/BookshelfController.php
<?php namespace BookStack\Entities\Controllers; use BookStack\Activity\ActivityQueries; use BookStack\Activity\Models\View; use BookStack\Entities\Queries\BookQueries; use BookStack\Entities\Queries\BookshelfQueries; use BookStack\Entities\Queries\EntityQueries; use BookStack\Entities\Repos\BookshelfRepo; use BookStack\Entities\Tools\ShelfContext; use BookStack\Exceptions\ImageUploadException; use BookStack\Exceptions\NotFoundException; use BookStack\Http\Controller; use BookStack\Permissions\Permission; use BookStack\References\ReferenceFetcher; use BookStack\Util\SimpleListOptions; use Exception; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; class BookshelfController extends Controller { public function __construct( protected BookshelfRepo $shelfRepo, protected BookshelfQueries $queries, protected EntityQueries $entityQueries, protected BookQueries $bookQueries, protected ShelfContext $shelfContext, protected ReferenceFetcher $referenceFetcher, ) { } /** * Display a listing of bookshelves. */ public function index(Request $request) { $view = setting()->getForCurrentUser('bookshelves_view_type'); $listOptions = SimpleListOptions::fromRequest($request, 'bookshelves')->withSortOptions([ 'name' => trans('common.sort_name'), 'created_at' => trans('common.sort_created_at'), 'updated_at' => trans('common.sort_updated_at'), ]); $shelves = $this->queries->visibleForListWithCover() ->orderBy($listOptions->getSort(), $listOptions->getOrder()) ->paginate(setting()->getInteger('lists-page-count-shelves', 18, 1, 1000)); $recents = $this->isSignedIn() ? $this->queries->recentlyViewedForCurrentUser()->get() : false; $popular = $this->queries->popularForList()->get(); $new = $this->queries->visibleForList() ->orderBy('created_at', 'desc') ->take(4) ->get(); $this->shelfContext->clearShelfContext(); $this->setPageTitle(trans('entities.shelves')); return view('shelves.index', [ 'shelves' => $shelves, 'recents' => $recents, 'popular' => $popular, 'new' => $new, 'view' => $view, 'listOptions' => $listOptions, ]); } /** * Show the form for creating a new bookshelf. */ public function create() { $this->checkPermission(Permission::BookshelfCreateAll); $books = $this->bookQueries->visibleForList()->orderBy('name')->get(['name', 'id', 'slug', 'created_at', 'updated_at']); $this->setPageTitle(trans('entities.shelves_create')); return view('shelves.create', ['books' => $books]); } /** * Store a newly created bookshelf in storage. * * @throws ValidationException * @throws ImageUploadException */ public function store(Request $request) { $this->checkPermission(Permission::BookshelfCreateAll); $validated = $this->validate($request, [ 'name' => ['required', 'string', 'max:255'], 'description_html' => ['string', 'max:2000'], 'image' => array_merge(['nullable'], $this->getImageValidationRules()), 'tags' => ['array'], ]); $bookIds = explode(',', $request->get('books', '')); $shelf = $this->shelfRepo->create($validated, $bookIds); return redirect($shelf->getUrl()); } /** * Display the bookshelf of the given slug. * * @throws NotFoundException */ public function show(Request $request, ActivityQueries $activities, string $slug) { try { $shelf = $this->queries->findVisibleBySlugOrFail($slug); } catch (NotFoundException $exception) { $shelf = $this->entityQueries->findVisibleByOldSlugs('bookshelf', $slug); if (is_null($shelf)) { throw $exception; } return redirect($shelf->getUrl()); } $this->checkOwnablePermission(Permission::BookshelfView, $shelf); $listOptions = SimpleListOptions::fromRequest($request, 'shelf_books')->withSortOptions([ 'default' => trans('common.sort_default'), 'name' => trans('common.sort_name'), 'created_at' => trans('common.sort_created_at'), 'updated_at' => trans('common.sort_updated_at'), ]); $sort = $listOptions->getSort(); $sortedVisibleShelfBooks = $shelf->visibleBooks() ->reorder($sort === 'default' ? 'order' : $sort, $listOptions->getOrder()) ->get() ->values() ->all(); View::incrementFor($shelf); $this->shelfContext->setShelfContext($shelf->id); $view = setting()->getForCurrentUser('bookshelf_view_type'); $this->setPageTitle($shelf->getShortName()); return view('shelves.show', [ 'shelf' => $shelf, 'sortedVisibleShelfBooks' => $sortedVisibleShelfBooks, 'view' => $view, 'activity' => $activities->entityActivity($shelf, 20, 1), 'listOptions' => $listOptions, 'referenceCount' => $this->referenceFetcher->getReferenceCountToEntity($shelf), ]); } /** * Show the form for editing the specified bookshelf. */ public function edit(string $slug) { $shelf = $this->queries->findVisibleBySlugOrFail($slug); $this->checkOwnablePermission(Permission::BookshelfUpdate, $shelf); $shelfBookIds = $shelf->books()->get(['id'])->pluck('id'); $books = $this->bookQueries->visibleForList() ->whereNotIn('id', $shelfBookIds) ->orderBy('name') ->get(['name', 'id', 'slug', 'created_at', 'updated_at']); $this->setPageTitle(trans('entities.shelves_edit_named', ['name' => $shelf->getShortName()])); return view('shelves.edit', [ 'shelf' => $shelf, 'books' => $books, ]); } /** * Update the specified bookshelf in storage. * * @throws ValidationException * @throws ImageUploadException * @throws NotFoundException */ public function update(Request $request, string $slug) { $shelf = $this->queries->findVisibleBySlugOrFail($slug); $this->checkOwnablePermission(Permission::BookshelfUpdate, $shelf); $validated = $this->validate($request, [ 'name' => ['required', 'string', 'max:255'], 'description_html' => ['string', 'max:2000'], 'image' => array_merge(['nullable'], $this->getImageValidationRules()), 'tags' => ['array'], ]); if ($request->has('image_reset')) { $validated['image'] = null; } elseif (array_key_exists('image', $validated) && is_null($validated['image'])) { unset($validated['image']); } $bookIds = explode(',', $request->get('books', '')); $shelf = $this->shelfRepo->update($shelf, $validated, $bookIds); return redirect($shelf->getUrl()); } /** * Shows the page to confirm deletion. */ public function showDelete(string $slug) { $shelf = $this->queries->findVisibleBySlugOrFail($slug); $this->checkOwnablePermission(Permission::BookshelfDelete, $shelf); $this->setPageTitle(trans('entities.shelves_delete_named', ['name' => $shelf->getShortName()])); return view('shelves.delete', ['shelf' => $shelf]); } /** * Remove the specified bookshelf from storage. * * @throws Exception */ public function destroy(string $slug) { $shelf = $this->queries->findVisibleBySlugOrFail($slug); $this->checkOwnablePermission(Permission::BookshelfDelete, $shelf); $this->shelfRepo->destroy($shelf); return redirect('/shelves'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/Page.php
app/Entities/Models/Page.php
<?php namespace BookStack\Entities\Models; use BookStack\Entities\Tools\PageContent; use BookStack\Permissions\PermissionApplicator; use BookStack\Uploads\Attachment; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; /** * Class Page. * @property EntityPageData $pageData * @property int $chapter_id * @property string $html * @property string $markdown * @property string $text * @property bool $template * @property bool $draft * @property int $revision_count * @property string $editor * @property Chapter $chapter * @property Collection $attachments * @property Collection $revisions * @property PageRevision $currentRevision */ class Page extends BookChild { use HasFactory; public string $textField = 'text'; public string $htmlField = 'html'; protected $hidden = ['html', 'markdown', 'text', 'pivot', 'deleted_at', 'entity_id', 'entity_type']; protected $fillable = ['name', 'priority']; protected $casts = [ 'draft' => 'boolean', 'template' => 'boolean', ]; /** * Get the entities that are visible to the current user. */ public function scopeVisible(Builder $query): Builder { $query = app()->make(PermissionApplicator::class)->restrictDraftsOnPageQuery($query); return parent::scopeVisible($query); } /** * Get the chapter that this page is in, If applicable. */ public function chapter(): BelongsTo { return $this->belongsTo(Chapter::class); } /** * Check if this page has a chapter. */ public function hasChapter(): bool { return $this->chapter()->count() > 0; } /** * Get the associated page revisions, ordered by created date. * Only provides actual saved page revision instances, Not drafts. */ public function revisions(): HasMany { return $this->allRevisions() ->where('type', '=', 'version') ->orderBy('created_at', 'desc') ->orderBy('id', 'desc'); } /** * Get the current revision for the page if existing. */ public function currentRevision(): HasOne { return $this->hasOne(PageRevision::class) ->where('type', '=', 'version') ->orderBy('created_at', 'desc') ->orderBy('id', 'desc'); } /** * Get all revision instances assigned to this page. * Includes all types of revisions. */ public function allRevisions(): HasMany { return $this->hasMany(PageRevision::class); } /** * Get the attachments assigned to this page. */ public function attachments(): HasMany { return $this->hasMany(Attachment::class, 'uploaded_to')->orderBy('order', 'asc'); } /** * Get the url of this page. */ public function getUrl(string $path = ''): string { $parts = [ 'books', urlencode($this->book_slug ?? $this->book->slug), $this->draft ? 'draft' : 'page', $this->draft ? $this->id : urlencode($this->slug), trim($path, '/'), ]; return url('/' . implode('/', $parts)); } /** * Get the ID-based permalink for this page. */ public function getPermalink(): string { return url("/link/{$this->id}"); } /** * Get this page for JSON display. */ public function forJsonDisplay(): self { $refreshed = $this->refresh()->unsetRelations()->load(['tags', 'createdBy', 'updatedBy', 'ownedBy']); $refreshed->setHidden(array_diff($refreshed->getHidden(), ['html', 'markdown'])); $refreshed->setAttribute('raw_html', $refreshed->html); $refreshed->setAttribute('html', (new PageContent($refreshed))->render()); return $refreshed; } /** * @return HasOne<EntityPageData, $this> */ public function relatedData(): HasOne { return $this->hasOne(EntityPageData::class, 'page_id', 'id'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/EntityPageData.php
app/Entities/Models/EntityPageData.php
<?php namespace BookStack\Entities\Models; use Illuminate\Database\Eloquent\Model; /** * @property int $page_id */ class EntityPageData extends Model { public $timestamps = false; protected $primaryKey = 'page_id'; public $incrementing = false; public static array $fields = [ 'draft', 'template', 'revision_count', 'editor', 'html', 'text', 'markdown', ]; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/BookChild.php
app/Entities/Models/BookChild.php
<?php namespace BookStack\Entities\Models; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * Class BookChild. * * @property int $book_id * @property int $priority * @property string $book_slug * @property Book $book */ abstract class BookChild extends Entity { /** * Get the book this page sits in. * @return BelongsTo<Book, $this> */ public function book(): BelongsTo { return $this->belongsTo(Book::class)->withTrashed(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/HasDescriptionInterface.php
app/Entities/Models/HasDescriptionInterface.php
<?php namespace BookStack\Entities\Models; use BookStack\Entities\Tools\EntityHtmlDescription; interface HasDescriptionInterface { public function descriptionInfo(): EntityHtmlDescription; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/Entity.php
app/Entities/Models/Entity.php
<?php namespace BookStack\Entities\Models; use BookStack\Activity\Models\Activity; use BookStack\Activity\Models\Comment; use BookStack\Activity\Models\Favouritable; use BookStack\Activity\Models\Favourite; use BookStack\Activity\Models\Loggable; use BookStack\Activity\Models\Tag; use BookStack\Activity\Models\View; use BookStack\Activity\Models\Viewable; use BookStack\Activity\Models\Watch; use BookStack\App\Model; use BookStack\App\SluggableInterface; use BookStack\Permissions\JointPermissionBuilder; use BookStack\Permissions\Models\EntityPermission; use BookStack\Permissions\Models\JointPermission; use BookStack\Permissions\PermissionApplicator; use BookStack\References\Reference; use BookStack\Search\SearchIndex; use BookStack\Search\SearchTerm; use BookStack\Users\Models\HasCreatorAndUpdater; use BookStack\Users\Models\OwnableInterface; use BookStack\Users\Models\User; use Carbon\Carbon; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\SoftDeletes; /** * Class Entity * The base class for book-like items such as pages, chapters and books. * This is not a database model in itself but extended. * * @property int $id * @property string $type * @property string $name * @property string $slug * @property Carbon $created_at * @property Carbon $updated_at * @property Carbon $deleted_at * @property int|null $created_by * @property int|null $updated_by * @property int|null $owned_by * @property Collection $tags * * @method static Entity|Builder visible() * @method static Builder withLastView() * @method static Builder withViewCount() */ abstract class Entity extends Model implements SluggableInterface, Favouritable, Viewable, DeletableInterface, OwnableInterface, Loggable { use SoftDeletes; use HasCreatorAndUpdater; /** * @var string - Name of property where the main text content is found */ public string $textField = 'description'; /** * @var string - Name of the property where the main HTML content is found */ public string $htmlField = 'description_html'; /** * @var float - Multiplier for search indexing. */ public float $searchFactor = 1.0; /** * Set the table to be that used by all entities. */ protected $table = 'entities'; /** * Set a custom query builder for entities. */ protected static string $builder = EntityQueryBuilder::class; public static array $commonFields = [ 'id', 'type', 'name', 'slug', 'book_id', 'chapter_id', 'priority', 'created_at', 'updated_at', 'deleted_at', 'created_by', 'updated_by', 'owned_by', ]; /** * Override the save method to also save the contents for convenience. */ public function save(array $options = []): bool { /** @var EntityPageData|EntityContainerData $contents */ $contents = $this->relatedData()->firstOrNew(); $contentFields = $this->getContentsAttributes(); foreach ($contentFields as $key => $value) { $contents->setAttribute($key, $value); unset($this->attributes[$key]); } $this->setAttribute('type', $this->getMorphClass()); $result = parent::save($options); $contentsResult = true; if ($result && $contents->isDirty()) { $contentsFillData = $contents instanceof EntityPageData ? ['page_id' => $this->id] : ['entity_id' => $this->id, 'entity_type' => $this->getMorphClass()]; $contents->forceFill($contentsFillData); $contentsResult = $contents->save(); $this->touch(); } $this->forceFill($contentFields); return $result && $contentsResult; } /** * Check if this item is a container item. */ public function isContainer(): bool { return $this instanceof Bookshelf || $this instanceof Book || $this instanceof Chapter; } /** * Get the entities that are visible to the current user. */ public function scopeVisible(Builder $query): Builder { return app()->make(PermissionApplicator::class)->restrictEntityQuery($query); } /** * Query scope to get the last view from the current user. */ public function scopeWithLastView(Builder $query) { $viewedAtQuery = View::query()->select('updated_at') ->whereColumn('viewable_id', '=', 'entities.id') ->whereColumn('viewable_type', '=', 'entities.type') ->where('user_id', '=', user()->id) ->take(1); return $query->addSelect(['last_viewed_at' => $viewedAtQuery]); } /** * Query scope to get the total view count of the entities. */ public function scopeWithViewCount(Builder $query): void { $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count') ->whereColumn('viewable_id', '=', 'entities.id') ->whereColumn('viewable_type', '=', 'entities.type') ->take(1); $query->addSelect(['view_count' => $viewCountQuery]); } /** * Compares this entity to another given entity. * Matches by comparing class and id. */ public function matches(self $entity): bool { return [get_class($this), $this->id] === [get_class($entity), $entity->id]; } /** * Checks if the current entity matches or contains the given. */ public function matchesOrContains(self $entity): bool { if ($this->matches($entity)) { return true; } if (($entity instanceof BookChild) && $this instanceof Book) { return $entity->book_id === $this->id; } if ($entity instanceof Page && $this instanceof Chapter) { return $entity->chapter_id === $this->id; } return false; } /** * Gets the activity objects for this entity. */ public function activity(): MorphMany { return $this->morphMany(Activity::class, 'loggable') ->orderBy('created_at', 'desc'); } /** * Get View objects for this entity. */ public function views(): MorphMany { return $this->morphMany(View::class, 'viewable'); } /** * Get the Tag models that have been user assigned to this entity. */ public function tags(): MorphMany { return $this->morphMany(Tag::class, 'entity') ->orderBy('order', 'asc'); } /** * Get the comments for an entity. * @return MorphMany<Comment, $this> */ public function comments(bool $orderByCreated = true): MorphMany { $query = $this->morphMany(Comment::class, 'commentable'); return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query; } /** * Get the related search terms. */ public function searchTerms(): MorphMany { return $this->morphMany(SearchTerm::class, 'entity'); } /** * Get this entities assigned permissions. */ public function permissions(): MorphMany { return $this->morphMany(EntityPermission::class, 'entity'); } /** * Check if this entity has a specific restriction set against it. */ public function hasPermissions(): bool { return $this->permissions()->count() > 0; } /** * Get the entity jointPermissions this is connected to. */ public function jointPermissions(): MorphMany { return $this->morphMany(JointPermission::class, 'entity'); } /** * Get the user who owns this entity. * @return BelongsTo<User, $this> */ public function ownedBy(): BelongsTo { return $this->belongsTo(User::class, 'owned_by'); } public function getOwnerFieldName(): string { return 'owned_by'; } /** * Get the related delete records for this entity. */ public function deletions(): MorphMany { return $this->morphMany(Deletion::class, 'deletable'); } /** * Get the references pointing from this entity to other items. */ public function referencesFrom(): MorphMany { return $this->morphMany(Reference::class, 'from'); } /** * Get the references pointing to this entity from other items. */ public function referencesTo(): MorphMany { return $this->morphMany(Reference::class, 'to'); } /** * Check if this instance or class is a certain type of entity. * Examples of $type are 'page', 'book', 'chapter'. * * @deprecated Use instanceof instead. */ public static function isA(string $type): bool { return static::getType() === strtolower($type); } /** * Get the entity type as a simple lowercase word. */ public static function getType(): string { $className = array_slice(explode('\\', static::class), -1, 1)[0]; return strtolower($className); } /** * Gets a limited-length version of the entity name. */ public function getShortName(int $length = 25): string { if (mb_strlen($this->name) <= $length) { return $this->name; } return mb_substr($this->name, 0, $length - 3) . '...'; } /** * Get an excerpt of this entity's descriptive content to the specified length. */ public function getExcerpt(int $length = 100): string { $text = $this->{$this->textField} ?? ''; if (mb_strlen($text) > $length) { $text = mb_substr($text, 0, $length - 3) . '...'; } return trim($text); } /** * Get the url of this entity. */ abstract public function getUrl(string $path = '/'): string; /** * Get the parent entity if existing. * This is the "static" parent and does not include dynamic * relations such as shelves to books. */ public function getParent(): ?self { if ($this instanceof Page) { /** @var BelongsTo<Chapter|Book, Page> $builder */ $builder = $this->chapter_id ? $this->chapter() : $this->book(); return $builder->withTrashed()->first(); } if ($this instanceof Chapter) { /** @var BelongsTo<Book, Page> $builder */ $builder = $this->book(); return $builder->withTrashed()->first(); } return null; } /** * Rebuild the permissions for this entity. */ public function rebuildPermissions(): void { app()->make(JointPermissionBuilder::class)->rebuildForEntity(clone $this); } /** * Index the current entity for search. */ public function indexForSearch(): void { app()->make(SearchIndex::class)->indexEntity(clone $this); } /** * {@inheritdoc} */ public function favourites(): MorphMany { return $this->morphMany(Favourite::class, 'favouritable'); } /** * Check if the entity is a favourite of the current user. */ public function isFavourite(): bool { return $this->favourites() ->where('user_id', '=', user()->id) ->exists(); } /** * Get the related watches for this entity. */ public function watches(): MorphMany { return $this->morphMany(Watch::class, 'watchable'); } /** * Get the related slug history for this entity. */ public function slugHistory(): MorphMany { return $this->morphMany(SlugHistory::class, 'sluggable'); } /** * {@inheritdoc} */ public function logDescriptor(): string { return "({$this->id}) {$this->name}"; } /** * @return HasOne<covariant (EntityContainerData|EntityPageData), $this> */ abstract public function relatedData(): HasOne; /** * Get the attributes that are intended for the related contents model. * @return array<string, mixed> */ protected function getContentsAttributes(): array { $contentFields = []; $contentModel = $this instanceof Page ? EntityPageData::class : EntityContainerData::class; foreach ($this->attributes as $key => $value) { if (in_array($key, $contentModel::$fields)) { $contentFields[$key] = $value; } } return $contentFields; } /** * Create a new instance for the given entity type. */ public static function instanceFromType(string $type): self { return match ($type) { 'page' => new Page(), 'chapter' => new Chapter(), 'book' => new Book(), 'bookshelf' => new Bookshelf(), }; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/DeletableInterface.php
app/Entities/Models/DeletableInterface.php
<?php namespace BookStack\Entities\Models; use Illuminate\Database\Eloquent\Relations\MorphMany; /** * A model that can be deleted in a manner that deletions * are tracked to be part of the recycle bin system. */ interface DeletableInterface { public function deletions(): MorphMany; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/SlugHistory.php
app/Entities/Models/SlugHistory.php
<?php namespace BookStack\Entities\Models; use BookStack\App\Model; use BookStack\Permissions\Models\JointPermission; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\HasMany; /** * @property int $id * @property int $sluggable_id * @property string $sluggable_type * @property string $slug * @property ?string $parent_slug */ class SlugHistory extends Model { use HasFactory; protected $table = 'slug_history'; public function jointPermissions(): HasMany { return $this->hasMany(JointPermission::class, 'entity_id', 'sluggable_id') ->whereColumn('joint_permissions.entity_type', '=', 'slug_history.sluggable_type'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/HasCoverInterface.php
app/Entities/Models/HasCoverInterface.php
<?php namespace BookStack\Entities\Models; use BookStack\Entities\Tools\EntityCover; use BookStack\Uploads\Image; use Illuminate\Database\Eloquent\Relations\BelongsTo; interface HasCoverInterface { public function coverInfo(): EntityCover; /** * The cover image of this entity. * @return BelongsTo<Image, covariant Entity> */ public function cover(): BelongsTo; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/HasDefaultTemplateInterface.php
app/Entities/Models/HasDefaultTemplateInterface.php
<?php namespace BookStack\Entities\Models; use BookStack\Entities\Tools\EntityDefaultTemplate; interface HasDefaultTemplateInterface { public function defaultTemplate(): EntityDefaultTemplate; }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/Deletion.php
app/Entities/Models/Deletion.php
<?php namespace BookStack\Entities\Models; use BookStack\Activity\Models\Loggable; use BookStack\Users\Models\User; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\MorphTo; /** * @property int $id * @property int $deleted_by * @property string $deletable_type * @property int $deletable_id * @property DeletableInterface $deletable */ class Deletion extends Model implements Loggable { use HasFactory; protected $hidden = []; /** * Get the related deletable record. */ public function deletable(): MorphTo { return $this->morphTo('deletable')->withTrashed(); } /** * Get the user that performed the deletion. */ public function deleter(): BelongsTo { return $this->belongsTo(User::class, 'deleted_by'); } /** * Create a new deletion record for the provided entity. */ public static function createForEntity(Entity $entity): self { $record = (new self())->forceFill([ 'deleted_by' => user()->id, 'deletable_type' => $entity->getMorphClass(), 'deletable_id' => $entity->id, ]); $record->save(); return $record; } public function logDescriptor(): string { $deletable = $this->deletable()->first(); if ($deletable instanceof Entity) { return "Deletion ({$this->id}) for {$deletable->getType()} ({$deletable->id}) {$deletable->name}"; } return "Deletion ({$this->id})"; } /** * Get a URL for this specific deletion. */ public function getUrl(string $path = 'restore'): string { return url("/settings/recycle-bin/{$this->id}/" . ltrim($path, '/')); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/EntityContainerData.php
app/Entities/Models/EntityContainerData.php
<?php namespace BookStack\Entities\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; /** * @property int $entity_id * @property string $entity_type * @property string $description * @property string $description_html * @property ?int $default_template_id * @property ?int $image_id * @property ?int $sort_rule_id */ class EntityContainerData extends Model { public $timestamps = false; protected $primaryKey = 'entity_id'; public $incrementing = false; public static array $fields = [ 'description', 'description_html', 'default_template_id', 'image_id', 'sort_rule_id', ]; /** * Override the default set keys for save query method to make it work with composite keys. */ public function setKeysForSaveQuery($query): Builder { $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery()) ->where('entity_type', '=', $this->entity_type); return $query; } /** * Override the default set keys for a select query method to make it work with composite keys. */ protected function setKeysForSelectQuery($query): Builder { $query->where($this->getKeyName(), '=', $this->getKeyForSelectQuery()) ->where('entity_type', '=', $this->entity_type); return $query; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/Chapter.php
app/Entities/Models/Chapter.php
<?php namespace BookStack\Entities\Models; use BookStack\Entities\Tools\EntityDefaultTemplate; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Collection; /** * @property Collection<Page> $pages * @property ?int $default_template_id * @property string $description * @property string $description_html */ class Chapter extends BookChild implements HasDescriptionInterface, HasDefaultTemplateInterface { use HasFactory; use ContainerTrait; public float $searchFactor = 1.2; protected $hidden = ['pivot', 'deleted_at', 'description_html', 'sort_rule_id', 'image_id', 'entity_id', 'entity_type', 'chapter_id']; protected $fillable = ['name', 'priority']; /** * Get the pages that this chapter contains. * * @return HasMany<Page, $this> */ public function pages(string $dir = 'ASC'): HasMany { return $this->hasMany(Page::class)->orderBy('priority', $dir); } /** * Get the url of this chapter. */ public function getUrl(string $path = ''): string { $parts = [ 'books', urlencode($this->book_slug ?? $this->book->slug), 'chapter', urlencode($this->slug), trim($path, '/'), ]; return url('/' . implode('/', $parts)); } /** * Get the visible pages in this chapter. * @return Collection<Page> */ public function getVisiblePages(): Collection { return $this->pages() ->scopes('visible') ->orderBy('draft', 'desc') ->orderBy('priority', 'asc') ->get(); } public function defaultTemplate(): EntityDefaultTemplate { return new EntityDefaultTemplate($this); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/EntityScope.php
app/Entities/Models/EntityScope.php
<?php namespace BookStack\Entities\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Scope; use Illuminate\Database\Query\JoinClause; class EntityScope implements Scope { /** * Apply the scope to a given Eloquent query builder. */ public function apply(Builder $builder, Model $model): void { $builder = $builder->where('type', '=', $model->getMorphClass()); $table = $model->getTable(); if ($model instanceof Page) { $builder->leftJoin('entity_page_data', 'entity_page_data.page_id', '=', "{$table}.id"); } else { $builder->leftJoin('entity_container_data', function (JoinClause $join) use ($model, $table) { $join->on('entity_container_data.entity_id', '=', "{$table}.id") ->where('entity_container_data.entity_type', '=', $model->getMorphClass()); }); } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/EntityQueryBuilder.php
app/Entities/Models/EntityQueryBuilder.php
<?php namespace BookStack\Entities\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Query\Builder as QueryBuilder; class EntityQueryBuilder extends Builder { /** * Create a new Eloquent query builder instance. */ public function __construct(QueryBuilder $query) { parent::__construct($query); $this->withGlobalScope('entity', new EntityScope()); } public function withoutGlobalScope($scope): static { // Prevent removal of the entity scope if ($scope === 'entity') { return $this; } return parent::withoutGlobalScope($scope); } /** * Override the default forceDelete method to add type filter onto the query * since it specifically ignores scopes by default. */ public function forceDelete() { return $this->query->where('type', '=', $this->model->getMorphClass())->delete(); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/PageRevision.php
app/Entities/Models/PageRevision.php
<?php namespace BookStack\Entities\Models; use BookStack\Activity\Models\Loggable; use BookStack\App\Model; use BookStack\Users\Models\User; use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * Class PageRevision. * * @property mixed $id * @property int $page_id * @property string $name * @property string $slug * @property string $book_slug * @property int $created_by * @property Carbon $created_at * @property Carbon $updated_at * @property string $type * @property string $summary * @property string $markdown * @property string $html * @property string $text * @property int $revision_number * @property Page $page * @property-read ?User $createdBy */ class PageRevision extends Model implements Loggable { use HasFactory; protected $fillable = ['name', 'text', 'summary']; protected $hidden = ['html', 'markdown', 'text']; /** * Get the user that created the page revision. */ public function createdBy(): BelongsTo { return $this->belongsTo(User::class, 'created_by'); } /** * Get the page this revision originates from. */ public function page(): BelongsTo { return $this->belongsTo(Page::class); } /** * Get the url for this revision. */ public function getUrl(string $path = ''): string { return $this->page->getUrl('/revisions/' . $this->id . '/' . ltrim($path, '/')); } /** * Get the previous revision for the same page if existing. */ public function getPreviousRevision(): ?PageRevision { $id = static::newQuery()->where('page_id', '=', $this->page_id) ->where('id', '<', $this->id) ->max('id'); if ($id) { return static::query()->find($id); } return null; } /** * Allows checking of the exact class, Used to check entity type. * Included here to align with entities in similar use cases. * (Yup, Bit of an awkward hack). * * @deprecated Use instanceof instead. */ public static function isA(string $type): bool { return $type === 'revision'; } public function logDescriptor(): string { return "Revision #{$this->revision_number} (ID: {$this->id}) for page ID {$this->page_id}"; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/Bookshelf.php
app/Entities/Models/Bookshelf.php
<?php namespace BookStack\Entities\Models; use BookStack\Entities\Tools\EntityCover; use BookStack\Uploads\Image; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; /** * @property string $description * @property string $description_html */ class Bookshelf extends Entity implements HasDescriptionInterface, HasCoverInterface { use HasFactory; use ContainerTrait; public float $searchFactor = 1.2; protected $hidden = ['image_id', 'deleted_at', 'description_html', 'priority', 'default_template_id', 'sort_rule_id', 'entity_id', 'entity_type', 'chapter_id', 'book_id']; protected $fillable = ['name']; /** * Get the books in this shelf. * Should not be used directly since it does not take into account permissions. */ public function books(): BelongsToMany { return $this->belongsToMany(Book::class, 'bookshelves_books', 'bookshelf_id', 'book_id') ->select(['entities.*', 'entity_container_data.*']) ->withPivot('order') ->orderBy('order', 'asc'); } /** * Related books that are visible to the current user. */ public function visibleBooks(): BelongsToMany { return $this->books()->scopes('visible'); } /** * Get the url for this bookshelf. */ public function getUrl(string $path = ''): string { return url('/shelves/' . implode('/', [urlencode($this->slug), trim($path, '/')])); } /** * Check if this shelf contains the given book. */ public function contains(Book $book): bool { return $this->books()->where('id', '=', $book->id)->count() > 0; } /** * Add a book to the end of this shelf. */ public function appendBook(Book $book): void { if ($this->contains($book)) { return; } $maxOrder = $this->books()->max('order'); $this->books()->attach($book->id, ['order' => $maxOrder + 1]); } public function coverInfo(): EntityCover { return new EntityCover($this); } public function cover(): BelongsTo { return $this->belongsTo(Image::class, 'image_id'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/ContainerTrait.php
app/Entities/Models/ContainerTrait.php
<?php namespace BookStack\Entities\Models; use BookStack\Entities\Tools\EntityHtmlDescription; use Illuminate\Database\Eloquent\Relations\HasOne; /** * @mixin Entity */ trait ContainerTrait { public function descriptionInfo(): EntityHtmlDescription { return new EntityHtmlDescription($this); } /** * @return HasOne<EntityContainerData, $this> */ public function relatedData(): HasOne { return $this->hasOne(EntityContainerData::class, 'entity_id', 'id') ->where('entity_type', '=', $this->getMorphClass()); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/EntityTable.php
app/Entities/Models/EntityTable.php
<?php namespace BookStack\Entities\Models; use BookStack\Activity\Models\Tag; use BookStack\Activity\Models\View; use BookStack\App\Model; use BookStack\Permissions\Models\EntityPermission; use BookStack\Permissions\Models\JointPermission; use BookStack\Permissions\PermissionApplicator; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\SoftDeletes; /** * This is a simplistic model interpretation of a generic Entity used to query and represent * that database abstractly. Generally, this should rarely be used outside queries. */ class EntityTable extends Model { use SoftDeletes; protected $table = 'entities'; /** * Get the entities that are visible to the current user. */ public function scopeVisible(Builder $query): Builder { return app()->make(PermissionApplicator::class)->restrictEntityQuery($query); } /** * Get the entity jointPermissions this is connected to. */ public function jointPermissions(): HasMany { return $this->hasMany(JointPermission::class, 'entity_id') ->whereColumn('entity_type', '=', 'entities.type'); } /** * Get the Tags that have been assigned to entities. */ public function tags(): HasMany { return $this->hasMany(Tag::class, 'entity_id') ->whereColumn('entity_type', '=', 'entities.type'); } /** * Get the assigned permissions. */ public function permissions(): HasMany { return $this->hasMany(EntityPermission::class, 'entity_id') ->whereColumn('entity_type', '=', 'entities.type'); } /** * Get View objects for this entity. */ public function views(): HasMany { return $this->hasMany(View::class, 'viewable_id') ->whereColumn('viewable_type', '=', 'entities.type'); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Models/Book.php
app/Entities/Models/Book.php
<?php namespace BookStack\Entities\Models; use BookStack\Entities\Tools\EntityCover; use BookStack\Entities\Tools\EntityDefaultTemplate; use BookStack\Sorting\SortRule; use BookStack\Uploads\Image; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Collection; /** * Class Book. * * @property string $description * @property string $description_html * @property int $image_id * @property ?int $default_template_id * @property ?int $sort_rule_id * @property \Illuminate\Database\Eloquent\Collection $chapters * @property \Illuminate\Database\Eloquent\Collection $pages * @property \Illuminate\Database\Eloquent\Collection $directPages * @property \Illuminate\Database\Eloquent\Collection $shelves * @property ?SortRule $sortRule */ class Book extends Entity implements HasDescriptionInterface, HasCoverInterface, HasDefaultTemplateInterface { use HasFactory; use ContainerTrait; public float $searchFactor = 1.2; protected $hidden = ['pivot', 'deleted_at', 'description_html', 'entity_id', 'entity_type', 'chapter_id', 'book_id', 'priority']; protected $fillable = ['name']; /** * Get the url for this book. */ public function getUrl(string $path = ''): string { return url('/books/' . implode('/', [urlencode($this->slug), trim($path, '/')])); } /** * Get all pages within this book. * @return HasMany<Page, $this> */ public function pages(): HasMany { return $this->hasMany(Page::class); } /** * Get the direct child pages of this book. */ public function directPages(): HasMany { return $this->pages()->whereNull('chapter_id'); } /** * Get all chapters within this book. * @return HasMany<Chapter, $this> */ public function chapters(): HasMany { return $this->hasMany(Chapter::class); } /** * Get the shelves this book is contained within. */ public function shelves(): BelongsToMany { return $this->belongsToMany(Bookshelf::class, 'bookshelves_books', 'book_id', 'bookshelf_id'); } /** * Get the direct child items within this book. */ public function getDirectVisibleChildren(): Collection { $pages = $this->directPages()->scopes('visible')->get(); $chapters = $this->chapters()->scopes('visible')->get(); return $pages->concat($chapters)->sortBy('priority')->sortByDesc('draft'); } public function defaultTemplate(): EntityDefaultTemplate { return new EntityDefaultTemplate($this); } public function cover(): BelongsTo { return $this->belongsTo(Image::class, 'image_id'); } public function coverInfo(): EntityCover { return new EntityCover($this); } /** * Get the sort rule assigned to this container, if existing. */ public function sortRule(): BelongsTo { return $this->belongsTo(SortRule::class); } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/PageIncludeContent.php
app/Entities/Tools/PageIncludeContent.php
<?php namespace BookStack\Entities\Tools; use BookStack\Util\HtmlDocument; use DOMNode; class PageIncludeContent { protected static array $topLevelTags = ['table', 'ul', 'ol', 'pre']; /** * @param DOMNode[] $contents * @param bool $isInline */ public function __construct( protected array $contents, protected bool $isInline, ) { } public static function fromHtmlAndTag(string $html, PageIncludeTag $tag): self { if (empty($html)) { return new self([], true); } $doc = new HtmlDocument($html); $sectionId = $tag->getSectionId(); if (!$sectionId) { $contents = [...$doc->getBodyChildren()]; return new self($contents, false); } $section = $doc->getElementById($sectionId); if (!$section) { return new self([], true); } $isTopLevel = in_array(strtolower($section->nodeName), static::$topLevelTags); $contents = $isTopLevel ? [$section] : [...$section->childNodes]; return new self($contents, !$isTopLevel); } public static function fromInlineHtml(string $html): self { if (empty($html)) { return new self([], true); } $doc = new HtmlDocument($html); return new self([...$doc->getBodyChildren()], true); } public function isInline(): bool { return $this->isInline; } public function isEmpty(): bool { return empty($this->contents); } /** * @return DOMNode[] */ public function toDomNodes(): array { return $this->contents; } public function toHtml(): string { $html = ''; foreach ($this->contents as $content) { $html .= $content->ownerDocument->saveHTML($content); } return $html; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/EntityHydrator.php
app/Entities/Tools/EntityHydrator.php
<?php namespace BookStack\Entities\Tools; use BookStack\Activity\Models\Tag; use BookStack\Entities\Models\Chapter; use BookStack\Entities\Models\Entity; use BookStack\Entities\Models\EntityTable; use BookStack\Entities\Models\Page; use BookStack\Entities\Queries\EntityQueries; use Illuminate\Database\Eloquent\Collection; class EntityHydrator { public function __construct( protected EntityQueries $entityQueries, ) { } /** * Hydrate the entities of this hydrator to return a list of entities represented * in their original intended models. * @param EntityTable[] $entities * @return Entity[] */ public function hydrate(array $entities, bool $loadTags = false, bool $loadParents = false): array { $hydrated = []; foreach ($entities as $entity) { $data = $entity->getRawOriginal(); $instance = Entity::instanceFromType($entity->type); if ($instance instanceof Page) { $data['text'] = $data['description']; unset($data['description']); } $instance = $instance->setRawAttributes($data, true); $hydrated[] = $instance; } if ($loadTags) { $this->loadTagsIntoModels($hydrated); } if ($loadParents) { $this->loadParentsIntoModels($hydrated); } return $hydrated; } /** * @param Entity[] $entities */ protected function loadTagsIntoModels(array $entities): void { $idsByType = []; $entityMap = []; foreach ($entities as $entity) { if (!isset($idsByType[$entity->type])) { $idsByType[$entity->type] = []; } $idsByType[$entity->type][] = $entity->id; $entityMap[$entity->type . ':' . $entity->id] = $entity; } $query = Tag::query(); foreach ($idsByType as $type => $ids) { $query->orWhere(function ($query) use ($type, $ids) { $query->where('entity_type', '=', $type) ->whereIn('entity_id', $ids); }); } $tags = empty($idsByType) ? [] : $query->get()->all(); $tagMap = []; foreach ($tags as $tag) { $key = $tag->entity_type . ':' . $tag->entity_id; if (!isset($tagMap[$key])) { $tagMap[$key] = []; } $tagMap[$key][] = $tag; } foreach ($entityMap as $key => $entity) { $entityTags = new Collection($tagMap[$key] ?? []); $entity->setRelation('tags', $entityTags); } } /** * @param Entity[] $entities */ protected function loadParentsIntoModels(array $entities): void { $parentsByType = ['book' => [], 'chapter' => []]; foreach ($entities as $entity) { if ($entity->getAttribute('book_id') !== null) { $parentsByType['book'][] = $entity->getAttribute('book_id'); } if ($entity->getAttribute('chapter_id') !== null) { $parentsByType['chapter'][] = $entity->getAttribute('chapter_id'); } } $parentQuery = $this->entityQueries->visibleForList(); $filtered = count($parentsByType['book']) > 0 || count($parentsByType['chapter']) > 0; $parentQuery = $parentQuery->where(function ($query) use ($parentsByType) { foreach ($parentsByType as $type => $ids) { if (count($ids) > 0) { $query = $query->orWhere(function ($query) use ($type, $ids) { $query->where('type', '=', $type) ->whereIn('id', $ids); }); } } }); $parentModels = $filtered ? $parentQuery->get()->all() : []; $parents = $this->hydrate($parentModels); $parentMap = []; foreach ($parents as $parent) { $parentMap[$parent->type . ':' . $parent->id] = $parent; } foreach ($entities as $entity) { if ($entity instanceof Page || $entity instanceof Chapter) { $key = 'book:' . $entity->getRawAttribute('book_id'); $entity->setRelation('book', $parentMap[$key] ?? null); } if ($entity instanceof Page) { $key = 'chapter:' . $entity->getRawAttribute('chapter_id'); $entity->setRelation('chapter', $parentMap[$key] ?? null); } } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/MixedEntityRequestHelper.php
app/Entities/Tools/MixedEntityRequestHelper.php
<?php namespace BookStack\Entities\Tools; use BookStack\Entities\EntityProvider; use BookStack\Entities\Models\Entity; class MixedEntityRequestHelper { public function __construct( protected EntityProvider $entities, ) { } /** * Query out an entity, visible to the current user, for the given * entity request details (this provided in a request validated by * this classes' validationRules method). * @param array{type: string, id: string} $requestData */ public function getVisibleEntityFromRequestData(array $requestData): Entity { $entityType = $this->entities->get($requestData['type']); return $entityType->newQuery()->scopes(['visible'])->findOrFail($requestData['id']); } /** * Get the validation rules for an abstract entity request. * @return array{type: string[], id: string[]} */ public function validationRules(): array { return [ 'type' => ['required', 'string'], 'id' => ['required', 'integer'], ]; } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false
BookStackApp/BookStack
https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Entities/Tools/PageIncludeParser.php
app/Entities/Tools/PageIncludeParser.php
<?php namespace BookStack\Entities\Tools; use BookStack\Util\HtmlDocument; use Closure; use DOMDocument; use DOMElement; use DOMNode; class PageIncludeParser { protected static string $includeTagRegex = "/{{@\s?([0-9].*?)}}/"; /** * Nodes to clean up and remove if left empty after a parsing operation. * @var DOMNode[] */ protected array $toCleanup = []; /** * @param Closure(PageIncludeTag $tag): PageContent $pageContentForId */ public function __construct( protected HtmlDocument $doc, protected Closure $pageContentForId, ) { } /** * Parse out the include tags. * Returns the count of new content DOM nodes added to the document. */ public function parse(): int { $nodesAdded = 0; $tags = $this->locateAndIsolateIncludeTags(); foreach ($tags as $tag) { /** @var PageIncludeContent $content */ $content = $this->pageContentForId->call($this, $tag); if (!$content->isInline()) { $parentP = $this->getParentParagraph($tag->domNode); $isWithinParentP = $parentP === $tag->domNode->parentNode; if ($parentP && $isWithinParentP) { $this->splitNodeAtChildNode($tag->domNode->parentNode, $tag->domNode); } else if ($parentP) { $this->moveTagNodeToBesideParent($tag, $parentP); } } $replacementNodes = $content->toDomNodes(); $nodesAdded += count($replacementNodes); $this->replaceNodeWithNodes($tag->domNode, $replacementNodes); } $this->cleanup(); return $nodesAdded; } /** * Locate include tags within the given document, isolating them to their * own nodes in the DOM for future targeted manipulation. * @return PageIncludeTag[] */ protected function locateAndIsolateIncludeTags(): array { $includeHosts = $this->doc->queryXPath("//*[text()[contains(., '{{@')]]"); $includeTags = []; /** @var DOMNode $node */ foreach ($includeHosts as $node) { /** @var DOMNode $childNode */ foreach ($node->childNodes as $childNode) { if ($childNode->nodeName === '#text') { array_push($includeTags, ...$this->splitTextNodesAtTags($childNode)); } } } return $includeTags; } /** * Takes a text DOMNode and splits its text content at include tags * into multiple text nodes within the original parent. * Returns found PageIncludeTag references. * @return PageIncludeTag[] */ protected function splitTextNodesAtTags(DOMNode $textNode): array { $includeTags = []; $text = $textNode->textContent; preg_match_all(static::$includeTagRegex, $text, $matches, PREG_OFFSET_CAPTURE); $currentOffset = 0; foreach ($matches[0] as $index => $fullTagMatch) { $tagOuterContent = $fullTagMatch[0]; $tagInnerContent = $matches[1][$index][0]; $tagStartOffset = $fullTagMatch[1]; if ($currentOffset < $tagStartOffset) { $previousText = substr($text, $currentOffset, $tagStartOffset - $currentOffset); $textNode->parentNode->insertBefore($this->doc->createTextNode($previousText), $textNode); } $node = $textNode->parentNode->insertBefore($this->doc->createTextNode($tagOuterContent), $textNode); $includeTags[] = new PageIncludeTag($tagInnerContent, $node); $currentOffset = $tagStartOffset + strlen($tagOuterContent); } if ($currentOffset > 0) { $textNode->textContent = substr($text, $currentOffset); } return $includeTags; } /** * Replace the given node with all those in $replacements * @param DOMNode[] $replacements */ protected function replaceNodeWithNodes(DOMNode $toReplace, array $replacements): void { /** @var DOMDocument $targetDoc */ $targetDoc = $toReplace->ownerDocument; foreach ($replacements as $replacement) { if ($replacement->ownerDocument !== $targetDoc) { $replacement = $targetDoc->importNode($replacement, true); } $toReplace->parentNode->insertBefore($replacement, $toReplace); } $toReplace->parentNode->removeChild($toReplace); } /** * Move a tag node to become a sibling of the given parent. * Will attempt to guess a position based upon the tag content within the parent. */ protected function moveTagNodeToBesideParent(PageIncludeTag $tag, DOMNode $parent): void { $parentText = $parent->textContent; $tagPos = strpos($parentText, $tag->tagContent); $before = $tagPos < (strlen($parentText) / 2); $this->toCleanup[] = $tag->domNode->parentNode; if ($before) { $parent->parentNode->insertBefore($tag->domNode, $parent); } else { $parent->parentNode->insertBefore($tag->domNode, $parent->nextSibling); } } /** * Splits the given $parentNode at the location of the $domNode within it. * Attempts to replicate the original $parentNode, moving some of their parent * children in where needed, before adding the $domNode between. */ protected function splitNodeAtChildNode(DOMElement $parentNode, DOMNode $domNode): void { $children = [...$parentNode->childNodes]; $splitPos = array_search($domNode, $children, true); if ($splitPos === false) { $splitPos = count($children) - 1; } $parentClone = $parentNode->cloneNode(); if (!($parentClone instanceof DOMElement)) { return; } $parentNode->parentNode->insertBefore($parentClone, $parentNode); $parentClone->removeAttribute('id'); for ($i = 0; $i < $splitPos; $i++) { /** @var DOMNode $child */ $child = $children[$i]; $parentClone->appendChild($child); } $parentNode->parentNode->insertBefore($domNode, $parentNode); $this->toCleanup[] = $parentNode; $this->toCleanup[] = $parentClone; } /** * Get the parent paragraph of the given node, if existing. */ protected function getParentParagraph(DOMNode $parent): ?DOMNode { do { if (strtolower($parent->nodeName) === 'p') { return $parent; } $parent = $parent->parentNode; } while ($parent !== null); return null; } /** * Clean up after a parse operation. * Removes stranded elements we may have left during the parse. */ protected function cleanup(): void { foreach ($this->toCleanup as $element) { $element->normalize(); while ($element->parentNode && !$element->hasChildNodes()) { $parent = $element->parentNode; $parent->removeChild($element); $element = $parent; } } } }
php
MIT
e6b754fad029d6c35e139b907d04e6510775997b
2026-01-04T15:02:34.418809Z
false