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/Exports/ZipExports/ZipExportReader.php | app/Exports/ZipExports/ZipExportReader.php | <?php
namespace BookStack\Exports\ZipExports;
use BookStack\Exceptions\ZipExportException;
use BookStack\Exports\ZipExports\Models\ZipExportBook;
use BookStack\Exports\ZipExports\Models\ZipExportChapter;
use BookStack\Exports\ZipExports\Models\ZipExportPage;
use BookStack\Util\WebSafeMimeSniffer;
use ZipArchive;
class ZipExportReader
{
protected ZipArchive $zip;
protected bool $open = false;
public function __construct(
protected string $zipPath,
) {
$this->zip = new ZipArchive();
}
/**
* @throws ZipExportException
*/
protected function open(): void
{
if ($this->open) {
return;
}
// Validate file exists
if (!file_exists($this->zipPath) || !is_readable($this->zipPath)) {
throw new ZipExportException(trans('errors.import_zip_cant_read'));
}
// Validate file is valid zip
$opened = $this->zip->open($this->zipPath, ZipArchive::RDONLY);
if ($opened !== true) {
throw new ZipExportException(trans('errors.import_zip_cant_read'));
}
$this->open = true;
}
public function close(): void
{
if ($this->open) {
$this->zip->close();
$this->open = false;
}
}
/**
* @throws ZipExportException
*/
public function readData(): array
{
$this->open();
$info = $this->zip->statName('data.json');
if ($info === false) {
throw new ZipExportException(trans('errors.import_zip_cant_decode_data'));
}
$maxSize = max(intval(config()->get('app.upload_limit')), 1) * 1000000;
if ($info['size'] > $maxSize) {
throw new ZipExportException(trans('errors.import_zip_data_too_large'));
}
// Validate json data exists, including metadata
$jsonData = $this->zip->getFromName('data.json') ?: '';
$importData = json_decode($jsonData, true);
if (!$importData) {
throw new ZipExportException(trans('errors.import_zip_cant_decode_data'));
}
return $importData;
}
public function fileExists(string $fileName): bool
{
return $this->zip->statName("files/{$fileName}") !== false;
}
public function fileWithinSizeLimit(string $fileName): bool
{
$fileInfo = $this->zip->statName("files/{$fileName}");
if ($fileInfo === false) {
return false;
}
$maxSize = max(intval(config()->get('app.upload_limit')), 1) * 1000000;
return $fileInfo['size'] <= $maxSize;
}
/**
* @return false|resource
*/
public function streamFile(string $fileName)
{
return $this->zip->getStream("files/{$fileName}");
}
/**
* Sniff the mime type from the file of given name.
*/
public function sniffFileMime(string $fileName): string
{
$stream = $this->streamFile($fileName);
$sniffContent = fread($stream, 2000);
return (new WebSafeMimeSniffer())->sniff($sniffContent);
}
/**
* @throws ZipExportException
*/
public function decodeDataToExportModel(): ZipExportBook|ZipExportChapter|ZipExportPage
{
$data = $this->readData();
if (isset($data['book'])) {
return ZipExportBook::fromArray($data['book']);
} else if (isset($data['chapter'])) {
return ZipExportChapter::fromArray($data['chapter']);
} else if (isset($data['page'])) {
return ZipExportPage::fromArray($data['page']);
}
throw new ZipExportException("Could not identify content in ZIP file data.");
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/ZipExportFiles.php | app/Exports/ZipExports/ZipExportFiles.php | <?php
namespace BookStack\Exports\ZipExports;
use BookStack\Uploads\Attachment;
use BookStack\Uploads\AttachmentService;
use BookStack\Uploads\Image;
use BookStack\Uploads\ImageService;
use Illuminate\Support\Str;
class ZipExportFiles
{
/**
* References for attachments by attachment ID.
* @var array<int, string>
*/
protected array $attachmentRefsById = [];
/**
* References for images by image ID.
* @var array<int, string>
*/
protected array $imageRefsById = [];
public function __construct(
protected AttachmentService $attachmentService,
protected ImageService $imageService,
) {
}
/**
* Gain a reference to the given attachment instance.
* This is expected to be a file-based attachment that the user
* has visibility of, no permission/access checks are performed here.
*/
public function referenceForAttachment(Attachment $attachment): string
{
if (isset($this->attachmentRefsById[$attachment->id])) {
return $this->attachmentRefsById[$attachment->id];
}
$existingFiles = $this->getAllFileNames();
do {
$fileName = Str::random(20) . '.' . $attachment->extension;
} while (in_array($fileName, $existingFiles));
$this->attachmentRefsById[$attachment->id] = $fileName;
return $fileName;
}
/**
* Gain a reference to the given image instance.
* This is expected to be an image that the user has visibility of,
* no permission/access checks are performed here.
*/
public function referenceForImage(Image $image): string
{
if (isset($this->imageRefsById[$image->id])) {
return $this->imageRefsById[$image->id];
}
$existingFiles = $this->getAllFileNames();
$extension = pathinfo($image->path, PATHINFO_EXTENSION);
do {
$fileName = Str::random(20) . '.' . $extension;
} while (in_array($fileName, $existingFiles));
$this->imageRefsById[$image->id] = $fileName;
return $fileName;
}
protected function getAllFileNames(): array
{
return array_merge(
array_values($this->attachmentRefsById),
array_values($this->imageRefsById),
);
}
/**
* Extract each of the ZIP export tracked files.
* Calls the given callback for each tracked file, passing a temporary
* file reference of the file contents, and the zip-local tracked reference.
*/
public function extractEach(callable $callback): void
{
foreach ($this->attachmentRefsById as $attachmentId => $ref) {
$attachment = Attachment::query()->find($attachmentId);
$stream = $this->attachmentService->streamAttachmentFromStorage($attachment);
$tmpFile = tempnam(sys_get_temp_dir(), 'bszipfile-');
$tmpFileStream = fopen($tmpFile, 'w');
stream_copy_to_stream($stream, $tmpFileStream);
$callback($tmpFile, $ref);
}
foreach ($this->imageRefsById as $imageId => $ref) {
$image = Image::query()->find($imageId);
$stream = $this->imageService->getImageStream($image);
$tmpFile = tempnam(sys_get_temp_dir(), 'bszipimage-');
$tmpFileStream = fopen($tmpFile, 'w');
stream_copy_to_stream($stream, $tmpFileStream);
$callback($tmpFile, $ref);
}
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/ZipFileReferenceRule.php | app/Exports/ZipExports/ZipFileReferenceRule.php | <?php
namespace BookStack\Exports\ZipExports;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class ZipFileReferenceRule implements ValidationRule
{
public function __construct(
protected ZipValidationHelper $context,
protected array $acceptedMimes,
) {
}
/**
* @inheritDoc
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (!$this->context->zipReader->fileExists($value)) {
$fail('validation.zip_file')->translate();
}
if (!$this->context->zipReader->fileWithinSizeLimit($value)) {
$fail('validation.zip_file_size')->translate([
'attribute' => $value,
'size' => config('app.upload_limit'),
]);
}
if (!empty($this->acceptedMimes)) {
$fileMime = $this->context->zipReader->sniffFileMime($value);
if (!in_array($fileMime, $this->acceptedMimes)) {
$fail('validation.zip_file_mime')->translate([
'attribute' => $attribute,
'validTypes' => implode(',', $this->acceptedMimes),
'foundType' => $fileMime
]);
}
}
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/ZipValidationHelper.php | app/Exports/ZipExports/ZipValidationHelper.php | <?php
namespace BookStack\Exports\ZipExports;
use BookStack\Exports\ZipExports\Models\ZipExportModel;
use Illuminate\Validation\Factory;
class ZipValidationHelper
{
protected Factory $validationFactory;
/**
* Local store of validated IDs (in format "<type>:<id>". Example: "book:2")
* which we can use to check uniqueness.
* @var array<string, bool>
*/
protected array $validatedIds = [];
public function __construct(
public ZipExportReader $zipReader,
) {
$this->validationFactory = app(Factory::class);
}
public function validateData(array $data, array $rules): array
{
$messages = $this->validationFactory->make($data, $rules)->errors()->messages();
foreach ($messages as $key => $message) {
$messages[$key] = implode("\n", $message);
}
return $messages;
}
public function fileReferenceRule(array $acceptedMimes = []): ZipFileReferenceRule
{
return new ZipFileReferenceRule($this, $acceptedMimes);
}
public function uniqueIdRule(string $type): ZipUniqueIdRule
{
return new ZipUniqueIdRule($this, $type);
}
public function hasIdBeenUsed(string $type, mixed $id): bool
{
$key = $type . ':' . $id;
if (isset($this->validatedIds[$key])) {
return true;
}
$this->validatedIds[$key] = true;
return false;
}
/**
* Validate an array of relation data arrays that are expected
* to be for the given ZipExportModel.
* @param class-string<ZipExportModel> $model
*/
public function validateRelations(array $relations, string $model): array
{
$results = [];
foreach ($relations as $key => $relationData) {
if (is_array($relationData)) {
$results[$key] = $model::validate($this, $relationData);
} else {
$results[$key] = [trans('validation.zip_model_expected', ['type' => gettype($relationData)])];
}
}
return $results;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/ZipUniqueIdRule.php | app/Exports/ZipExports/ZipUniqueIdRule.php | <?php
namespace BookStack\Exports\ZipExports;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class ZipUniqueIdRule implements ValidationRule
{
public function __construct(
protected ZipValidationHelper $context,
protected string $modelType,
) {
}
/**
* @inheritDoc
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if ($this->context->hasIdBeenUsed($this->modelType, $value)) {
$fail('validation.zip_unique')->translate(['attribute' => $attribute]);
}
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/ZipExportBuilder.php | app/Exports/ZipExports/ZipExportBuilder.php | <?php
namespace BookStack\Exports\ZipExports;
use BookStack\App\AppVersion;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Models\Page;
use BookStack\Exceptions\ZipExportException;
use BookStack\Exports\ZipExports\Models\ZipExportBook;
use BookStack\Exports\ZipExports\Models\ZipExportChapter;
use BookStack\Exports\ZipExports\Models\ZipExportPage;
use ZipArchive;
class ZipExportBuilder
{
protected array $data = [];
public function __construct(
protected ZipExportFiles $files,
protected ZipExportReferences $references,
) {
}
/**
* @throws ZipExportException
*/
public function buildForPage(Page $page): string
{
$exportPage = ZipExportPage::fromModel($page, $this->files);
$this->data['page'] = $exportPage;
$this->references->addPage($exportPage);
return $this->build();
}
/**
* @throws ZipExportException
*/
public function buildForChapter(Chapter $chapter): string
{
$exportChapter = ZipExportChapter::fromModel($chapter, $this->files);
$this->data['chapter'] = $exportChapter;
$this->references->addChapter($exportChapter);
return $this->build();
}
/**
* @throws ZipExportException
*/
public function buildForBook(Book $book): string
{
$exportBook = ZipExportBook::fromModel($book, $this->files);
$this->data['book'] = $exportBook;
$this->references->addBook($exportBook);
return $this->build();
}
/**
* @throws ZipExportException
*/
protected function build(): string
{
$this->references->buildReferences($this->files);
$this->data['exported_at'] = date(DATE_ATOM);
$this->data['instance'] = [
'id' => setting('instance-id', ''),
'version' => AppVersion::get(),
];
$zipFile = tempnam(sys_get_temp_dir(), 'bszip-');
$zip = new ZipArchive();
$opened = $zip->open($zipFile, ZipArchive::OVERWRITE);
if ($opened !== true) {
throw new ZipExportException('Failed to create zip file for export.');
}
$zip->addFromString('data.json', json_encode($this->data));
$zip->addEmptyDir('files');
$toRemove = [];
$addedNames = [];
try {
$this->files->extractEach(function ($filePath, $fileRef) use ($zip, &$toRemove, &$addedNames) {
$entryName = "files/$fileRef";
$zip->addFile($filePath, $entryName);
$toRemove[] = $filePath;
$addedNames[] = $entryName;
});
} catch (\Exception $exception) {
// Cleanup the files we've processed so far and respond back with error
foreach ($toRemove as $file) {
unlink($file);
}
foreach ($addedNames as $name) {
$zip->deleteName($name);
}
$zip->close();
unlink($zipFile);
throw new ZipExportException("Failed to add files for ZIP export, received error: " . $exception->getMessage());
}
$zip->close();
foreach ($toRemove as $file) {
unlink($file);
}
return $zipFile;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/ZipReferenceParser.php | app/Exports/ZipExports/ZipReferenceParser.php | <?php
namespace BookStack\Exports\ZipExports;
use BookStack\App\Model;
use BookStack\Entities\Queries\EntityQueries;
use BookStack\References\ModelResolvers\AttachmentModelResolver;
use BookStack\References\ModelResolvers\BookLinkModelResolver;
use BookStack\References\ModelResolvers\ChapterLinkModelResolver;
use BookStack\References\ModelResolvers\CrossLinkModelResolver;
use BookStack\References\ModelResolvers\ImageModelResolver;
use BookStack\References\ModelResolvers\PageLinkModelResolver;
use BookStack\References\ModelResolvers\PagePermalinkModelResolver;
use BookStack\Uploads\ImageStorage;
class ZipReferenceParser
{
/**
* @var CrossLinkModelResolver[]|null
*/
protected ?array $modelResolvers = null;
public function __construct(
protected EntityQueries $queries
) {
}
/**
* Parse and replace references in the given content.
* Calls the handler for each model link detected and replaces the link
* with the handler return value if provided.
* Returns the resulting content with links replaced.
* @param callable(Model):(string|null) $handler
*/
public function parseLinks(string $content, callable $handler): string
{
$linkRegex = $this->getLinkRegex();
$matches = [];
preg_match_all($linkRegex, $content, $matches);
if (count($matches) < 2) {
return $content;
}
foreach ($matches[1] as $link) {
$model = $this->linkToModel($link);
if ($model) {
$result = $handler($model);
if ($result !== null) {
$content = str_replace($link, $result, $content);
}
}
}
return $content;
}
/**
* Parse and replace references in the given content.
* Calls the handler for each reference detected and replaces the link
* with the handler return value if provided.
* Returns the resulting content string with references replaced.
* @param callable(string $type, int $id):(string|null) $handler
*/
public function parseReferences(string $content, callable $handler): string
{
$referenceRegex = '/\[\[bsexport:([a-z]+):(\d+)]]/';
$matches = [];
preg_match_all($referenceRegex, $content, $matches);
if (count($matches) < 3) {
return $content;
}
for ($i = 0; $i < count($matches[0]); $i++) {
$referenceText = $matches[0][$i];
$type = strtolower($matches[1][$i]);
$id = intval($matches[2][$i]);
$result = $handler($type, $id);
if ($result !== null) {
$content = str_replace($referenceText, $result, $content);
}
}
return $content;
}
/**
* Attempt to resolve the given link to a model using the instance model resolvers.
*/
protected function linkToModel(string $link): ?Model
{
foreach ($this->getModelResolvers() as $resolver) {
$model = $resolver->resolve($link);
if (!is_null($model)) {
return $model;
}
}
return null;
}
protected function getModelResolvers(): array
{
if (isset($this->modelResolvers)) {
return $this->modelResolvers;
}
$this->modelResolvers = [
new PagePermalinkModelResolver($this->queries->pages),
new PageLinkModelResolver($this->queries->pages),
new ChapterLinkModelResolver($this->queries->chapters),
new BookLinkModelResolver($this->queries->books),
new ImageModelResolver(),
new AttachmentModelResolver(),
];
return $this->modelResolvers;
}
/**
* Build the regex to identify links we should handle in content.
*/
protected function getLinkRegex(): string
{
$urls = [rtrim(url('/'), '/')];
$imageUrl = rtrim(ImageStorage::getPublicUrl('/'), '/');
if ($urls[0] !== $imageUrl) {
$urls[] = $imageUrl;
}
$urlBaseRegex = implode('|', array_map(function ($url) {
return preg_quote($url, '/');
}, $urls));
return "/(({$urlBaseRegex}).*?)[\\t\\n\\f>\"'=?#()]/";
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/ZipImportRunner.php | app/Exports/ZipExports/ZipImportRunner.php | <?php
namespace BookStack\Exports\ZipExports;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Repos\BookRepo;
use BookStack\Entities\Repos\ChapterRepo;
use BookStack\Entities\Repos\PageRepo;
use BookStack\Exceptions\ZipExportException;
use BookStack\Exceptions\ZipImportException;
use BookStack\Exports\Import;
use BookStack\Exports\ZipExports\Models\ZipExportAttachment;
use BookStack\Exports\ZipExports\Models\ZipExportBook;
use BookStack\Exports\ZipExports\Models\ZipExportChapter;
use BookStack\Exports\ZipExports\Models\ZipExportImage;
use BookStack\Exports\ZipExports\Models\ZipExportPage;
use BookStack\Exports\ZipExports\Models\ZipExportTag;
use BookStack\Permissions\Permission;
use BookStack\Uploads\Attachment;
use BookStack\Uploads\AttachmentService;
use BookStack\Uploads\FileStorage;
use BookStack\Uploads\Image;
use BookStack\Uploads\ImageService;
use Illuminate\Http\UploadedFile;
class ZipImportRunner
{
protected array $tempFilesToCleanup = [];
public function __construct(
protected FileStorage $storage,
protected PageRepo $pageRepo,
protected ChapterRepo $chapterRepo,
protected BookRepo $bookRepo,
protected ImageService $imageService,
protected AttachmentService $attachmentService,
protected ZipImportReferences $references,
) {
}
/**
* Run the import.
* Performs re-validation on zip, validation on parent provided, and permissions for importing
* the planned content, before running the import process.
* Returns the top-level entity item which was imported.
* @throws ZipImportException
*/
public function run(Import $import, ?Entity $parent = null): Entity
{
$zipPath = $this->getZipPath($import);
$reader = new ZipExportReader($zipPath);
$errors = (new ZipExportValidator($reader))->validate();
if ($errors) {
throw new ZipImportException([
trans('errors.import_validation_failed'),
...$errors,
]);
}
try {
$exportModel = $reader->decodeDataToExportModel();
} catch (ZipExportException $e) {
throw new ZipImportException([$e->getMessage()]);
}
// Validate parent type
if ($exportModel instanceof ZipExportBook && ($parent !== null)) {
throw new ZipImportException(["Must not have a parent set for a Book import."]);
} else if ($exportModel instanceof ZipExportChapter && !($parent instanceof Book)) {
throw new ZipImportException(["Parent book required for chapter import."]);
} else if ($exportModel instanceof ZipExportPage && !($parent instanceof Book || $parent instanceof Chapter)) {
throw new ZipImportException(["Parent book or chapter required for page import."]);
}
$this->ensurePermissionsPermitImport($exportModel, $parent);
if ($exportModel instanceof ZipExportBook) {
$entity = $this->importBook($exportModel, $reader);
} else if ($exportModel instanceof ZipExportChapter) {
$entity = $this->importChapter($exportModel, $parent, $reader);
} else if ($exportModel instanceof ZipExportPage) {
$entity = $this->importPage($exportModel, $parent, $reader);
} else {
throw new ZipImportException(['No importable data found in import data.']);
}
$this->references->replaceReferences();
$reader->close();
$this->cleanup();
return $entity;
}
/**
* Revert any files which have been stored during this import process.
* Considers files only, and avoids the database under the
* assumption that the database may already have been
* reverted as part of a transaction rollback.
*/
public function revertStoredFiles(): void
{
foreach ($this->references->images() as $image) {
$this->imageService->destroyFileAtPath($image->type, $image->path);
}
foreach ($this->references->attachments() as $attachment) {
if (!$attachment->external) {
$this->attachmentService->deleteFileInStorage($attachment);
}
}
$this->cleanup();
}
protected function cleanup(): void
{
foreach ($this->tempFilesToCleanup as $file) {
unlink($file);
}
$this->tempFilesToCleanup = [];
}
protected function importBook(ZipExportBook $exportBook, ZipExportReader $reader): Book
{
$book = $this->bookRepo->create([
'name' => $exportBook->name,
'description_html' => $exportBook->description_html ?? '',
'image' => $exportBook->cover ? $this->zipFileToUploadedFile($exportBook->cover, $reader) : null,
'tags' => $this->exportTagsToInputArray($exportBook->tags ?? []),
]);
if ($book->coverInfo()->getImage()) {
$this->references->addImage($book->coverInfo()->getImage(), null);
}
$children = [
...$exportBook->chapters,
...$exportBook->pages,
];
usort($children, function (ZipExportPage|ZipExportChapter $a, ZipExportPage|ZipExportChapter $b) {
return ($a->priority ?? 0) - ($b->priority ?? 0);
});
foreach ($children as $child) {
if ($child instanceof ZipExportChapter) {
$this->importChapter($child, $book, $reader);
} else if ($child instanceof ZipExportPage) {
$this->importPage($child, $book, $reader);
}
}
$this->references->addBook($book, $exportBook);
return $book;
}
protected function importChapter(ZipExportChapter $exportChapter, Book $parent, ZipExportReader $reader): Chapter
{
$chapter = $this->chapterRepo->create([
'name' => $exportChapter->name,
'description_html' => $exportChapter->description_html ?? '',
'tags' => $this->exportTagsToInputArray($exportChapter->tags ?? []),
], $parent);
$exportPages = $exportChapter->pages;
usort($exportPages, function (ZipExportPage $a, ZipExportPage $b) {
return ($a->priority ?? 0) - ($b->priority ?? 0);
});
foreach ($exportPages as $exportPage) {
$this->importPage($exportPage, $chapter, $reader);
}
$this->references->addChapter($chapter, $exportChapter);
return $chapter;
}
protected function importPage(ZipExportPage $exportPage, Book|Chapter $parent, ZipExportReader $reader): Page
{
$page = $this->pageRepo->getNewDraftPage($parent);
foreach ($exportPage->attachments as $exportAttachment) {
$this->importAttachment($exportAttachment, $page, $reader);
}
foreach ($exportPage->images as $exportImage) {
$this->importImage($exportImage, $page, $reader);
}
$this->pageRepo->publishDraft($page, [
'name' => $exportPage->name,
'markdown' => $exportPage->markdown ?? '',
'html' => $exportPage->html ?? '',
'tags' => $this->exportTagsToInputArray($exportPage->tags ?? []),
]);
$this->references->addPage($page, $exportPage);
return $page;
}
protected function importAttachment(ZipExportAttachment $exportAttachment, Page $page, ZipExportReader $reader): Attachment
{
if ($exportAttachment->file) {
$file = $this->zipFileToUploadedFile($exportAttachment->file, $reader);
$attachment = $this->attachmentService->saveNewUpload($file, $page->id);
$attachment->name = $exportAttachment->name;
$attachment->save();
} else {
$attachment = $this->attachmentService->saveNewFromLink(
$exportAttachment->name,
$exportAttachment->link ?? '',
$page->id,
);
}
$this->references->addAttachment($attachment, $exportAttachment->id);
return $attachment;
}
protected function importImage(ZipExportImage $exportImage, Page $page, ZipExportReader $reader): Image
{
$mime = $reader->sniffFileMime($exportImage->file);
$extension = explode('/', $mime)[1];
$file = $this->zipFileToUploadedFile($exportImage->file, $reader);
$image = $this->imageService->saveNewFromUpload(
$file,
$exportImage->type,
$page->id,
null,
null,
true,
$exportImage->name . '.' . $extension,
);
$image->name = $exportImage->name;
$image->save();
$this->references->addImage($image, $exportImage->id);
return $image;
}
protected function exportTagsToInputArray(array $exportTags): array
{
$tags = [];
/** @var ZipExportTag $tag */
foreach ($exportTags as $tag) {
$tags[] = ['name' => $tag->name, 'value' => $tag->value ?? ''];
}
return $tags;
}
protected function zipFileToUploadedFile(string $fileName, ZipExportReader $reader): UploadedFile
{
if (!$reader->fileWithinSizeLimit($fileName)) {
throw new ZipImportException([
"File $fileName exceeds app upload limit."
]);
}
$tempPath = tempnam(sys_get_temp_dir(), 'bszipextract');
$fileStream = $reader->streamFile($fileName);
$tempStream = fopen($tempPath, 'wb');
stream_copy_to_stream($fileStream, $tempStream);
fclose($tempStream);
$this->tempFilesToCleanup[] = $tempPath;
return new UploadedFile($tempPath, $fileName);
}
/**
* @throws ZipImportException
*/
protected function ensurePermissionsPermitImport(ZipExportPage|ZipExportChapter|ZipExportBook $exportModel, Book|Chapter|null $parent = null): void
{
$errors = [];
$chapters = [];
$pages = [];
$images = [];
$attachments = [];
if ($exportModel instanceof ZipExportBook) {
if (!userCan(Permission::BookCreateAll)) {
$errors[] = trans('errors.import_perms_books');
}
array_push($pages, ...$exportModel->pages);
array_push($chapters, ...$exportModel->chapters);
} else if ($exportModel instanceof ZipExportChapter) {
$chapters[] = $exportModel;
} else if ($exportModel instanceof ZipExportPage) {
$pages[] = $exportModel;
}
foreach ($chapters as $chapter) {
array_push($pages, ...$chapter->pages);
}
if (count($chapters) > 0) {
$permission = 'chapter-create' . ($parent ? '' : '-all');
if (!userCan($permission, $parent)) {
$errors[] = trans('errors.import_perms_chapters');
}
}
foreach ($pages as $page) {
array_push($attachments, ...$page->attachments);
array_push($images, ...$page->images);
}
if (count($pages) > 0) {
if ($parent) {
if (!userCan(Permission::PageCreate, $parent)) {
$errors[] = trans('errors.import_perms_pages');
}
} else {
$hasPermission = userCan(Permission::PageCreateAll) || userCan(Permission::PageCreateOwn);
if (!$hasPermission) {
$errors[] = trans('errors.import_perms_pages');
}
}
}
if (count($images) > 0) {
if (!userCan(Permission::ImageCreateAll)) {
$errors[] = trans('errors.import_perms_images');
}
}
if (count($attachments) > 0) {
if (!userCan(Permission::AttachmentCreateAll)) {
$errors[] = trans('errors.import_perms_attachments');
}
}
if (count($errors)) {
throw new ZipImportException($errors);
}
}
protected function getZipPath(Import $import): string
{
if (!$this->storage->isRemote()) {
return $this->storage->getSystemPath($import->path);
}
$tempFilePath = tempnam(sys_get_temp_dir(), 'bszip-import-');
$tempFile = fopen($tempFilePath, 'wb');
$stream = $this->storage->getReadStream($import->path);
stream_copy_to_stream($stream, $tempFile);
fclose($tempFile);
$this->tempFilesToCleanup[] = $tempFilePath;
return $tempFilePath;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/ZipImportReferences.php | app/Exports/ZipExports/ZipImportReferences.php | <?php
namespace BookStack\Exports\ZipExports;
use BookStack\App\Model;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Repos\BaseRepo;
use BookStack\Entities\Repos\PageRepo;
use BookStack\Exports\ZipExports\Models\ZipExportBook;
use BookStack\Exports\ZipExports\Models\ZipExportChapter;
use BookStack\Exports\ZipExports\Models\ZipExportPage;
use BookStack\Uploads\Attachment;
use BookStack\Uploads\Image;
use BookStack\Uploads\ImageResizer;
class ZipImportReferences
{
/** @var Page[] */
protected array $pages = [];
/** @var Chapter[] */
protected array $chapters = [];
/** @var Book[] */
protected array $books = [];
/** @var Attachment[] */
protected array $attachments = [];
/** @var Image[] */
protected array $images = [];
/**
* Mapping keyed by "type:old-reference-id" with values being the new imported equivalent model.
* @var array<string, Model>
*/
protected array $referenceMap = [];
/** @var array<int, ZipExportPage> */
protected array $zipExportPageMap = [];
/** @var array<int, ZipExportChapter> */
protected array $zipExportChapterMap = [];
/** @var array<int, ZipExportBook> */
protected array $zipExportBookMap = [];
public function __construct(
protected ZipReferenceParser $parser,
protected BaseRepo $baseRepo,
protected PageRepo $pageRepo,
protected ImageResizer $imageResizer,
) {
}
protected function addReference(string $type, Model $model, ?int $importId): void
{
if ($importId) {
$key = $type . ':' . $importId;
$this->referenceMap[$key] = $model;
}
}
public function addPage(Page $page, ZipExportPage $exportPage): void
{
$this->pages[] = $page;
$this->zipExportPageMap[$page->id] = $exportPage;
$this->addReference('page', $page, $exportPage->id);
}
public function addChapter(Chapter $chapter, ZipExportChapter $exportChapter): void
{
$this->chapters[] = $chapter;
$this->zipExportChapterMap[$chapter->id] = $exportChapter;
$this->addReference('chapter', $chapter, $exportChapter->id);
}
public function addBook(Book $book, ZipExportBook $exportBook): void
{
$this->books[] = $book;
$this->zipExportBookMap[$book->id] = $exportBook;
$this->addReference('book', $book, $exportBook->id);
}
public function addAttachment(Attachment $attachment, ?int $importId): void
{
$this->attachments[] = $attachment;
$this->addReference('attachment', $attachment, $importId);
}
public function addImage(Image $image, ?int $importId): void
{
$this->images[] = $image;
$this->addReference('image', $image, $importId);
}
protected function handleReference(string $type, int $id): ?string
{
$key = $type . ':' . $id;
$model = $this->referenceMap[$key] ?? null;
if ($model instanceof Entity) {
return $model->getUrl();
} else if ($model instanceof Image) {
if ($model->type === 'gallery') {
$this->imageResizer->loadGalleryThumbnailsForImage($model, false);
return $model->thumbs['display'] ?? $model->url;
}
return $model->url;
} else if ($model instanceof Attachment) {
return $model->getUrl(false);
}
return null;
}
protected function replaceDrawingIdReferences(string $content): string
{
$referenceRegex = '/\sdrawio-diagram=[\'"](\d+)[\'"]/';
$result = preg_replace_callback($referenceRegex, function ($matches) {
$key = 'image:' . $matches[1];
$model = $this->referenceMap[$key] ?? null;
if ($model instanceof Image && $model->type === 'drawio') {
return ' drawio-diagram="' . $model->id . '"';
}
return $matches[0];
}, $content);
return $result ?: $content;
}
public function replaceReferences(): void
{
foreach ($this->books as $book) {
$exportBook = $this->zipExportBookMap[$book->id];
$content = $exportBook->description_html ?? '';
$parsed = $this->parser->parseReferences($content, $this->handleReference(...));
$this->baseRepo->update($book, [
'description_html' => $parsed,
]);
}
foreach ($this->chapters as $chapter) {
$exportChapter = $this->zipExportChapterMap[$chapter->id];
$content = $exportChapter->description_html ?? '';
$parsed = $this->parser->parseReferences($content, $this->handleReference(...));
$this->baseRepo->update($chapter, [
'description_html' => $parsed,
]);
}
foreach ($this->pages as $page) {
$exportPage = $this->zipExportPageMap[$page->id];
$contentType = $exportPage->markdown ? 'markdown' : 'html';
$content = $exportPage->markdown ?: ($exportPage->html ?: '');
$parsed = $this->parser->parseReferences($content, $this->handleReference(...));
$parsed = $this->replaceDrawingIdReferences($parsed);
$this->pageRepo->setContentFromInput($page, [
$contentType => $parsed,
]);
}
}
/**
* @return Image[]
*/
public function images(): array
{
return $this->images;
}
/**
* @return Attachment[]
*/
public function attachments(): array
{
return $this->attachments;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/Models/ZipExportBook.php | app/Exports/ZipExports/Models/ZipExportBook.php | <?php
namespace BookStack\Exports\ZipExports\Models;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Models\Page;
use BookStack\Exports\ZipExports\ZipExportFiles;
use BookStack\Exports\ZipExports\ZipValidationHelper;
final class ZipExportBook extends ZipExportModel
{
public ?int $id = null;
public string $name;
public ?string $description_html = null;
public ?string $cover = null;
/** @var ZipExportChapter[] */
public array $chapters = [];
/** @var ZipExportPage[] */
public array $pages = [];
/** @var ZipExportTag[] */
public array $tags = [];
public function metadataOnly(): void
{
$this->description_html = $this->cover = null;
foreach ($this->chapters as $chapter) {
$chapter->metadataOnly();
}
foreach ($this->pages as $page) {
$page->metadataOnly();
}
foreach ($this->tags as $tag) {
$tag->metadataOnly();
}
}
public function children(): array
{
$children = [
...$this->pages,
...$this->chapters,
];
usort($children, function ($a, $b) {
return ($a->priority ?? 0) - ($b->priority ?? 0);
});
return $children;
}
public static function fromModel(Book $model, ZipExportFiles $files): self
{
$instance = new self();
$instance->id = $model->id;
$instance->name = $model->name;
$instance->description_html = $model->descriptionInfo()->getHtml();
if ($model->coverInfo()->exists()) {
$instance->cover = $files->referenceForImage($model->coverInfo()->getImage());
}
$instance->tags = ZipExportTag::fromModelArray($model->tags()->get()->all());
$chapters = [];
$pages = [];
$children = $model->getDirectVisibleChildren()->all();
foreach ($children as $child) {
if ($child instanceof Chapter) {
$chapters[] = $child;
} else if ($child instanceof Page && !$child->draft) {
$pages[] = $child;
}
}
$instance->pages = ZipExportPage::fromModelArray($pages, $files);
$instance->chapters = ZipExportChapter::fromModelArray($chapters, $files);
return $instance;
}
public static function validate(ZipValidationHelper $context, array $data): array
{
$rules = [
'id' => ['nullable', 'int', $context->uniqueIdRule('book')],
'name' => ['required', 'string', 'min:1'],
'description_html' => ['nullable', 'string'],
'cover' => ['nullable', 'string', $context->fileReferenceRule()],
'tags' => ['array'],
'pages' => ['array'],
'chapters' => ['array'],
];
$errors = $context->validateData($data, $rules);
$errors['tags'] = $context->validateRelations($data['tags'] ?? [], ZipExportTag::class);
$errors['pages'] = $context->validateRelations($data['pages'] ?? [], ZipExportPage::class);
$errors['chapters'] = $context->validateRelations($data['chapters'] ?? [], ZipExportChapter::class);
return $errors;
}
public static function fromArray(array $data): static
{
$model = new static();
$model->id = $data['id'] ?? null;
$model->name = $data['name'];
$model->description_html = $data['description_html'] ?? null;
$model->cover = $data['cover'] ?? null;
$model->tags = ZipExportTag::fromManyArray($data['tags'] ?? []);
$model->pages = ZipExportPage::fromManyArray($data['pages'] ?? []);
$model->chapters = ZipExportChapter::fromManyArray($data['chapters'] ?? []);
return $model;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/Models/ZipExportImage.php | app/Exports/ZipExports/Models/ZipExportImage.php | <?php
namespace BookStack\Exports\ZipExports\Models;
use BookStack\Exports\ZipExports\ZipExportFiles;
use BookStack\Exports\ZipExports\ZipValidationHelper;
use BookStack\Uploads\Image;
use Illuminate\Validation\Rule;
final class ZipExportImage extends ZipExportModel
{
public ?int $id = null;
public string $name;
public string $file;
public string $type;
public static function fromModel(Image $model, ZipExportFiles $files): self
{
$instance = new self();
$instance->id = $model->id;
$instance->name = $model->name;
$instance->type = $model->type;
$instance->file = $files->referenceForImage($model);
return $instance;
}
public function metadataOnly(): void
{
//
}
public static function validate(ZipValidationHelper $context, array $data): array
{
$acceptedImageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
$rules = [
'id' => ['nullable', 'int', $context->uniqueIdRule('image')],
'name' => ['required', 'string', 'min:1'],
'file' => ['required', 'string', $context->fileReferenceRule($acceptedImageTypes)],
'type' => ['required', 'string', Rule::in(['gallery', 'drawio'])],
];
return $context->validateData($data, $rules);
}
public static function fromArray(array $data): static
{
$model = new static();
$model->id = $data['id'] ?? null;
$model->name = $data['name'];
$model->file = $data['file'];
$model->type = $data['type'];
return $model;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/Models/ZipExportPage.php | app/Exports/ZipExports/Models/ZipExportPage.php | <?php
namespace BookStack\Exports\ZipExports\Models;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Tools\PageContent;
use BookStack\Exports\ZipExports\ZipExportFiles;
use BookStack\Exports\ZipExports\ZipValidationHelper;
final class ZipExportPage extends ZipExportModel
{
public ?int $id = null;
public string $name;
public ?string $html = null;
public ?string $markdown = null;
public ?int $priority = null;
/** @var ZipExportAttachment[] */
public array $attachments = [];
/** @var ZipExportImage[] */
public array $images = [];
/** @var ZipExportTag[] */
public array $tags = [];
public function metadataOnly(): void
{
$this->html = $this->markdown = null;
foreach ($this->attachments as $attachment) {
$attachment->metadataOnly();
}
foreach ($this->images as $image) {
$image->metadataOnly();
}
foreach ($this->tags as $tag) {
$tag->metadataOnly();
}
}
public static function fromModel(Page $model, ZipExportFiles $files): self
{
$instance = new self();
$instance->id = $model->id;
$instance->name = $model->name;
$instance->html = (new PageContent($model))->render();
$instance->priority = $model->priority;
if (!empty($model->markdown)) {
$instance->markdown = $model->markdown;
}
$instance->tags = ZipExportTag::fromModelArray($model->tags()->get()->all());
$instance->attachments = ZipExportAttachment::fromModelArray($model->attachments()->get()->all(), $files);
return $instance;
}
/**
* @param Page[] $pageArray
* @return self[]
*/
public static function fromModelArray(array $pageArray, ZipExportFiles $files): array
{
return array_values(array_map(function (Page $page) use ($files) {
return self::fromModel($page, $files);
}, $pageArray));
}
public static function validate(ZipValidationHelper $context, array $data): array
{
$rules = [
'id' => ['nullable', 'int', $context->uniqueIdRule('page')],
'name' => ['required', 'string', 'min:1'],
'html' => ['nullable', 'string'],
'markdown' => ['nullable', 'string'],
'priority' => ['nullable', 'int'],
'attachments' => ['array'],
'images' => ['array'],
'tags' => ['array'],
];
$errors = $context->validateData($data, $rules);
$errors['attachments'] = $context->validateRelations($data['attachments'] ?? [], ZipExportAttachment::class);
$errors['images'] = $context->validateRelations($data['images'] ?? [], ZipExportImage::class);
$errors['tags'] = $context->validateRelations($data['tags'] ?? [], ZipExportTag::class);
return $errors;
}
public static function fromArray(array $data): static
{
$model = new static();
$model->id = $data['id'] ?? null;
$model->name = $data['name'];
$model->html = $data['html'] ?? null;
$model->markdown = $data['markdown'] ?? null;
$model->priority = isset($data['priority']) ? intval($data['priority']) : null;
$model->attachments = ZipExportAttachment::fromManyArray($data['attachments'] ?? []);
$model->images = ZipExportImage::fromManyArray($data['images'] ?? []);
$model->tags = ZipExportTag::fromManyArray($data['tags'] ?? []);
return $model;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/Models/ZipExportAttachment.php | app/Exports/ZipExports/Models/ZipExportAttachment.php | <?php
namespace BookStack\Exports\ZipExports\Models;
use BookStack\Exports\ZipExports\ZipExportFiles;
use BookStack\Exports\ZipExports\ZipValidationHelper;
use BookStack\Uploads\Attachment;
final class ZipExportAttachment extends ZipExportModel
{
public ?int $id = null;
public string $name;
public ?string $link = null;
public ?string $file = null;
public function metadataOnly(): void
{
$this->link = $this->file = null;
}
public static function fromModel(Attachment $model, ZipExportFiles $files): self
{
$instance = new self();
$instance->id = $model->id;
$instance->name = $model->name;
if ($model->external) {
$instance->link = $model->path;
} else {
$instance->file = $files->referenceForAttachment($model);
}
return $instance;
}
public static function fromModelArray(array $attachmentArray, ZipExportFiles $files): array
{
return array_values(array_map(function (Attachment $attachment) use ($files) {
return self::fromModel($attachment, $files);
}, $attachmentArray));
}
public static function validate(ZipValidationHelper $context, array $data): array
{
$rules = [
'id' => ['nullable', 'int', $context->uniqueIdRule('attachment')],
'name' => ['required', 'string', 'min:1'],
'link' => ['required_without:file', 'nullable', 'string'],
'file' => ['required_without:link', 'nullable', 'string', $context->fileReferenceRule()],
];
return $context->validateData($data, $rules);
}
public static function fromArray(array $data): static
{
$model = new static();
$model->id = $data['id'] ?? null;
$model->name = $data['name'];
$model->link = $data['link'] ?? null;
$model->file = $data['file'] ?? null;
return $model;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/Models/ZipExportChapter.php | app/Exports/ZipExports/Models/ZipExportChapter.php | <?php
namespace BookStack\Exports\ZipExports\Models;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Models\Page;
use BookStack\Exports\ZipExports\ZipExportFiles;
use BookStack\Exports\ZipExports\ZipValidationHelper;
final class ZipExportChapter extends ZipExportModel
{
public ?int $id = null;
public string $name;
public ?string $description_html = null;
public ?int $priority = null;
/** @var ZipExportPage[] */
public array $pages = [];
/** @var ZipExportTag[] */
public array $tags = [];
public function metadataOnly(): void
{
$this->description_html = null;
foreach ($this->pages as $page) {
$page->metadataOnly();
}
foreach ($this->tags as $tag) {
$tag->metadataOnly();
}
}
public function children(): array
{
return $this->pages;
}
public static function fromModel(Chapter $model, ZipExportFiles $files): self
{
$instance = new self();
$instance->id = $model->id;
$instance->name = $model->name;
$instance->description_html = $model->descriptionInfo()->getHtml();
$instance->priority = $model->priority;
$instance->tags = ZipExportTag::fromModelArray($model->tags()->get()->all());
$pages = $model->getVisiblePages()->filter(fn (Page $page) => !$page->draft)->all();
$instance->pages = ZipExportPage::fromModelArray($pages, $files);
return $instance;
}
/**
* @param Chapter[] $chapterArray
* @return self[]
*/
public static function fromModelArray(array $chapterArray, ZipExportFiles $files): array
{
return array_values(array_map(function (Chapter $chapter) use ($files) {
return self::fromModel($chapter, $files);
}, $chapterArray));
}
public static function validate(ZipValidationHelper $context, array $data): array
{
$rules = [
'id' => ['nullable', 'int', $context->uniqueIdRule('chapter')],
'name' => ['required', 'string', 'min:1'],
'description_html' => ['nullable', 'string'],
'priority' => ['nullable', 'int'],
'tags' => ['array'],
'pages' => ['array'],
];
$errors = $context->validateData($data, $rules);
$errors['tags'] = $context->validateRelations($data['tags'] ?? [], ZipExportTag::class);
$errors['pages'] = $context->validateRelations($data['pages'] ?? [], ZipExportPage::class);
return $errors;
}
public static function fromArray(array $data): static
{
$model = new static();
$model->id = $data['id'] ?? null;
$model->name = $data['name'];
$model->description_html = $data['description_html'] ?? null;
$model->priority = isset($data['priority']) ? intval($data['priority']) : null;
$model->tags = ZipExportTag::fromManyArray($data['tags'] ?? []);
$model->pages = ZipExportPage::fromManyArray($data['pages'] ?? []);
return $model;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/Models/ZipExportModel.php | app/Exports/ZipExports/Models/ZipExportModel.php | <?php
namespace BookStack\Exports\ZipExports\Models;
use BookStack\Exports\ZipExports\ZipValidationHelper;
use JsonSerializable;
abstract class ZipExportModel implements JsonSerializable
{
/**
* Handle the serialization to JSON.
* For these exports, we filter out optional (represented as nullable) fields
* just to clean things up and prevent confusion to avoid null states in the
* resulting export format itself.
*/
public function jsonSerialize(): array
{
$publicProps = get_object_vars(...)->__invoke($this);
return array_filter($publicProps, fn ($value) => $value !== null);
}
/**
* Validate the given array of data intended for this model.
* Return an array of validation errors messages.
* Child items can be considered in the validation result by returning a keyed
* item in the array for its own validation messages.
*/
abstract public static function validate(ZipValidationHelper $context, array $data): array;
/**
* Decode the array of data into this export model.
*/
abstract public static function fromArray(array $data): static;
/**
* Decode an array of array data into an array of export models.
* @param array[] $data
* @return static[]
*/
public static function fromManyArray(array $data): array
{
$results = [];
foreach ($data as $item) {
$results[] = static::fromArray($item);
}
return $results;
}
/**
* Remove additional content in this model to reduce it down
* to just essential id/name values for identification.
*
* The result of this may be something that does not pass validation, but is
* simple for the purpose of creating a contents.
*/
abstract public function metadataOnly(): void;
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Exports/ZipExports/Models/ZipExportTag.php | app/Exports/ZipExports/Models/ZipExportTag.php | <?php
namespace BookStack\Exports\ZipExports\Models;
use BookStack\Activity\Models\Tag;
use BookStack\Exports\ZipExports\ZipValidationHelper;
final class ZipExportTag extends ZipExportModel
{
public string $name;
public ?string $value = null;
public function metadataOnly(): void
{
$this->value = null;
}
public static function fromModel(Tag $model): self
{
$instance = new self();
$instance->name = $model->name;
$instance->value = $model->value;
return $instance;
}
public static function fromModelArray(array $tagArray): array
{
return array_values(array_map(self::fromModel(...), $tagArray));
}
public static function validate(ZipValidationHelper $context, array $data): array
{
$rules = [
'name' => ['required', 'string', 'min:1'],
'value' => ['nullable', 'string'],
];
return $context->validateData($data, $rules);
}
public static function fromArray(array $data): static
{
$model = new static();
$model->name = $data['name'];
$model->value = $data['value'] ?? null;
return $model;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/ReferenceChangeContext.php | app/References/ReferenceChangeContext.php | <?php
namespace BookStack\References;
use BookStack\Entities\Models\Entity;
class ReferenceChangeContext
{
/**
* Entity pairs where the first is the old entity and the second is the new entity.
* @var array<array{0: Entity, 1: Entity}>
*/
protected array $changes = [];
public function add(Entity $oldEntity, Entity $newEntity): void
{
$this->changes[] = [$oldEntity, $newEntity];
}
/**
* Get all the new entities from the changes.
*/
public function getNewEntities(): array
{
return array_column($this->changes, 1);
}
/**
* Get all the old entities from the changes.
*/
public function getOldEntities(): array
{
return array_column($this->changes, 0);
}
public function getNewForOld(Entity $oldEntity): ?Entity
{
foreach ($this->changes as [$old, $new]) {
if ($old->id === $oldEntity->id && $old->type === $oldEntity->type) {
return $new;
}
}
return null;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/ReferenceStore.php | app/References/ReferenceStore.php | <?php
namespace BookStack\References;
use BookStack\Entities\EntityProvider;
use BookStack\Entities\Models\Entity;
use Illuminate\Database\Eloquent\Collection;
class ReferenceStore
{
public function __construct(
protected EntityProvider $entityProvider
) {
}
/**
* Update the outgoing references for the given entity.
*/
public function updateForEntity(Entity $entity): void
{
$this->updateForEntities([$entity]);
}
/**
* Update the outgoing references for all entities in the system.
*/
public function updateForAll(): void
{
Reference::query()->delete();
foreach ($this->entityProvider->all() as $entity) {
$entity->newQuery()->select(['id', $entity->htmlField])->chunk(100, function (Collection $entities) {
$this->updateForEntities($entities->all());
});
}
}
/**
* Update the outgoing references for the entities in the given array.
*
* @param Entity[] $entities
*/
protected function updateForEntities(array $entities): void
{
if (count($entities) === 0) {
return;
}
$parser = CrossLinkParser::createWithEntityResolvers();
$references = [];
$this->dropReferencesFromEntities($entities);
foreach ($entities as $entity) {
$models = $parser->extractLinkedModels($entity->getAttribute($entity->htmlField));
foreach ($models as $model) {
$references[] = [
'from_id' => $entity->id,
'from_type' => $entity->getMorphClass(),
'to_id' => $model->id,
'to_type' => $model->getMorphClass(),
];
}
}
foreach (array_chunk($references, 1000) as $referenceDataChunk) {
Reference::query()->insert($referenceDataChunk);
}
}
/**
* Delete all the existing references originating from the given entities.
* @param Entity[] $entities
*/
protected function dropReferencesFromEntities(array $entities): void
{
$IdsByType = [];
foreach ($entities as $entity) {
$type = $entity->getMorphClass();
if (!isset($IdsByType[$type])) {
$IdsByType[$type] = [];
}
$IdsByType[$type][] = $entity->id;
}
foreach ($IdsByType as $type => $entityIds) {
Reference::query()
->where('from_type', '=', $type)
->whereIn('from_id', $entityIds)
->delete();
}
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/ReferenceUpdater.php | app/References/ReferenceUpdater.php | <?php
namespace BookStack\References;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\HasDescriptionInterface;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Repos\RevisionRepo;
use BookStack\Util\HtmlDocument;
class ReferenceUpdater
{
public function __construct(
protected ReferenceFetcher $referenceFetcher,
protected RevisionRepo $revisionRepo,
) {
}
public function updateEntityReferences(Entity $entity, string $oldLink): void
{
$references = $this->getReferencesToUpdate($entity);
$newLink = $entity->getUrl();
foreach ($references as $reference) {
/** @var Entity $entity */
$entity = $reference->from;
$this->updateReferencesWithinEntity($entity, $oldLink, $newLink);
}
}
/**
* Change existing references for a range of entities using the given context.
*/
public function changeReferencesUsingContext(ReferenceChangeContext $context): void
{
$bindings = [];
foreach ($context->getOldEntities() as $old) {
$bindings[] = $old->getMorphClass();
$bindings[] = $old->id;
}
// No targets to update within the context, so no need to continue.
if (count($bindings) < 2) {
return;
}
$toReferenceQuery = '(to_type, to_id) IN (' . rtrim(str_repeat('(?,?),', count($bindings) / 2), ',') . ')';
// Cycle each new entity in the context
foreach ($context->getNewEntities() as $new) {
// For each, get all references from it which lead to other items within the context of the change
$newReferencesInContext = $new->referencesFrom()->whereRaw($toReferenceQuery, $bindings)->get();
// For each reference, update the URL and the reference entry
foreach ($newReferencesInContext as $reference) {
$oldToEntity = $reference->to;
$newToEntity = $context->getNewForOld($oldToEntity);
if ($newToEntity === null) {
continue;
}
$this->updateReferencesWithinEntity($new, $oldToEntity->getUrl(), $newToEntity->getUrl());
if ($newToEntity instanceof Page && $oldToEntity instanceof Page) {
$this->updateReferencesWithinEntity($new, $oldToEntity->getPermalink(), $newToEntity->getPermalink());
}
$reference->to_id = $newToEntity->id;
$reference->to_type = $newToEntity->getMorphClass();
$reference->save();
}
}
}
/**
* @return Reference[]
*/
protected function getReferencesToUpdate(Entity $entity): array
{
/** @var Reference[] $references */
$references = $this->referenceFetcher->getReferencesToEntity($entity, true)->values()->all();
if ($entity instanceof Book) {
$pages = $entity->pages()->get(['id']);
$chapters = $entity->chapters()->get(['id']);
$children = $pages->concat($chapters);
foreach ($children as $bookChild) {
/** @var Reference[] $childRefs */
$childRefs = $this->referenceFetcher->getReferencesToEntity($bookChild, true)->values()->all();
array_push($references, ...$childRefs);
}
}
$deduped = [];
foreach ($references as $reference) {
$key = $reference->from_id . ':' . $reference->from_type;
$deduped[$key] = $reference;
}
return array_values($deduped);
}
protected function updateReferencesWithinEntity(Entity $entity, string $oldLink, string $newLink): void
{
if ($entity instanceof Page) {
$this->updateReferencesWithinPage($entity, $oldLink, $newLink);
}
if ($entity instanceof HasDescriptionInterface) {
$this->updateReferencesWithinDescription($entity, $oldLink, $newLink);
}
}
protected function updateReferencesWithinDescription(Entity&HasDescriptionInterface $entity, string $oldLink, string $newLink): void
{
$description = $entity->descriptionInfo();
$html = $this->updateLinksInHtml($description->getHtml(true) ?: '', $oldLink, $newLink);
$description->set($html);
$entity->save();
}
protected function updateReferencesWithinPage(Page $page, string $oldLink, string $newLink): void
{
$page = (clone $page)->refresh();
$html = $this->updateLinksInHtml($page->html, $oldLink, $newLink);
$markdown = $this->updateLinksInMarkdown($page->markdown, $oldLink, $newLink);
$page->html = $html;
$page->markdown = $markdown;
$page->revision_count++;
$page->save();
$summary = trans('entities.pages_references_update_revision');
$this->revisionRepo->storeNewForPage($page, $summary);
}
protected function updateLinksInMarkdown(string $markdown, string $oldLink, string $newLink): string
{
if (empty($markdown)) {
return $markdown;
}
$commonLinkRegex = '/(\[.*?\]\()' . preg_quote($oldLink, '/') . '(.*?\))/i';
$markdown = preg_replace($commonLinkRegex, '$1' . $newLink . '$2', $markdown);
$referenceLinkRegex = '/(\[.*?\]:\s?)' . preg_quote($oldLink, '/') . '(.*?)($|\s)/i';
$markdown = preg_replace($referenceLinkRegex, '$1' . $newLink . '$2$3', $markdown);
return $markdown;
}
protected function updateLinksInHtml(string $html, string $oldLink, string $newLink): string
{
if (empty($html)) {
return $html;
}
$doc = new HtmlDocument($html);
$anchors = $doc->queryXPath('//a[@href]');
/** @var \DOMElement $anchor */
foreach ($anchors as $anchor) {
$link = $anchor->getAttribute('href');
$updated = str_ireplace($oldLink, $newLink, $link);
$anchor->setAttribute('href', $updated);
}
return $doc->getBodyInnerHtml();
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/Reference.php | app/References/Reference.php | <?php
namespace BookStack\References;
use BookStack\Permissions\Models\JointPermission;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
/**
* @property int $from_id
* @property string $from_type
* @property int $to_id
* @property string $to_type
*/
class Reference extends Model
{
public $timestamps = false;
public function from(): MorphTo
{
return $this->morphTo('from');
}
public function to(): MorphTo
{
return $this->morphTo('to');
}
public function jointPermissions(): HasMany
{
return $this->hasMany(JointPermission::class, 'entity_id', 'from_id')
->whereColumn('references.from_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/References/ReferenceFetcher.php | app/References/ReferenceFetcher.php | <?php
namespace BookStack\References;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Tools\MixedEntityListLoader;
use BookStack\Permissions\PermissionApplicator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
class ReferenceFetcher
{
public function __construct(
protected PermissionApplicator $permissions,
protected MixedEntityListLoader $mixedEntityListLoader,
) {
}
/**
* Query and return the references pointing to the given entity.
* Loads the commonly required relations while taking permissions into account.
*/
public function getReferencesToEntity(Entity $entity, bool $withContents = false): Collection
{
$references = $this->queryReferencesToEntity($entity)->get();
$this->mixedEntityListLoader->loadIntoRelations($references->all(), 'from', false, $withContents);
return $references;
}
/**
* Returns the count of references pointing to the given entity.
* Takes permissions into account.
*/
public function getReferenceCountToEntity(Entity $entity): int
{
return $this->queryReferencesToEntity($entity)->count();
}
protected function queryReferencesToEntity(Entity $entity): Builder
{
$baseQuery = Reference::query()
->where('to_type', '=', $entity->getMorphClass())
->where('to_id', '=', $entity->id)
->whereHas('from');
return $this->permissions->restrictEntityRelationQuery(
$baseQuery,
'references',
'from_id',
'from_type'
);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/CrossLinkParser.php | app/References/CrossLinkParser.php | <?php
namespace BookStack\References;
use BookStack\App\Model;
use BookStack\Entities\Queries\EntityQueries;
use BookStack\References\ModelResolvers\BookLinkModelResolver;
use BookStack\References\ModelResolvers\BookshelfLinkModelResolver;
use BookStack\References\ModelResolvers\ChapterLinkModelResolver;
use BookStack\References\ModelResolvers\CrossLinkModelResolver;
use BookStack\References\ModelResolvers\PageLinkModelResolver;
use BookStack\References\ModelResolvers\PagePermalinkModelResolver;
use BookStack\Util\HtmlDocument;
class CrossLinkParser
{
/**
* @var CrossLinkModelResolver[]
*/
protected array $modelResolvers;
public function __construct(array $modelResolvers)
{
$this->modelResolvers = $modelResolvers;
}
/**
* Extract any found models within the given HTML content.
*
* @return Model[]
*/
public function extractLinkedModels(string $html): array
{
$models = [];
$links = $this->getLinksFromContent($html);
foreach ($links as $link) {
$model = $this->linkToModel($link);
if (!is_null($model)) {
$models[get_class($model) . ':' . $model->id] = $model;
}
}
return array_values($models);
}
/**
* Get a list of href values from the given document.
*
* @return string[]
*/
protected function getLinksFromContent(string $html): array
{
$links = [];
$doc = new HtmlDocument($html);
$anchors = $doc->queryXPath('//a[@href]');
/** @var \DOMElement $anchor */
foreach ($anchors as $anchor) {
$links[] = $anchor->getAttribute('href');
}
return $links;
}
/**
* Attempt to resolve the given link to a model using the instance model resolvers.
*/
protected function linkToModel(string $link): ?Model
{
foreach ($this->modelResolvers as $resolver) {
$model = $resolver->resolve($link);
if (!is_null($model)) {
return $model;
}
}
return null;
}
/**
* Create a new instance with a pre-defined set of model resolvers, specifically for the
* default set of entities within BookStack.
*/
public static function createWithEntityResolvers(): self
{
$queries = app()->make(EntityQueries::class);
return new self([
new PagePermalinkModelResolver($queries->pages),
new PageLinkModelResolver($queries->pages),
new ChapterLinkModelResolver($queries->chapters),
new BookLinkModelResolver($queries->books),
new BookshelfLinkModelResolver($queries->shelves),
]);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/ReferenceController.php | app/References/ReferenceController.php | <?php
namespace BookStack\References;
use BookStack\Entities\Queries\EntityQueries;
use BookStack\Http\Controller;
class ReferenceController extends Controller
{
public function __construct(
protected ReferenceFetcher $referenceFetcher,
protected EntityQueries $queries,
) {
}
/**
* Display the references to a given page.
*/
public function page(string $bookSlug, string $pageSlug)
{
$page = $this->queries->pages->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
$references = $this->referenceFetcher->getReferencesToEntity($page);
return view('pages.references', [
'page' => $page,
'references' => $references,
]);
}
/**
* Display the references to a given chapter.
*/
public function chapter(string $bookSlug, string $chapterSlug)
{
$chapter = $this->queries->chapters->findVisibleBySlugsOrFail($bookSlug, $chapterSlug);
$references = $this->referenceFetcher->getReferencesToEntity($chapter);
return view('chapters.references', [
'chapter' => $chapter,
'references' => $references,
]);
}
/**
* Display the references to a given book.
*/
public function book(string $slug)
{
$book = $this->queries->books->findVisibleBySlugOrFail($slug);
$references = $this->referenceFetcher->getReferencesToEntity($book);
return view('books.references', [
'book' => $book,
'references' => $references,
]);
}
/**
* Display the references to a given shelf.
*/
public function shelf(string $slug)
{
$shelf = $this->queries->shelves->findVisibleBySlugOrFail($slug);
$references = $this->referenceFetcher->getReferencesToEntity($shelf);
return view('shelves.references', [
'shelf' => $shelf,
'references' => $references,
]);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/ModelResolvers/PagePermalinkModelResolver.php | app/References/ModelResolvers/PagePermalinkModelResolver.php | <?php
namespace BookStack\References\ModelResolvers;
use BookStack\App\Model;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Queries\PageQueries;
class PagePermalinkModelResolver implements CrossLinkModelResolver
{
public function __construct(
protected PageQueries $queries
) {
}
public function resolve(string $link): ?Model
{
$pattern = '/^' . preg_quote(url('/link'), '/') . '\/(\d+)/';
$matches = [];
$match = preg_match($pattern, $link, $matches);
if (!$match) {
return null;
}
$id = intval($matches[1]);
/** @var ?Page $model */
$model = $this->queries->start()->find($id, ['id']);
return $model;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/ModelResolvers/CrossLinkModelResolver.php | app/References/ModelResolvers/CrossLinkModelResolver.php | <?php
namespace BookStack\References\ModelResolvers;
use BookStack\App\Model;
interface CrossLinkModelResolver
{
/**
* Resolve the given href link value to a model.
*/
public function resolve(string $link): ?Model;
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/ModelResolvers/BookLinkModelResolver.php | app/References/ModelResolvers/BookLinkModelResolver.php | <?php
namespace BookStack\References\ModelResolvers;
use BookStack\App\Model;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Queries\BookQueries;
class BookLinkModelResolver implements CrossLinkModelResolver
{
public function __construct(
protected BookQueries $queries
) {
}
public function resolve(string $link): ?Model
{
$pattern = '/^' . preg_quote(url('/books'), '/') . '\/([\w-]+)' . '([#?\/]|$)/';
$matches = [];
$match = preg_match($pattern, $link, $matches);
if (!$match) {
return null;
}
$bookSlug = $matches[1];
/** @var ?Book $model */
$model = $this->queries->start()->where('slug', '=', $bookSlug)->first(['id']);
return $model;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/ModelResolvers/PageLinkModelResolver.php | app/References/ModelResolvers/PageLinkModelResolver.php | <?php
namespace BookStack\References\ModelResolvers;
use BookStack\App\Model;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Queries\PageQueries;
class PageLinkModelResolver implements CrossLinkModelResolver
{
public function __construct(
protected PageQueries $queries
) {
}
public function resolve(string $link): ?Model
{
$pattern = '/^' . preg_quote(url('/books'), '/') . '\/([\w-]+)' . '\/page\/' . '([\w-]+)' . '([#?\/]|$)/';
$matches = [];
$match = preg_match($pattern, $link, $matches);
if (!$match) {
return null;
}
$bookSlug = $matches[1];
$pageSlug = $matches[2];
/** @var ?Page $model */
$model = $this->queries->usingSlugs($bookSlug, $pageSlug)->first(['id']);
return $model;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/ModelResolvers/AttachmentModelResolver.php | app/References/ModelResolvers/AttachmentModelResolver.php | <?php
namespace BookStack\References\ModelResolvers;
use BookStack\Uploads\Attachment;
class AttachmentModelResolver implements CrossLinkModelResolver
{
public function resolve(string $link): ?Attachment
{
$pattern = '/^' . preg_quote(url('/attachments'), '/') . '\/(\d+)/';
$matches = [];
$match = preg_match($pattern, $link, $matches);
if (!$match) {
return null;
}
$id = intval($matches[1]);
return Attachment::query()->find($id);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/ModelResolvers/ImageModelResolver.php | app/References/ModelResolvers/ImageModelResolver.php | <?php
namespace BookStack\References\ModelResolvers;
use BookStack\Uploads\Image;
use BookStack\Uploads\ImageStorage;
class ImageModelResolver implements CrossLinkModelResolver
{
protected ?string $pattern = null;
public function resolve(string $link): ?Image
{
$pattern = $this->getUrlPattern();
$matches = [];
$match = preg_match($pattern, $link, $matches);
if (!$match) {
return null;
}
$path = $matches[2];
// 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), '/');
return Image::query()->where('path', '=', $fullPath)->first();
}
/**
* Get the regex pattern to identify image URLs.
* Caches the pattern since it requires looking up to settings/config.
*/
protected function getUrlPattern(): string
{
if ($this->pattern) {
return $this->pattern;
}
$urls = [url('/uploads/images')];
$baseImageUrl = ImageStorage::getPublicUrl('/uploads/images');
if ($baseImageUrl !== $urls[0]) {
$urls[] = $baseImageUrl;
}
$imageUrlRegex = implode('|', array_map(fn ($url) => preg_quote($url, '/'), $urls));
$this->pattern = '/^(' . $imageUrlRegex . ')\/(.+)/';
return $this->pattern;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/ModelResolvers/ChapterLinkModelResolver.php | app/References/ModelResolvers/ChapterLinkModelResolver.php | <?php
namespace BookStack\References\ModelResolvers;
use BookStack\App\Model;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Queries\ChapterQueries;
class ChapterLinkModelResolver implements CrossLinkModelResolver
{
public function __construct(
protected ChapterQueries $queries
) {
}
public function resolve(string $link): ?Model
{
$pattern = '/^' . preg_quote(url('/books'), '/') . '\/([\w-]+)' . '\/chapter\/' . '([\w-]+)' . '([#?\/]|$)/';
$matches = [];
$match = preg_match($pattern, $link, $matches);
if (!$match) {
return null;
}
$bookSlug = $matches[1];
$chapterSlug = $matches[2];
/** @var ?Chapter $model */
$model = $this->queries->usingSlugs($bookSlug, $chapterSlug)->first(['id']);
return $model;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/References/ModelResolvers/BookshelfLinkModelResolver.php | app/References/ModelResolvers/BookshelfLinkModelResolver.php | <?php
namespace BookStack\References\ModelResolvers;
use BookStack\App\Model;
use BookStack\Entities\Models\Bookshelf;
use BookStack\Entities\Queries\BookshelfQueries;
class BookshelfLinkModelResolver implements CrossLinkModelResolver
{
public function __construct(
protected BookshelfQueries $queries
) {
}
public function resolve(string $link): ?Model
{
$pattern = '/^' . preg_quote(url('/shelves'), '/') . '\/([\w-]+)' . '([#?\/]|$)/';
$matches = [];
$match = preg_match($pattern, $link, $matches);
if (!$match) {
return null;
}
$shelfSlug = $matches[1];
/** @var ?Bookshelf $model */
$model = $this->queries->start()->where('slug', '=', $shelfSlug)->first(['id']);
return $model;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/PwaManifestBuilder.php | app/App/PwaManifestBuilder.php | <?php
namespace BookStack\App;
class PwaManifestBuilder
{
public function build(): array
{
// Note, while we attempt to use the user's preference here, the request to the manifest
// does not start a session, so we won't have current user context.
// This was attempted but removed since manifest calls could affect user session
// history tracking and back redirection.
// Context: https://github.com/BookStackApp/BookStack/issues/4649
$darkMode = (bool) setting()->getForCurrentUser('dark-mode-enabled');
$appName = setting('app-name');
return [
"name" => $appName,
"short_name" => $appName,
"start_url" => "./",
"scope" => "/",
"display" => "standalone",
"background_color" => $darkMode ? '#111111' : '#F2F2F2',
"description" => $appName,
"theme_color" => ($darkMode ? setting('app-color-dark') : setting('app-color')),
"launch_handler" => [
"client_mode" => "focus-existing"
],
"orientation" => "any",
"icons" => [
[
"src" => setting('app-icon-32') ?: url('/icon-32.png'),
"sizes" => "32x32",
"type" => "image/png"
],
[
"src" => setting('app-icon-64') ?: url('/icon-64.png'),
"sizes" => "64x64",
"type" => "image/png"
],
[
"src" => setting('app-icon-128') ?: url('/icon-128.png'),
"sizes" => "128x128",
"type" => "image/png"
],
[
"src" => setting('app-icon-180') ?: url('/icon-180.png'),
"sizes" => "180x180",
"type" => "image/png"
],
[
"src" => setting('app-icon') ?: url('/icon.png'),
"sizes" => "256x256",
"type" => "image/png"
],
[
"src" => url('favicon.ico'),
"sizes" => "48x48",
"type" => "image/vnd.microsoft.icon"
],
],
];
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/SluggableInterface.php | app/App/SluggableInterface.php | <?php
namespace BookStack\App;
/**
* Assigned to models that can have slugs.
* Must have the below properties.
*
* @property string $slug
*/
interface SluggableInterface
{
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/MailNotification.php | app/App/MailNotification.php | <?php
namespace BookStack\App;
use BookStack\Translation\LocaleDefinition;
use BookStack\Users\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
abstract class MailNotification extends Notification implements ShouldQueue
{
use Queueable;
/**
* Get the mail representation of the notification.
*/
abstract public function toMail(User $notifiable): MailMessage;
/**
* Get the notification's channels.
*
* @param mixed $notifiable
*
* @return array|string
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Create a new mail message.
*/
protected function newMailMessage(?LocaleDefinition $locale = null): MailMessage
{
$data = ['locale' => $locale ?? user()->getLocale()];
return (new MailMessage())->view([
'html' => 'vendor.notifications.email',
'text' => 'vendor.notifications.email-plain',
], $data);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/Application.php | app/App/Application.php | <?php
namespace BookStack\App;
class Application extends \Illuminate\Foundation\Application
{
/**
* Get the path to the application configuration files.
*
* @param string $path Optionally, a path to append to the config path
*
* @return string
*/
public function configPath($path = '')
{
return $this->basePath
. DIRECTORY_SEPARATOR
. 'app'
. DIRECTORY_SEPARATOR
. 'Config'
. ($path ? DIRECTORY_SEPARATOR . $path : $path);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/helpers.php | app/App/helpers.php | <?php
use BookStack\App\AppVersion;
use BookStack\App\Model;
use BookStack\Facades\Theme;
use BookStack\Permissions\Permission;
use BookStack\Permissions\PermissionApplicator;
use BookStack\Settings\SettingService;
use BookStack\Users\Models\User;
/**
* Get the path to a versioned file.
*
* @throws Exception
*/
function versioned_asset(string $file = ''): string
{
$version = AppVersion::get();
$additional = '';
if (config('app.env') === 'development') {
$additional = sha1_file(public_path($file));
}
$path = $file . '?version=' . urlencode($version) . $additional;
return url($path);
}
/**
* Helper method to get the current User.
* Defaults to public 'Guest' user if not logged in.
*/
function user(): User
{
return auth()->user() ?: User::getGuest();
}
/**
* Check if the current user has a permission. If an ownable element
* is passed in the jointPermissions are checked against that particular item.
*/
function userCan(string|Permission $permission, ?Model $ownable = null): bool
{
if (is_null($ownable)) {
return user()->can($permission);
}
// Check permission on ownable item
$permissions = app()->make(PermissionApplicator::class);
return $permissions->checkOwnableUserAccess($ownable, $permission);
}
/**
* Check if the current user can perform the given action on any items in the system.
* Can be provided the class name of an entity to filter ability to that specific entity type.
*/
function userCanOnAny(string|Permission $action, string $entityClass = ''): bool
{
$permissions = app()->make(PermissionApplicator::class);
return $permissions->checkUserHasEntityPermissionOnAny($action, $entityClass);
}
/**
* Helper to access system settings.
*
* @return mixed|SettingService
*/
function setting(?string $key = null, mixed $default = null): mixed
{
$settingService = app()->make(SettingService::class);
if (is_null($key)) {
return $settingService;
}
return $settingService->get($key, $default);
}
/**
* Get a path to a theme resource.
* Returns null if a theme is not configured and
* therefore a full path is not available for use.
*/
function theme_path(string $path = ''): ?string
{
$theme = Theme::getTheme();
if (!$theme) {
return null;
}
return base_path('themes/' . $theme . ($path ? DIRECTORY_SEPARATOR . $path : $path));
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/SystemApiController.php | app/App/SystemApiController.php | <?php
namespace BookStack\App;
use BookStack\Http\ApiController;
use Illuminate\Http\JsonResponse;
class SystemApiController extends ApiController
{
/**
* Read details regarding the BookStack instance.
* Some details may be null where not set, like the app logo for example.
*/
public function read(): JsonResponse
{
$logoSetting = setting('app-logo', '');
if ($logoSetting === 'none') {
$logo = null;
} else {
$logo = $logoSetting ? url($logoSetting) : url('/logo.png');
}
return response()->json([
'version' => AppVersion::get(),
'instance_id' => setting('instance-id'),
'app_name' => setting('app-name'),
'app_logo' => $logo,
'base_url' => url('/'),
]);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/HomeController.php | app/App/HomeController.php | <?php
namespace BookStack\App;
use BookStack\Activity\ActivityQueries;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Queries\EntityQueries;
use BookStack\Entities\Queries\QueryRecentlyViewed;
use BookStack\Entities\Queries\QueryTopFavourites;
use BookStack\Entities\Tools\PageContent;
use BookStack\Http\Controller;
use BookStack\Util\SimpleListOptions;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function __construct(
protected EntityQueries $queries,
) {
}
/**
* Display the homepage.
*/
public function index(
Request $request,
ActivityQueries $activities,
QueryRecentlyViewed $recentlyViewed,
QueryTopFavourites $topFavourites,
) {
$activity = $activities->latest(10);
$draftPages = [];
if ($this->isSignedIn()) {
$draftPages = $this->queries->pages->currentUserDraftsForList()
->orderBy('updated_at', 'desc')
->with('book')
->take(6)
->get();
}
$recentFactor = count($draftPages) > 0 ? 0.5 : 1;
$recents = $this->isSignedIn() ?
$recentlyViewed->run(12 * $recentFactor, 1)
: $this->queries->books->visibleForList()->orderBy('created_at', 'desc')->take(12 * $recentFactor)->get();
$favourites = $topFavourites->run(6);
$recentlyUpdatedPages = $this->queries->pages->visibleForList()
->where('draft', false)
->orderBy('updated_at', 'desc')
->take($favourites->count() > 0 ? 5 : 10)
->get();
$homepageOptions = ['default', 'books', 'bookshelves', 'page'];
$homepageOption = setting('app-homepage-type', 'default');
if (!in_array($homepageOption, $homepageOptions)) {
$homepageOption = 'default';
}
$commonData = [
'activity' => $activity,
'recents' => $recents,
'recentlyUpdatedPages' => $recentlyUpdatedPages,
'draftPages' => $draftPages,
'favourites' => $favourites,
];
// Add required list ordering & sorting for books & shelves views.
if ($homepageOption === 'bookshelves' || $homepageOption === 'books') {
$key = $homepageOption;
$view = setting()->getForCurrentUser($key . '_view_type');
$listOptions = SimpleListOptions::fromRequest($request, $key)->withSortOptions([
'name' => trans('common.sort_name'),
'created_at' => trans('common.sort_created_at'),
'updated_at' => trans('common.sort_updated_at'),
]);
$commonData = array_merge($commonData, [
'view' => $view,
'listOptions' => $listOptions,
]);
}
if ($homepageOption === 'bookshelves') {
$shelves = $this->queries->shelves->visibleForListWithCover()
->orderBy($commonData['listOptions']->getSort(), $commonData['listOptions']->getOrder())
->paginate(setting()->getInteger('lists-page-count-shelves', 18, 1, 1000));
$data = array_merge($commonData, ['shelves' => $shelves]);
return view('home.shelves', $data);
}
if ($homepageOption === 'books') {
$books = $this->queries->books->visibleForListWithCover()
->orderBy($commonData['listOptions']->getSort(), $commonData['listOptions']->getOrder())
->paginate(setting()->getInteger('lists-page-count-books', 18, 1, 1000));
$data = array_merge($commonData, ['books' => $books]);
return view('home.books', $data);
}
if ($homepageOption === 'page') {
$homepageSetting = setting('app-homepage', '0:');
$id = intval(explode(':', $homepageSetting)[0]);
/** @var Page $customHomepage */
$customHomepage = $this->queries->pages->start()->where('draft', '=', false)->findOrFail($id);
$pageContent = new PageContent($customHomepage);
$customHomepage->html = $pageContent->render(false);
return view('home.specific-page', array_merge($commonData, ['customHomepage' => $customHomepage]));
}
return view('home.default', $commonData);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/MetaController.php | app/App/MetaController.php | <?php
namespace BookStack\App;
use BookStack\Http\Controller;
use BookStack\Uploads\FaviconHandler;
class MetaController extends Controller
{
/**
* Show the view for /robots.txt.
*/
public function robots()
{
$sitePublic = setting('app-public', false);
$allowRobots = config('app.allow_robots');
if ($allowRobots === null) {
$allowRobots = $sitePublic;
}
return response()
->view('misc.robots', ['allowRobots' => $allowRobots])
->header('Content-Type', 'text/plain');
}
/**
* Show the route for 404 responses.
*/
public function notFound()
{
return response()->view('errors.404', [], 404);
}
/**
* Serve the application favicon.
* Ensures a 'favicon.ico' file exists at the web root location (if writable) to be served
* directly by the webserver in the future.
*/
public function favicon(FaviconHandler $favicons)
{
$exists = $favicons->restoreOriginalIfNotExists();
return response()->file($exists ? $favicons->getPath() : $favicons->getOriginalPath());
}
/**
* Serve a PWA application manifest.
*/
public function pwaManifest(PwaManifestBuilder $manifestBuilder)
{
return response()->json($manifestBuilder->build());
}
/**
* Show license information for the application.
*/
public function licenses()
{
$this->setPageTitle(trans('settings.licenses'));
return view('help.licenses', [
'license' => file_get_contents(base_path('LICENSE')),
'phpLibData' => file_get_contents(base_path('dev/licensing/php-library-licenses.txt')),
'jsLibData' => file_get_contents(base_path('dev/licensing/js-library-licenses.txt')),
]);
}
/**
* Show the view for /opensearch.xml.
*/
public function opensearch()
{
return response()
->view('misc.opensearch')
->header('Content-Type', 'application/opensearchdescription+xml');
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/Model.php | app/App/Model.php | <?php
namespace BookStack\App;
use Illuminate\Database\Eloquent\Model as EloquentModel;
class Model extends EloquentModel
{
/**
* Provides public access to get the raw attribute value from the model.
* Used in areas where no mutations are required, but performance is critical.
*
* @return mixed
*/
public function getRawAttribute(string $key)
{
return parent::getAttributeFromArray($key);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/AppVersion.php | app/App/AppVersion.php | <?php
namespace BookStack\App;
class AppVersion
{
protected static string $version = '';
/**
* Get the application's version number from its top-level `version` text file.
*/
public static function get(): string
{
if (!empty(static::$version)) {
return static::$version;
}
$versionFile = base_path('version');
$version = trim(file_get_contents($versionFile));
static::$version = $version;
return $version;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/Providers/TranslationServiceProvider.php | app/App/Providers/TranslationServiceProvider.php | <?php
namespace BookStack\App\Providers;
use BookStack\Translation\FileLoader;
use BookStack\Translation\MessageSelector;
use Illuminate\Translation\TranslationServiceProvider as BaseProvider;
use Illuminate\Translation\Translator;
class TranslationServiceProvider extends BaseProvider
{
/**
* Register the service provider.
*/
public function register(): void
{
$this->registerLoader();
// This is a tweak upon Laravel's based translation service registration to allow
// usage of a custom MessageSelector class
$this->app->singleton('translator', function ($app) {
$loader = $app['translation.loader'];
// When registering the translator component, we'll need to set the default
// locale as well as the fallback locale. So, we'll grab the application
// configuration so we can easily get both of these values from there.
$locale = $app['config']['app.locale'];
$trans = new Translator($loader, $locale);
$trans->setFallback($app['config']['app.fallback_locale']);
$trans->setSelector(new MessageSelector());
return $trans;
});
}
/**
* Register the translation line loader.
* Overrides the default register action from Laravel so a custom loader can be used.
*/
protected function registerLoader(): void
{
$this->app->singleton('translation.loader', function ($app) {
return new FileLoader($app['files'], $app['path.lang']);
});
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/Providers/ViewTweaksServiceProvider.php | app/App/Providers/ViewTweaksServiceProvider.php | <?php
namespace BookStack\App\Providers;
use BookStack\Entities\BreadcrumbsViewComposer;
use BookStack\Util\DateFormatter;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ViewTweaksServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(DateFormatter::class, function ($app) {
return new DateFormatter(
$app['config']->get('app.display_timezone'),
);
});
}
/**
* Bootstrap services.
*/
public function boot(): void
{
// Set paginator to use bootstrap-style pagination
Paginator::useBootstrap();
// View Composers
View::composer('entities.breadcrumbs', BreadcrumbsViewComposer::class);
// View Globals
View::share('dates', $this->app->make(DateFormatter::class));
// Custom blade view directives
Blade::directive('icon', function ($expression) {
return "<?php echo (new \BookStack\Util\SvgIcon($expression))->toHtml(); ?>";
});
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/Providers/ThemeServiceProvider.php | app/App/Providers/ThemeServiceProvider.php | <?php
namespace BookStack\App\Providers;
use BookStack\Theming\ThemeEvents;
use BookStack\Theming\ThemeService;
use Illuminate\Support\ServiceProvider;
class ThemeServiceProvider extends ServiceProvider
{
/**
* Register services.
*/
public function register(): void
{
// Register the ThemeService as a singleton
$this->app->singleton(ThemeService::class, fn ($app) => new ThemeService());
}
/**
* Bootstrap services.
*/
public function boot(): void
{
// Boot up the theme system
$themeService = $this->app->make(ThemeService::class);
$themeService->readThemeActions();
$themeService->dispatch(ThemeEvents::APP_BOOT, $this->app);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/Providers/RouteServiceProvider.php | app/App/Providers/RouteServiceProvider.php | <?php
namespace BookStack\App\Providers;
use BookStack\Facades\Theme;
use BookStack\Theming\ThemeEvents;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* @var string
*/
public const HOME = '/';
/**
* Define your route model bindings, pattern filters, etc.
*/
public function boot(): void
{
$this->configureRateLimiting();
$this->routes(function () {
$this->mapWebRoutes();
$this->mapApiRoutes();
});
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*/
protected function mapWebRoutes(): void
{
Route::group([
'middleware' => 'web',
'namespace' => $this->namespace,
], function (Router $router) {
require base_path('routes/web.php');
Theme::dispatch(ThemeEvents::ROUTES_REGISTER_WEB, $router);
});
Route::group([
'middleware' => ['web', 'auth'],
], function (Router $router) {
Theme::dispatch(ThemeEvents::ROUTES_REGISTER_WEB_AUTH, $router);
});
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*/
protected function mapApiRoutes(): void
{
Route::group([
'middleware' => 'api',
'namespace' => $this->namespace . '\Api',
'prefix' => 'api',
], function ($router) {
require base_path('routes/api.php');
});
}
/**
* Configure the rate limiters for the application.
*/
protected function configureRateLimiting(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
RateLimiter::for('public', function (Request $request) {
return Limit::perMinute(10)->by($request->ip());
});
RateLimiter::for('exports', function (Request $request) {
$user = user();
$attempts = $user->isGuest() ? 4 : 10;
$key = $user->isGuest() ? $request->ip() : $user->id;
return Limit::perMinute($attempts)->by($key);
});
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/Providers/EventServiceProvider.php | app/App/Providers/EventServiceProvider.php | <?php
namespace BookStack\App\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use SocialiteProviders\Azure\AzureExtendSocialite;
use SocialiteProviders\Discord\DiscordExtendSocialite;
use SocialiteProviders\GitLab\GitLabExtendSocialite;
use SocialiteProviders\Manager\SocialiteWasCalled;
use SocialiteProviders\Okta\OktaExtendSocialite;
use SocialiteProviders\Twitch\TwitchExtendSocialite;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array<class-string, array<int, string>>
*/
protected $listen = [
SocialiteWasCalled::class => [
AzureExtendSocialite::class . '@handle',
OktaExtendSocialite::class . '@handle',
GitLabExtendSocialite::class . '@handle',
TwitchExtendSocialite::class . '@handle',
DiscordExtendSocialite::class . '@handle',
],
];
/**
* Register any events for your application.
*/
public function boot(): void
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*/
public function shouldDiscoverEvents(): bool
{
return false;
}
/**
* Overrides the registration of Laravel's default email verification system
*/
protected function configureEmailVerification(): void
{
//
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/Providers/ValidationRuleServiceProvider.php | app/App/Providers/ValidationRuleServiceProvider.php | <?php
namespace BookStack\App\Providers;
use BookStack\Uploads\ImageService;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;
class ValidationRuleServiceProvider extends ServiceProvider
{
/**
* Register our custom validation rules when the application boots.
*/
public function boot(): void
{
Validator::extend('image_extension', function ($attribute, $value, $parameters, $validator) {
$extension = strtolower($value->getClientOriginalExtension());
return ImageService::isExtensionSupported($extension);
});
Validator::extend('safe_url', function ($attribute, $value, $parameters, $validator) {
$cleanLinkName = strtolower(trim($value));
$isJs = str_starts_with($cleanLinkName, 'javascript:');
$isData = str_starts_with($cleanLinkName, 'data:');
return !$isJs && !$isData;
});
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/Providers/AppServiceProvider.php | app/App/Providers/AppServiceProvider.php | <?php
namespace BookStack\App\Providers;
use BookStack\Access\SocialDriverManager;
use BookStack\Activity\Models\Comment;
use BookStack\Activity\Tools\ActivityLogger;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Bookshelf;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Models\Page;
use BookStack\Exceptions\BookStackExceptionHandlerPage;
use BookStack\Http\HttpRequestService;
use BookStack\Permissions\PermissionApplicator;
use BookStack\Settings\SettingService;
use BookStack\Util\CspService;
use Illuminate\Contracts\Foundation\ExceptionRenderer;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Custom container bindings to register.
* @var string[]
*/
public array $bindings = [
ExceptionRenderer::class => BookStackExceptionHandlerPage::class,
];
/**
* Custom singleton bindings to register.
* @var string[]
*/
public array $singletons = [
'activity' => ActivityLogger::class,
SettingService::class => SettingService::class,
SocialDriverManager::class => SocialDriverManager::class,
CspService::class => CspService::class,
HttpRequestService::class => HttpRequestService::class,
];
/**
* Register any application services.
*/
public function register(): void
{
$this->app->singleton(PermissionApplicator::class, function ($app) {
return new PermissionApplicator(null);
});
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
// Set root URL
$appUrl = config('app.url');
if ($appUrl) {
$isHttps = str_starts_with($appUrl, 'https://');
URL::forceRootUrl($appUrl);
URL::forceScheme($isHttps ? 'https' : 'http');
}
// Allow longer string lengths after upgrade to utf8mb4
Schema::defaultStringLength(191);
// Set morph-map for our relations to friendlier aliases
Relation::enforceMorphMap([
'bookshelf' => Bookshelf::class,
'book' => Book::class,
'chapter' => Chapter::class,
'page' => Page::class,
'comment' => Comment::class,
]);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/App/Providers/AuthServiceProvider.php | app/App/Providers/AuthServiceProvider.php | <?php
namespace BookStack\App\Providers;
use BookStack\Access\ExternalBaseUserProvider;
use BookStack\Access\Guards\AsyncExternalBaseSessionGuard;
use BookStack\Access\Guards\LdapSessionGuard;
use BookStack\Access\LdapService;
use BookStack\Access\LoginService;
use BookStack\Access\RegistrationService;
use BookStack\Api\ApiTokenGuard;
use BookStack\Users\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
class AuthServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot(): void
{
// Password Configuration
// Changes here must be reflected in ApiDocsGenerate@getValidationAsString.
Password::defaults(fn () => Password::min(8));
// Custom guards
Auth::extend('api-token', function ($app, $name, array $config) {
return new ApiTokenGuard($app['request'], $app->make(LoginService::class));
});
Auth::extend('ldap-session', function ($app, $name, array $config) {
$provider = Auth::createUserProvider($config['provider']);
return new LdapSessionGuard(
$name,
$provider,
$app['session.store'],
$app[LdapService::class],
$app[RegistrationService::class]
);
});
Auth::extend('async-external-session', function ($app, $name, array $config) {
$provider = Auth::createUserProvider($config['provider']);
return new AsyncExternalBaseSessionGuard(
$name,
$provider,
$app['session.store'],
$app[RegistrationService::class]
);
});
}
/**
* Register the application services.
*/
public function register(): void
{
Auth::provider('external-users', function () {
return new ExternalBaseUserProvider();
});
// Bind and provide the default system user as a singleton to the app instance when needed.
// This effectively "caches" fetching the user at an app-instance level.
$this->app->singleton('users.default', function () {
return User::query()->where('system_name', '=', 'public')->first();
});
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Sorting/BookSorter.php | app/Sorting/BookSorter.php | <?php
namespace BookStack\Sorting;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\BookChild;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Queries\EntityQueries;
use BookStack\Entities\Tools\ParentChanger;
use BookStack\Permissions\Permission;
class BookSorter
{
public function __construct(
protected EntityQueries $queries,
protected ParentChanger $parentChanger,
) {
}
public function runBookAutoSortForAllWithSet(SortRule $set): void
{
$set->books()->chunk(50, function ($books) {
foreach ($books as $book) {
$this->runBookAutoSort($book);
}
});
}
/**
* Runs the auto-sort for a book if the book has a sort set applied to it.
* This does not consider permissions since the sort operations are centrally
* managed by admins so considered permitted if existing and assigned.
*/
public function runBookAutoSort(Book $book): void
{
$rule = $book->sortRule()->first();
if (!($rule instanceof SortRule)) {
return;
}
$sortFunctions = array_map(function (SortRuleOperation $op) {
return $op->getSortFunction();
}, $rule->getOperations());
$chapters = $book->chapters()
->with('pages:id,name,book_id,chapter_id,priority,created_at,updated_at')
->get(['id', 'name', 'priority', 'created_at', 'updated_at']);
/** @var (Chapter|Book)[] $topItems */
$topItems = [
...$book->directPages()->get(['id', 'book_id', 'name', 'priority', 'created_at', 'updated_at']),
...$chapters,
];
foreach ($sortFunctions as $sortFunction) {
usort($topItems, $sortFunction);
}
foreach ($topItems as $index => $topItem) {
$topItem->priority = $index + 1;
$topItem::withoutTimestamps(fn () => $topItem->save());
}
foreach ($chapters as $chapter) {
$pages = $chapter->pages->all();
foreach ($sortFunctions as $sortFunction) {
usort($pages, $sortFunction);
}
foreach ($pages as $index => $page) {
$page->priority = $index + 1;
$page::withoutTimestamps(fn () => $page->save());
}
}
}
/**
* Sort the books content using the given sort map.
* Returns a list of books that were involved in the operation.
*
* @return Book[]
*/
public function sortUsingMap(BookSortMap $sortMap): array
{
// Load models into map
$modelMap = $this->loadModelsFromSortMap($sortMap);
// Sort our changes from our map to be chapters first
// Since they need to be process to ensure book alignment for child page changes.
$sortMapItems = $sortMap->all();
usort($sortMapItems, function (BookSortMapItem $itemA, BookSortMapItem $itemB) {
$aScore = $itemA->type === 'page' ? 2 : 1;
$bScore = $itemB->type === 'page' ? 2 : 1;
return $aScore - $bScore;
});
// Perform the sort
foreach ($sortMapItems as $item) {
$this->applySortUpdates($item, $modelMap);
}
/** @var Book[] $booksInvolved */
$booksInvolved = array_values(array_filter($modelMap, function (string $key) {
return str_starts_with($key, 'book:');
}, ARRAY_FILTER_USE_KEY));
// Update permissions of books involved
foreach ($booksInvolved as $book) {
$book->rebuildPermissions();
}
return $booksInvolved;
}
/**
* Using the given sort map item, detect changes for the related model
* and update it if required. Changes where permissions are lacking will
* be skipped and not throw an error.
*
* @param array<string, Entity> $modelMap
*/
protected function applySortUpdates(BookSortMapItem $sortMapItem, array $modelMap): void
{
/** @var BookChild $model */
$model = $modelMap[$sortMapItem->type . ':' . $sortMapItem->id] ?? null;
if (!$model) {
return;
}
$priorityChanged = $model->priority !== $sortMapItem->sort;
$bookChanged = $model->book_id !== $sortMapItem->parentBookId;
$chapterChanged = ($model instanceof Page) && $model->chapter_id !== $sortMapItem->parentChapterId;
// Stop if there's no change
if (!$priorityChanged && !$bookChanged && !$chapterChanged) {
return;
}
$currentParentKey = 'book:' . $model->book_id;
if ($model instanceof Page && $model->chapter_id) {
$currentParentKey = 'chapter:' . $model->chapter_id;
}
$currentParent = $modelMap[$currentParentKey] ?? null;
/** @var Book $newBook */
$newBook = $modelMap['book:' . $sortMapItem->parentBookId] ?? null;
/** @var ?Chapter $newChapter */
$newChapter = $sortMapItem->parentChapterId ? ($modelMap['chapter:' . $sortMapItem->parentChapterId] ?? null) : null;
if (!$this->isSortChangePermissible($sortMapItem, $model, $currentParent, $newBook, $newChapter)) {
return;
}
// Action the required changes
if ($bookChanged) {
$this->parentChanger->changeBook($model, $newBook->id);
}
if ($model instanceof Page && $chapterChanged) {
$model->chapter_id = $newChapter->id ?? 0;
$model->unsetRelation('chapter');
}
if ($priorityChanged) {
$model->priority = $sortMapItem->sort;
}
if ($chapterChanged || $priorityChanged) {
$model::withoutTimestamps(fn () => $model->save());
}
}
/**
* Check if the current user has permissions to apply the given sorting change.
* Is quite complex since items can gain a different parent change. Acts as a:
* - Update of old parent element (Change of content/order).
* - Update of sorted/moved element.
* - Deletion of element (Relative to parent upon move).
* - Creation of element within parent (Upon move to new parent).
*/
protected function isSortChangePermissible(BookSortMapItem $sortMapItem, BookChild $model, ?Entity $currentParent, ?Entity $newBook, ?Entity $newChapter): bool
{
// Stop if we can't see the current parent or new book.
if (!$currentParent || !$newBook) {
return false;
}
$hasNewParent = $newBook->id !== $model->book_id || ($model instanceof Page && $model->chapter_id !== ($sortMapItem->parentChapterId ?? 0));
if ($model instanceof Chapter) {
$hasPermission = userCan(Permission::BookUpdate, $currentParent)
&& userCan(Permission::BookUpdate, $newBook)
&& userCan(Permission::ChapterUpdate, $model)
&& (!$hasNewParent || userCan(Permission::ChapterCreate, $newBook))
&& (!$hasNewParent || userCan(Permission::ChapterDelete, $model));
if (!$hasPermission) {
return false;
}
}
if ($model instanceof Page) {
$parentPermission = ($currentParent instanceof Chapter) ? 'chapter-update' : 'book-update';
$hasCurrentParentPermission = userCan($parentPermission, $currentParent);
// This needs to check if there was an intended chapter location in the original sort map
// rather than inferring from the $newChapter since that variable may be null
// due to other reasons (Visibility).
$newParent = $sortMapItem->parentChapterId ? $newChapter : $newBook;
if (!$newParent) {
return false;
}
$hasPageEditPermission = userCan(Permission::PageUpdate, $model);
$newParentInRightLocation = ($newParent instanceof Book || ($newParent instanceof Chapter && $newParent->book_id === $newBook->id));
$newParentPermission = ($newParent instanceof Chapter) ? 'chapter-update' : 'book-update';
$hasNewParentPermission = userCan($newParentPermission, $newParent);
$hasDeletePermissionIfMoving = (!$hasNewParent || userCan(Permission::PageDelete, $model));
$hasCreatePermissionIfMoving = (!$hasNewParent || userCan(Permission::PageCreate, $newParent));
$hasPermission = $hasCurrentParentPermission
&& $newParentInRightLocation
&& $hasNewParentPermission
&& $hasPageEditPermission
&& $hasDeletePermissionIfMoving
&& $hasCreatePermissionIfMoving;
if (!$hasPermission) {
return false;
}
}
return true;
}
/**
* Load models from the database into the given sort map.
*
* @return array<string, Entity>
*/
protected function loadModelsFromSortMap(BookSortMap $sortMap): array
{
$modelMap = [];
$ids = [
'chapter' => [],
'page' => [],
'book' => [],
];
foreach ($sortMap->all() as $sortMapItem) {
$ids[$sortMapItem->type][] = $sortMapItem->id;
$ids['book'][] = $sortMapItem->parentBookId;
if ($sortMapItem->parentChapterId) {
$ids['chapter'][] = $sortMapItem->parentChapterId;
}
}
$pages = $this->queries->pages->visibleForList()->whereIn('id', array_unique($ids['page']))->get();
/** @var Page $page */
foreach ($pages as $page) {
$modelMap['page:' . $page->id] = $page;
$ids['book'][] = $page->book_id;
if ($page->chapter_id) {
$ids['chapter'][] = $page->chapter_id;
}
}
$chapters = $this->queries->chapters->visibleForList()->whereIn('id', array_unique($ids['chapter']))->get();
/** @var Chapter $chapter */
foreach ($chapters as $chapter) {
$modelMap['chapter:' . $chapter->id] = $chapter;
$ids['book'][] = $chapter->book_id;
}
$books = $this->queries->books->visibleForList()->whereIn('id', array_unique($ids['book']))->get();
/** @var Book $book */
foreach ($books as $book) {
$modelMap['book:' . $book->id] = $book;
}
return $modelMap;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Sorting/BookSortController.php | app/Sorting/BookSortController.php | <?php
namespace BookStack\Sorting;
use BookStack\Activity\ActivityType;
use BookStack\Entities\Queries\BookQueries;
use BookStack\Entities\Tools\BookContents;
use BookStack\Facades\Activity;
use BookStack\Http\Controller;
use BookStack\Permissions\Permission;
use BookStack\Util\DatabaseTransaction;
use Illuminate\Http\Request;
class BookSortController extends Controller
{
public function __construct(
protected BookQueries $queries,
) {
}
/**
* Shows the view which allows pages to be re-ordered and sorted.
*/
public function show(string $bookSlug)
{
$book = $this->queries->findVisibleBySlugOrFail($bookSlug);
$this->checkOwnablePermission(Permission::BookUpdate, $book);
$bookChildren = (new BookContents($book))->getTree(false);
$this->setPageTitle(trans('entities.books_sort_named', ['bookName' => $book->getShortName()]));
return view('books.sort', ['book' => $book, 'current' => $book, 'bookChildren' => $bookChildren]);
}
/**
* Shows the sort box for a single book.
* Used via AJAX when loading in extra books to a sort.
*/
public function showItem(string $bookSlug)
{
$book = $this->queries->findVisibleBySlugOrFail($bookSlug);
$bookChildren = (new BookContents($book))->getTree();
return view('books.parts.sort-box', ['book' => $book, 'bookChildren' => $bookChildren]);
}
/**
* Update the sort options of a book, setting the auto-sort and/or updating
* child order via mapping.
*/
public function update(Request $request, BookSorter $sorter, string $bookSlug)
{
$book = $this->queries->findVisibleBySlugOrFail($bookSlug);
$this->checkOwnablePermission(Permission::BookUpdate, $book);
$loggedActivityForBook = false;
// Sort via map
if ($request->filled('sort-tree')) {
(new DatabaseTransaction(function () use ($book, $request, $sorter, &$loggedActivityForBook) {
$sortMap = BookSortMap::fromJson($request->get('sort-tree'));
$booksInvolved = $sorter->sortUsingMap($sortMap);
// Add activity for involved books.
foreach ($booksInvolved as $bookInvolved) {
Activity::add(ActivityType::BOOK_SORT, $bookInvolved);
if ($bookInvolved->id === $book->id) {
$loggedActivityForBook = true;
}
}
}))->run();
}
if ($request->filled('auto-sort')) {
$sortSetId = intval($request->get('auto-sort')) ?: null;
if ($sortSetId && SortRule::query()->find($sortSetId) === null) {
$sortSetId = null;
}
$book->sort_rule_id = $sortSetId;
$book->save();
$sorter->runBookAutoSort($book);
if (!$loggedActivityForBook) {
Activity::add(ActivityType::BOOK_SORT, $book);
}
}
return redirect($book->getUrl());
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Sorting/SortUrl.php | app/Sorting/SortUrl.php | <?php
namespace BookStack\Sorting;
/**
* Generate a URL with multiple parameters for sorting purposes.
* Works out the logic to set the correct sorting direction
* Discards empty parameters and allows overriding.
*/
class SortUrl
{
public function __construct(
protected string $path,
protected array $data,
protected array $overrideData = []
) {
}
public function withOverrideData(array $overrideData = []): self
{
return new self($this->path, $this->data, $overrideData);
}
public function build(): string
{
$queryStringSections = [];
$queryData = array_merge($this->data, $this->overrideData);
// Change sorting direction if already sorted on current attribute
if (isset($this->overrideData['sort']) && $this->overrideData['sort'] === $this->data['sort']) {
$queryData['order'] = ($this->data['order'] === 'asc') ? 'desc' : 'asc';
} elseif (isset($this->overrideData['sort'])) {
$queryData['order'] = 'asc';
}
foreach ($queryData as $name => $value) {
$trimmedVal = trim($value);
if ($trimmedVal !== '') {
$queryStringSections[] = urlencode($name) . '=' . urlencode($trimmedVal);
}
}
if (count($queryStringSections) === 0) {
return url($this->path);
}
return url($this->path . '?' . implode('&', $queryStringSections));
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Sorting/SortRuleController.php | app/Sorting/SortRuleController.php | <?php
namespace BookStack\Sorting;
use BookStack\Activity\ActivityType;
use BookStack\Entities\Models\EntityContainerData;
use BookStack\Http\Controller;
use BookStack\Permissions\Permission;
use Illuminate\Http\Request;
class SortRuleController extends Controller
{
public function __construct()
{
$this->middleware(Permission::SettingsManage->middleware());
}
public function create()
{
$this->setPageTitle(trans('settings.sort_rule_create'));
return view('settings.sort-rules.create');
}
public function store(Request $request)
{
$this->validate($request, [
'name' => ['required', 'string', 'min:1', 'max:200'],
'sequence' => ['required', 'string', 'min:1'],
]);
$operations = SortRuleOperation::fromSequence($request->input('sequence'));
if (count($operations) === 0) {
return redirect('/settings/sorting/rules/new')->withInput()->withErrors(['sequence' => 'No operations set.']);
}
$rule = new SortRule();
$rule->name = $request->input('name');
$rule->setOperations($operations);
$rule->save();
$this->logActivity(ActivityType::SORT_RULE_CREATE, $rule);
return redirect('/settings/sorting');
}
public function edit(string $id)
{
$rule = SortRule::query()->findOrFail($id);
$this->setPageTitle(trans('settings.sort_rule_edit'));
return view('settings.sort-rules.edit', ['rule' => $rule]);
}
public function update(string $id, Request $request, BookSorter $bookSorter)
{
$this->validate($request, [
'name' => ['required', 'string', 'min:1', 'max:200'],
'sequence' => ['required', 'string', 'min:1'],
]);
$rule = SortRule::query()->findOrFail($id);
$operations = SortRuleOperation::fromSequence($request->input('sequence'));
if (count($operations) === 0) {
return redirect($rule->getUrl())->withInput()->withErrors(['sequence' => 'No operations set.']);
}
$rule->name = $request->input('name');
$rule->setOperations($operations);
$changedSequence = $rule->isDirty('sequence');
$rule->save();
$this->logActivity(ActivityType::SORT_RULE_UPDATE, $rule);
if ($changedSequence) {
$bookSorter->runBookAutoSortForAllWithSet($rule);
}
return redirect('/settings/sorting');
}
public function destroy(string $id, Request $request)
{
$rule = SortRule::query()->findOrFail($id);
$confirmed = $request->input('confirm') === 'true';
$booksAssigned = $rule->books()->count();
$warnings = [];
if ($booksAssigned > 0) {
if ($confirmed) {
EntityContainerData::query()
->where('sort_rule_id', $rule->id)
->update(['sort_rule_id' => null]);
} else {
$warnings[] = trans('settings.sort_rule_delete_warn_books', ['count' => $booksAssigned]);
}
}
$defaultBookSortSetting = intval(setting('sorting-book-default', '0'));
if ($defaultBookSortSetting === intval($id)) {
if ($confirmed) {
setting()->remove('sorting-book-default');
} else {
$warnings[] = trans('settings.sort_rule_delete_warn_default');
}
}
if (count($warnings) > 0) {
return redirect($rule->getUrl() . '#delete')->withErrors(['delete' => $warnings]);
}
$rule->delete();
$this->logActivity(ActivityType::SORT_RULE_DELETE, $rule);
return redirect('/settings/sorting');
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Sorting/SortRuleOperation.php | app/Sorting/SortRuleOperation.php | <?php
namespace BookStack\Sorting;
use Closure;
use Illuminate\Support\Str;
enum SortRuleOperation: string
{
case NameAsc = 'name_asc';
case NameDesc = 'name_desc';
case NameNumericAsc = 'name_numeric_asc';
case NameNumericDesc = 'name_numeric_desc';
case CreatedDateAsc = 'created_date_asc';
case CreatedDateDesc = 'created_date_desc';
case UpdateDateAsc = 'updated_date_asc';
case UpdateDateDesc = 'updated_date_desc';
case ChaptersFirst = 'chapters_first';
case ChaptersLast = 'chapters_last';
/**
* Provide a translated label string for this option.
*/
public function getLabel(): string
{
$key = $this->value;
$label = '';
if (str_ends_with($key, '_asc')) {
$key = substr($key, 0, -4);
$label = trans('settings.sort_rule_op_asc');
} elseif (str_ends_with($key, '_desc')) {
$key = substr($key, 0, -5);
$label = trans('settings.sort_rule_op_desc');
}
$label = trans('settings.sort_rule_op_' . $key) . ' ' . $label;
return trim($label);
}
public function getSortFunction(): callable
{
$camelValue = Str::camel($this->value);
return SortSetOperationComparisons::$camelValue(...);
}
/**
* @return SortRuleOperation[]
*/
public static function allExcluding(array $operations): array
{
$all = SortRuleOperation::cases();
$filtered = array_filter($all, function (SortRuleOperation $operation) use ($operations) {
return !in_array($operation, $operations);
});
return array_values($filtered);
}
/**
* Create a set of operations from a string sequence representation.
* (values seperated by commas).
* @return SortRuleOperation[]
*/
public static function fromSequence(string $sequence): array
{
$strOptions = explode(',', $sequence);
$options = array_map(fn ($val) => SortRuleOperation::tryFrom($val), $strOptions);
return array_filter($options);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Sorting/SortSetOperationComparisons.php | app/Sorting/SortSetOperationComparisons.php | <?php
namespace BookStack\Sorting;
use voku\helper\ASCII;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Models\Entity;
/**
* Sort comparison function for each of the possible SortSetOperation values.
* Method names should be camelCase names for the SortSetOperation enum value.
*/
class SortSetOperationComparisons
{
public static function nameAsc(Entity $a, Entity $b): int
{
return strtolower(ASCII::to_transliterate($a->name, null)) <=> strtolower(ASCII::to_transliterate($b->name, null));
}
public static function nameDesc(Entity $a, Entity $b): int
{
return strtolower(ASCII::to_transliterate($b->name, null)) <=> strtolower(ASCII::to_transliterate($a->name, null));
}
public static function nameNumericAsc(Entity $a, Entity $b): int
{
$numRegex = '/^\d+(\.\d+)?/';
$aMatches = [];
$bMatches = [];
preg_match($numRegex, $a->name, $aMatches);
preg_match($numRegex, $b->name, $bMatches);
$aVal = floatval(($aMatches[0] ?? 0));
$bVal = floatval(($bMatches[0] ?? 0));
return $aVal <=> $bVal;
}
public static function nameNumericDesc(Entity $a, Entity $b): int
{
return -(static::nameNumericAsc($a, $b));
}
public static function createdDateAsc(Entity $a, Entity $b): int
{
return $a->created_at->unix() <=> $b->created_at->unix();
}
public static function createdDateDesc(Entity $a, Entity $b): int
{
return $b->created_at->unix() <=> $a->created_at->unix();
}
public static function updatedDateAsc(Entity $a, Entity $b): int
{
return $a->updated_at->unix() <=> $b->updated_at->unix();
}
public static function updatedDateDesc(Entity $a, Entity $b): int
{
return $b->updated_at->unix() <=> $a->updated_at->unix();
}
public static function chaptersFirst(Entity $a, Entity $b): int
{
return ($b instanceof Chapter ? 1 : 0) - (($a instanceof Chapter) ? 1 : 0);
}
public static function chaptersLast(Entity $a, Entity $b): int
{
return ($a instanceof Chapter ? 1 : 0) - (($b instanceof Chapter) ? 1 : 0);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Sorting/BookSortMapItem.php | app/Sorting/BookSortMapItem.php | <?php
namespace BookStack\Sorting;
class BookSortMapItem
{
/**
* @var int
*/
public $id;
/**
* @var int
*/
public $sort;
/**
* @var ?int
*/
public $parentChapterId;
/**
* @var string
*/
public $type;
/**
* @var int
*/
public $parentBookId;
public function __construct(int $id, int $sort, ?int $parentChapterId, string $type, int $parentBookId)
{
$this->id = $id;
$this->sort = $sort;
$this->parentChapterId = $parentChapterId;
$this->type = $type;
$this->parentBookId = $parentBookId;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Sorting/SortRule.php | app/Sorting/SortRule.php | <?php
namespace BookStack\Sorting;
use BookStack\Activity\Models\Loggable;
use BookStack\Entities\Models\Book;
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 $sequence
* @property Carbon $created_at
* @property Carbon $updated_at
*/
class SortRule extends Model implements Loggable
{
use HasFactory;
/**
* @return SortRuleOperation[]
*/
public function getOperations(): array
{
return SortRuleOperation::fromSequence($this->sequence);
}
/**
* @param SortRuleOperation[] $options
*/
public function setOperations(array $options): void
{
$values = array_map(fn (SortRuleOperation $opt) => $opt->value, $options);
$this->sequence = implode(',', $values);
}
public function logDescriptor(): string
{
return "({$this->id}) {$this->name}";
}
public function getUrl(): string
{
return url("/settings/sorting/rules/{$this->id}");
}
public function books(): HasMany
{
return $this->hasMany(Book::class, 'entity_container_data.sort_rule_id', 'id');
}
public static function allByName(): Collection
{
return static::query()
->withCount('books')
->orderBy('name', 'asc')
->get();
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Sorting/BookSortMap.php | app/Sorting/BookSortMap.php | <?php
namespace BookStack\Sorting;
class BookSortMap
{
/**
* @var BookSortMapItem[]
*/
protected $mapData = [];
public function addItem(BookSortMapItem $mapItem): void
{
$this->mapData[] = $mapItem;
}
/**
* @return BookSortMapItem[]
*/
public function all(): array
{
return $this->mapData;
}
public static function fromJson(string $json): self
{
$map = new BookSortMap();
$mapData = json_decode($json);
foreach ($mapData as $mapDataItem) {
$item = new BookSortMapItem(
intval($mapDataItem->id),
intval($mapDataItem->sort),
$mapDataItem->parentChapter ? intval($mapDataItem->parentChapter) : null,
$mapDataItem->type,
intval($mapDataItem->book)
);
$map->addItem($item);
}
return $map;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Settings/MaintenanceController.php | app/Settings/MaintenanceController.php | <?php
namespace BookStack\Settings;
use BookStack\Activity\ActivityType;
use BookStack\App\AppVersion;
use BookStack\Entities\Tools\TrashCan;
use BookStack\Http\Controller;
use BookStack\Permissions\Permission;
use BookStack\References\ReferenceStore;
use BookStack\Uploads\ImageService;
use Illuminate\Http\Request;
class MaintenanceController extends Controller
{
/**
* Show the page for application maintenance.
*/
public function index(TrashCan $trashCan)
{
$this->checkPermission(Permission::SettingsManage);
$this->setPageTitle(trans('settings.maint'));
// Recycle bin details
$recycleStats = $trashCan->getTrashedCounts();
return view('settings.maintenance', [
'version' => AppVersion::get(),
'recycleStats' => $recycleStats,
]);
}
/**
* Action to clean-up images in the system.
*/
public function cleanupImages(Request $request, ImageService $imageService)
{
$this->checkPermission(Permission::SettingsManage);
$this->logActivity(ActivityType::MAINTENANCE_ACTION_RUN, 'cleanup-images');
$checkRevisions = !($request->get('ignore_revisions', 'false') === 'true');
$dryRun = !($request->has('confirm'));
$imagesToDelete = $imageService->deleteUnusedImages($checkRevisions, $dryRun);
$deleteCount = count($imagesToDelete);
if ($deleteCount === 0) {
$this->showWarningNotification(trans('settings.maint_image_cleanup_nothing_found'));
return redirect('/settings/maintenance')->withInput();
}
if ($dryRun) {
session()->flash('cleanup-images-warning', trans('settings.maint_image_cleanup_warning', ['count' => $deleteCount]));
} else {
$this->showSuccessNotification(trans('settings.maint_image_cleanup_success', ['count' => $deleteCount]));
}
return redirect('/settings/maintenance#image-cleanup')->withInput();
}
/**
* Action to send a test e-mail to the current user.
*/
public function sendTestEmail()
{
$this->checkPermission(Permission::SettingsManage);
$this->logActivity(ActivityType::MAINTENANCE_ACTION_RUN, 'send-test-email');
try {
user()->notifyNow(new TestEmailNotification());
$this->showSuccessNotification(trans('settings.maint_send_test_email_success', ['address' => user()->email]));
} catch (\Exception $exception) {
$errorMessage = trans('errors.maintenance_test_email_failure') . "\n" . $exception->getMessage();
$this->showErrorNotification($errorMessage);
}
return redirect('/settings/maintenance#image-cleanup');
}
/**
* Action to regenerate the reference index in the system.
*/
public function regenerateReferences(ReferenceStore $referenceStore)
{
$this->checkPermission(Permission::SettingsManage);
$this->logActivity(ActivityType::MAINTENANCE_ACTION_RUN, 'regenerate-references');
try {
$referenceStore->updateForAll();
$this->showSuccessNotification(trans('settings.maint_regen_references_success'));
} catch (\Exception $exception) {
$this->showErrorNotification($exception->getMessage());
}
return redirect('/settings/maintenance#regenerate-references');
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Settings/UserNotificationPreferences.php | app/Settings/UserNotificationPreferences.php | <?php
namespace BookStack\Settings;
use BookStack\Users\Models\User;
class UserNotificationPreferences
{
public function __construct(
protected User $user
) {
}
public function notifyOnOwnPageChanges(): bool
{
return $this->getNotificationSetting('own-page-changes');
}
public function notifyOnOwnPageComments(): bool
{
return $this->getNotificationSetting('own-page-comments');
}
public function notifyOnCommentReplies(): bool
{
return $this->getNotificationSetting('comment-replies');
}
public function notifyOnCommentMentions(): bool
{
return $this->getNotificationSetting('comment-mentions');
}
public function updateFromSettingsArray(array $settings)
{
$allowList = ['own-page-changes', 'own-page-comments', 'comment-replies', 'comment-mentions'];
foreach ($settings as $setting => $status) {
if (!in_array($setting, $allowList)) {
continue;
}
$value = $status === 'true' ? 'true' : 'false';
setting()->putUser($this->user, 'notifications#' . $setting, $value);
}
}
protected function getNotificationSetting(string $key): bool
{
return setting()->getUser($this->user, 'notifications#' . $key);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Settings/StatusController.php | app/Settings/StatusController.php | <?php
namespace BookStack\Settings;
use BookStack\Http\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
class StatusController extends Controller
{
/**
* Show the system status as a simple json page.
*/
public function show()
{
$statuses = [
'database' => $this->trueWithoutError(function () {
return DB::table('migrations')->count() > 0;
}),
'cache' => $this->trueWithoutError(function () {
$rand = Str::random(12);
$key = "status_test_{$rand}";
Cache::add($key, $rand);
return Cache::pull($key) === $rand;
}),
'session' => $this->trueWithoutError(function () {
$rand = Str::random();
Session::put('status_test', $rand);
return Session::get('status_test') === $rand;
}),
];
$hasError = in_array(false, $statuses);
return response()->json($statuses, $hasError ? 500 : 200);
}
/**
* Check the callable passed returns true and does not throw an exception.
*/
protected function trueWithoutError(callable $test): bool
{
try {
return $test() === true;
} catch (\Exception $e) {
return false;
}
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Settings/SettingController.php | app/Settings/SettingController.php | <?php
namespace BookStack\Settings;
use BookStack\Activity\ActivityType;
use BookStack\App\AppVersion;
use BookStack\Http\Controller;
use BookStack\Permissions\Permission;
use BookStack\Users\Models\User;
use Illuminate\Http\Request;
class SettingController extends Controller
{
/**
* Handle requests to the settings index path.
*/
public function index()
{
return redirect('/settings/features');
}
/**
* Display the settings for the given category.
*/
public function category(string $category)
{
$this->ensureCategoryExists($category);
$this->checkPermission(Permission::SettingsManage);
$this->setPageTitle(trans('settings.settings'));
return view('settings.categories.' . $category, [
'category' => $category,
'version' => AppVersion::get(),
'guestUser' => User::getGuest(),
]);
}
/**
* Update the specified settings in storage.
*/
public function update(Request $request, AppSettingsStore $store, string $category)
{
$this->ensureCategoryExists($category);
$this->preventAccessInDemoMode();
$this->checkPermission(Permission::SettingsManage);
$this->validate($request, [
'app_logo' => ['nullable', ...$this->getImageValidationRules()],
'app_icon' => ['nullable', ...$this->getImageValidationRules()],
]);
$store->storeFromUpdateRequest($request, $category);
$this->logActivity(ActivityType::SETTINGS_UPDATE, $category);
return redirect("/settings/{$category}");
}
protected function ensureCategoryExists(string $category): void
{
if (!view()->exists('settings.categories.' . $category)) {
abort(404);
}
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Settings/UserShortcutMap.php | app/Settings/UserShortcutMap.php | <?php
namespace BookStack\Settings;
class UserShortcutMap
{
protected const DEFAULTS = [
// Header actions
"home_view" => "1",
"shelves_view" => "2",
"books_view" => "3",
"settings_view" => "4",
"favourites_view" => "5",
"profile_view" => "6",
"global_search" => "/",
"logout" => "0",
// Common actions
"edit" => "e",
"new" => "n",
"copy" => "c",
"delete" => "d",
"favourite" => "f",
"export" => "x",
"sort" => "s",
"permissions" => "p",
"move" => "m",
"revisions" => "r",
// Navigation
"next" => "ArrowRight",
"previous" => "ArrowLeft",
];
/**
* @var array<string, string>
*/
protected array $mapping;
public function __construct(array $map)
{
$this->mapping = static::DEFAULTS;
$this->merge($map);
}
/**
* Merge the given map into the current shortcut mapping.
*/
protected function merge(array $map): void
{
foreach ($map as $key => $value) {
if (is_string($value) && isset($this->mapping[$key])) {
$this->mapping[$key] = $value;
}
}
}
/**
* Get the shortcut defined for the given ID.
*/
public function getShortcut(string $id): string
{
return $this->mapping[$id] ?? '';
}
/**
* Convert this mapping to JSON.
*/
public function toJson(): string
{
return json_encode($this->mapping);
}
/**
* Create a new instance from the current user's preferences.
*/
public static function fromUserPreferences(): self
{
$userKeyMap = setting()->getForCurrentUser('ui-shortcuts');
return new self(json_decode($userKeyMap, true) ?: []);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Settings/SettingService.php | app/Settings/SettingService.php | <?php
namespace BookStack\Settings;
use BookStack\Users\Models\User;
/**
* Class SettingService
* The settings are a simple key-value database store.
* For non-authenticated users, user settings are stored via the session instead.
* A local array-based cache is used to for setting accesses across a request.
*/
class SettingService
{
protected array $localCache = [];
/**
* Gets a setting from the database,
* If not found, Returns default, Which is false by default.
*/
public function get(string $key, $default = null): mixed
{
if (is_null($default)) {
$default = config('setting-defaults.' . $key, false);
}
$value = $this->getValueFromStore($key) ?? $default;
return $this->formatValue($value, $default);
}
/**
* Get a setting from the database as an integer.
* Returns the default value if not found or not an integer, and clamps the value to the given min/max range.
*/
public function getInteger(string $key, int $default, int $min = 0, int $max = PHP_INT_MAX): int
{
$value = $this->get($key, $default);
if (!is_numeric($value)) {
return $default;
}
$int = intval($value);
return max($min, min($max, $int));
}
/**
* Get a value from the session instead of the main store option.
*/
protected function getFromSession(string $key, $default = false)
{
$value = session()->get($key, $default);
return $this->formatValue($value, $default);
}
/**
* Get a user-specific setting from the database or cache.
*/
public function getUser(User $user, string $key, $default = null)
{
if (is_null($default)) {
$default = config('setting-defaults.user.' . $key, false);
}
if ($user->isGuest()) {
return $this->getFromSession($key, $default);
}
return $this->get($this->userKey($user->id, $key), $default);
}
/**
* Get a value for the current logged-in user.
*/
public function getForCurrentUser(string $key, $default = null)
{
return $this->getUser(user(), $key, $default);
}
/**
* Gets a setting value from the local cache.
* Will load the local cache if not previously loaded.
*/
protected function getValueFromStore(string $key): mixed
{
$cacheCategory = $this->localCacheCategory($key);
if (!isset($this->localCache[$cacheCategory])) {
$this->loadToLocalCache($cacheCategory);
}
return $this->localCache[$cacheCategory][$key] ?? null;
}
/**
* Put the given value into the local cached under the given key.
*/
protected function putValueIntoLocalCache(string $key, mixed $value): void
{
$cacheCategory = $this->localCacheCategory($key);
if (!isset($this->localCache[$cacheCategory])) {
$this->loadToLocalCache($cacheCategory);
}
$this->localCache[$cacheCategory][$key] = $value;
}
/**
* Get the category for the given setting key.
* Will return 'app' for a general app setting otherwise 'user:<user_id>' for a user setting.
*/
protected function localCacheCategory(string $key): string
{
if (str_starts_with($key, 'user:')) {
return implode(':', array_slice(explode(':', $key), 0, 2));
}
return 'app';
}
/**
* For the given category, load the relevant settings from the database into the local cache.
*/
protected function loadToLocalCache(string $cacheCategory): void
{
$query = Setting::query();
if ($cacheCategory === 'app') {
$query->where('setting_key', 'not like', 'user:%');
} else {
$query->where('setting_key', 'like', $cacheCategory . ':%');
}
$settings = $query->toBase()->get();
if (!isset($this->localCache[$cacheCategory])) {
$this->localCache[$cacheCategory] = [];
}
foreach ($settings as $setting) {
$value = $setting->value;
if ($setting->type === 'array') {
$value = json_decode($value, true) ?? [];
}
$this->localCache[$cacheCategory][$setting->setting_key] = $value;
}
}
/**
* Format a settings value.
*/
protected function formatValue(mixed $value, mixed $default): mixed
{
// Change string booleans to actual booleans
if ($value === 'true') {
$value = true;
} elseif ($value === 'false') {
$value = false;
}
// Set to default if empty
if ($value === '') {
$value = $default;
}
return $value;
}
/**
* Checks if a setting exists.
*/
public function has(string $key): bool
{
$setting = $this->getSettingObjectByKey($key);
return $setting !== null;
}
/**
* Add a setting to the database.
* Values can be an array or a string.
*/
public function put(string $key, mixed $value): bool
{
$setting = Setting::query()->firstOrNew([
'setting_key' => $key,
]);
$setting->type = 'string';
$setting->value = $value;
if (is_array($value)) {
$setting->type = 'array';
$setting->value = $this->formatArrayValue($value);
}
$setting->save();
$this->putValueIntoLocalCache($key, $value);
return true;
}
/**
* Format an array to be stored as a setting.
* Array setting types are expected to be a flat array of child key=>value array items.
* This filters out any child items that are empty.
*/
protected function formatArrayValue(array $value): string
{
$values = collect($value)->values()->filter(function (array $item) {
return count(array_filter($item)) > 0;
});
return json_encode($values);
}
/**
* Put a user-specific setting into the database.
* Can only take string value types since this may use
* the session which is less flexible to data types.
*/
public function putUser(User $user, string $key, string $value): bool
{
if ($user->isGuest()) {
session()->put($key, $value);
return true;
}
return $this->put($this->userKey($user->id, $key), $value);
}
/**
* Put a user-specific setting into the database for the current access user.
* Can only take string value types since this may use
* the session which is less flexible to data types.
*/
public function putForCurrentUser(string $key, string $value): bool
{
return $this->putUser(user(), $key, $value);
}
/**
* Convert a setting key into a user-specific key.
*/
protected function userKey(string $userId, string $key = ''): string
{
return 'user:' . $userId . ':' . $key;
}
/**
* Removes a setting from the database.
*/
public function remove(string $key): void
{
$setting = $this->getSettingObjectByKey($key);
if ($setting) {
$setting->delete();
}
$cacheCategory = $this->localCacheCategory($key);
if (isset($this->localCache[$cacheCategory])) {
unset($this->localCache[$cacheCategory][$key]);
}
}
/**
* Delete settings for a given user id.
*/
public function deleteUserSettings(string $userId): void
{
Setting::query()
->where('setting_key', 'like', $this->userKey($userId) . '%')
->delete();
}
/**
* Gets a setting model from the database for the given key.
*/
protected function getSettingObjectByKey(string $key): ?Setting
{
return Setting::query()
->where('setting_key', '=', $key)
->first();
}
/**
* Empty the local setting value cache used by this service.
*/
public function flushCache(): void
{
$this->localCache = [];
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Settings/AppSettingsStore.php | app/Settings/AppSettingsStore.php | <?php
namespace BookStack\Settings;
use BookStack\Uploads\FaviconHandler;
use BookStack\Uploads\ImageRepo;
use Illuminate\Http\Request;
class AppSettingsStore
{
public function __construct(
protected ImageRepo $imageRepo,
protected FaviconHandler $faviconHandler,
) {
}
public function storeFromUpdateRequest(Request $request, string $category): void
{
$this->storeSimpleSettings($request);
if ($category === 'customization') {
$this->updateAppLogo($request);
$this->updateAppIcon($request);
}
}
protected function updateAppIcon(Request $request): void
{
$sizes = [180, 128, 64, 32];
// Update icon image if set
if ($request->hasFile('app_icon')) {
$iconFile = $request->file('app_icon');
$this->destroyExistingSettingImage('app-icon');
$image = $this->imageRepo->saveNew($iconFile, 'system', 0, 256, 256);
setting()->put('app-icon', $image->url);
foreach ($sizes as $size) {
$this->destroyExistingSettingImage('app-icon-' . $size);
$icon = $this->imageRepo->saveNew($iconFile, 'system', 0, $size, $size);
setting()->put('app-icon-' . $size, $icon->url);
}
$this->faviconHandler->saveForUploadedImage($iconFile);
}
// Clear icon image if requested
if ($request->get('app_icon_reset')) {
$this->destroyExistingSettingImage('app-icon');
setting()->remove('app-icon');
foreach ($sizes as $size) {
$this->destroyExistingSettingImage('app-icon-' . $size);
setting()->remove('app-icon-' . $size);
}
$this->faviconHandler->restoreOriginal();
}
}
protected function updateAppLogo(Request $request): void
{
// Update logo image if set
if ($request->hasFile('app_logo')) {
$logoFile = $request->file('app_logo');
$this->destroyExistingSettingImage('app-logo');
$image = $this->imageRepo->saveNew($logoFile, 'system', 0, null, 86);
setting()->put('app-logo', $image->url);
}
// Clear logo image if requested
if ($request->get('app_logo_reset')) {
$this->destroyExistingSettingImage('app-logo');
setting()->remove('app-logo');
}
}
protected function storeSimpleSettings(Request $request): void
{
foreach ($request->all() as $name => $value) {
if (!str_starts_with($name, 'setting-')) {
continue;
}
$key = str_replace('setting-', '', trim($name));
setting()->put($key, $value);
}
}
protected function destroyExistingSettingImage(string $settingKey): void
{
$existingVal = setting()->get($settingKey);
if ($existingVal) {
$this->imageRepo->destroyByUrlAndType($existingVal, 'system');
}
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Settings/TestEmailNotification.php | app/Settings/TestEmailNotification.php | <?php
namespace BookStack\Settings;
use BookStack\App\MailNotification;
use BookStack\Users\Models\User;
use Illuminate\Notifications\Messages\MailMessage;
class TestEmailNotification extends MailNotification
{
public function toMail(User $notifiable): MailMessage
{
return $this->newMailMessage()
->subject(trans('settings.maint_send_test_email_mail_subject'))
->greeting(trans('settings.maint_send_test_email_mail_greeting'))
->line(trans('settings.maint_send_test_email_mail_text'));
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/app/Settings/Setting.php | app/Settings/Setting.php | <?php
namespace BookStack\Settings;
use BookStack\App\Model;
class Setting extends Model
{
protected $fillable = ['setting_key', 'value'];
protected $primaryKey = 'setting_key';
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/dev/licensing/gen-licenses-shared.php | dev/licensing/gen-licenses-shared.php | <?php
declare(strict_types=1);
$warnings = [];
function findLicenseFile(string $packageName, string $packagePath): string
{
$licenseNameOptions = [
'license', 'LICENSE', 'License',
'license.*', 'LICENSE.*', 'License.*',
'license-*.*', 'LICENSE-*.*', 'License-*.*',
];
$packageDir = dirname($packagePath);
$foundLicenses = [];
foreach ($licenseNameOptions as $option) {
$search = glob("{$packageDir}/$option");
array_push($foundLicenses, ...$search);
}
if (count($foundLicenses) > 1) {
warn("Package {$packageName}: more than one license file found");
}
if (count($foundLicenses) > 0) {
$fileName = basename($foundLicenses[0]);
return "{$packageDir}/{$fileName}";
}
warn("Package {$packageName}: no license files found");
return '';
}
function findCopyright(string $licenseFile): string
{
$fileContents = file_get_contents($licenseFile);
$pattern = '/^.*?copyright (\(c\)|\d{4})[\s\S]*?(\n\n|\.\n)/mi';
$matches = [];
preg_match($pattern, $fileContents, $matches);
$copyright = trim($matches[0] ?? '');
if (str_contains($copyright, 'i.e.')) {
return '';
}
$emailPattern = '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i';
return preg_replace_callback($emailPattern, obfuscateEmail(...), $copyright);
}
function obfuscateEmail(array $matches): string
{
return preg_replace('/[^@.]/', '*', $matches[1]);
}
function warn(string $text): void
{
global $warnings;
$warnings[] = "WARN:" . $text;
}
function getWarnings(): array
{
global $warnings;
return $warnings;
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/bootstrap/app.php | bootstrap/app.php | <?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new \BookStack\App\Application(
dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
BookStack\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
BookStack\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
BookStack\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/bootstrap/phpstan.php | bootstrap/phpstan.php | <?php
// Overwrite configuration that can interfere with the phpstan/larastan scanning.
config()->set([
'filesystems.default' => 'local',
]);
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/ErrorTest.php | tests/ErrorTest.php | <?php
namespace Tests;
use Illuminate\Foundation\Http\Middleware\ValidatePostSize;
use Illuminate\Support\Facades\Log;
class ErrorTest extends TestCase
{
public function test_404_page_does_not_show_login()
{
// Due to middleware being handled differently this will not fail
// if our custom, middleware-loaded handler fails but this is here
// as a reminder and as a general check in the event of other issues.
$editor = $this->users->editor();
$editor->name = 'tester';
$editor->save();
$this->actingAs($editor);
$notFound = $this->get('/fgfdngldfnotfound');
$notFound->assertStatus(404);
$notFound->assertDontSeeText('Log in');
$notFound->assertSeeText('tester');
}
public function test_404_page_does_not_non_visible_content()
{
$editor = $this->users->editor();
$book = $this->entities->book();
$this->actingAs($editor)->get($book->getUrl())->assertOk();
$this->permissions->disableEntityInheritedPermissions($book);
$this->actingAs($editor)->get($book->getUrl())->assertNotFound();
}
public function test_404_page_shows_visible_content_within_non_visible_parent()
{
$editor = $this->users->editor();
$book = $this->entities->book();
$page = $book->pages()->first();
$this->actingAs($editor)->get($page->getUrl())->assertOk();
$this->permissions->disableEntityInheritedPermissions($book);
$this->permissions->addEntityPermission($page, ['view'], $editor->roles()->first());
$resp = $this->actingAs($editor)->get($book->getUrl());
$resp->assertNotFound();
$resp->assertSee($page->name);
$resp->assertDontSee($book->name);
}
public function test_item_not_found_does_not_get_logged_to_file()
{
$this->actingAs($this->users->viewer());
$handler = $this->withTestLogger();
$book = $this->entities->book();
// Ensure we're seeing errors
Log::error('cat');
$this->assertTrue($handler->hasErrorThatContains('cat'));
$this->get('/books/arandomnotfouindbook');
$this->get($book->getUrl('/chapter/arandomnotfouindchapter'));
$this->get($book->getUrl('/chapter/arandomnotfouindpages'));
$this->assertCount(1, $handler->getRecords());
}
public function test_access_to_non_existing_image_location_provides_404_response()
{
$resp = $this->actingAs($this->users->viewer())->get('/uploads/images/gallery/2021-05/anonexistingimage.png');
$resp->assertStatus(404);
$resp->assertSeeText('Image Not Found');
}
public function test_posts_above_php_limit_shows_friendly_error()
{
// Fake super large JSON request
$resp = $this->asEditor()->call('GET', '/books', [], [], [], [
'CONTENT_LENGTH' => '10000000000',
'HTTP_ACCEPT' => 'application/json',
]);
$resp->assertStatus(413);
$resp->assertJson(['error' => 'The server cannot receive the provided amount of data. Try again with less data or a smaller file.']);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/DebugViewTest.php | tests/DebugViewTest.php | <?php
namespace Tests;
use BookStack\Access\SocialDriverManager;
use Illuminate\Testing\TestResponse;
class DebugViewTest extends TestCase
{
public function test_debug_view_shows_expected_details()
{
config()->set('app.debug', true);
$resp = $this->getDebugViewForException(new \InvalidArgumentException('An error occurred during testing'));
// Error message
$resp->assertSeeText('An error occurred during testing');
// Exception Class
$resp->assertSeeText('InvalidArgumentException');
// Stack trace
$resp->assertSeeText('#0');
$resp->assertSeeText('#1');
// Warning message
$resp->assertSeeText('WARNING: Application is in debug mode. This mode has the potential to leak');
// PHP version
$resp->assertSeeText('PHP Version: ' . phpversion());
// BookStack version
$resp->assertSeeText('BookStack Version: ' . trim(file_get_contents(base_path('version'))));
// Dynamic help links
$this->withHtml($resp)->assertElementExists('a[href*="q=' . urlencode('BookStack An error occurred during testing') . '"]');
$this->withHtml($resp)->assertElementExists('a[href*="?q=is%3Aissue+' . urlencode('An error occurred during testing') . '"]');
}
public function test_debug_view_only_shows_when_debug_mode_is_enabled()
{
config()->set('app.debug', true);
$resp = $this->getDebugViewForException(new \InvalidArgumentException('An error occurred during testing'));
$resp->assertSeeText('Stack Trace');
$resp->assertDontSeeText('An unknown error occurred');
config()->set('app.debug', false);
$resp = $this->getDebugViewForException(new \InvalidArgumentException('An error occurred during testing'));
$resp->assertDontSeeText('Stack Trace');
$resp->assertSeeText('An unknown error occurred');
}
protected function getDebugViewForException(\Exception $exception): TestResponse
{
// Fake an error via social auth service used on login page
$mockService = $this->mock(SocialDriverManager::class);
$mockService->shouldReceive('getActive')->andThrow($exception);
return $this->get('/login');
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/SessionTest.php | tests/SessionTest.php | <?php
namespace Tests;
class SessionTest extends TestCase
{
public function test_secure_images_not_tracked_in_session_history()
{
config()->set('filesystems.images', 'local_secure');
$this->asEditor();
$page = $this->entities->page();
$result = $this->files->uploadGalleryImageToPage($this, $page);
$expectedPath = storage_path($result['path']);
$this->assertFileExists($expectedPath);
$this->get('/books');
$this->assertEquals(url('/books'), session()->previousUrl());
$resp = $this->get($result['path']);
$resp->assertOk();
$resp->assertHeader('Content-Type', 'image/png');
$this->assertEquals(url('/books'), session()->previousUrl());
if (file_exists($expectedPath)) {
unlink($expectedPath);
}
}
public function test_pwa_manifest_is_not_tracked_in_session_history()
{
$this->asEditor()->get('/books');
$this->get('/manifest.json');
$this->assertEquals(url('/books'), session()->previousUrl());
}
public function test_dist_dir_access_is_not_tracked_in_session_history()
{
$this->asEditor()->get('/books');
$this->get('/dist/sub/hello.txt');
$this->assertEquals(url('/books'), session()->previousUrl());
}
public function test_opensearch_is_not_tracked_in_session_history()
{
$this->asEditor()->get('/books');
$this->get('/opensearch.xml');
$this->assertEquals(url('/books'), session()->previousUrl());
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/LanguageTest.php | tests/LanguageTest.php | <?php
namespace Tests;
use BookStack\Activity\ActivityType;
use BookStack\Translation\LocaleManager;
class LanguageTest extends TestCase
{
protected array $langs;
/**
* LanguageTest constructor.
*/
protected function setUp(): void
{
parent::setUp();
$this->langs = array_diff(scandir(lang_path('')), ['..', '.']);
}
public function test_locales_list_set_properly()
{
$appLocales = $this->app->make(LocaleManager::class)->getAllAppLocales();
sort($appLocales);
sort($this->langs);
$this->assertEquals(implode(':', $this->langs), implode(':', $appLocales), 'app.locales configuration variable does not match those found in lang files');
}
// Not part of standard phpunit test runs since we sometimes expect non-added langs.
public function test_locales_all_have_language_dropdown_entry()
{
$this->markTestSkipped('Only used when checking language inclusion');
$dropdownLocales = array_keys(trans('settings.language_select', [], 'en'));
sort($dropdownLocales);
sort($this->langs);
$diffs = array_diff($this->langs, $dropdownLocales);
if (count($diffs) > 0) {
$diffText = implode(',', $diffs);
$warning = "Languages: {$diffText} found in files but not in language select dropdown.";
$this->fail($warning);
}
$this->assertTrue(true);
}
public function test_correct_language_if_not_logged_in()
{
$loginReq = $this->get('/login');
$loginReq->assertSee('Log In');
$loginPageFrenchReq = $this->get('/login', ['Accept-Language' => 'fr']);
$loginPageFrenchReq->assertSee('Se Connecter');
}
public function test_public_lang_autodetect_can_be_disabled()
{
config()->set('app.auto_detect_locale', false);
$loginReq = $this->get('/login');
$loginReq->assertSee('Log In');
$loginPageFrenchReq = $this->get('/login', ['Accept-Language' => 'fr']);
$loginPageFrenchReq->assertDontSee('Se Connecter');
}
public function test_all_lang_files_loadable()
{
$files = array_diff(scandir(lang_path('en')), ['..', '.']);
foreach ($this->langs as $lang) {
foreach ($files as $file) {
$loadError = false;
try {
$translations = trans(str_replace('.php', '', $file), [], $lang);
} catch (\Exception $e) {
$loadError = true;
}
$this->assertFalse($loadError, "Translation file {$lang}/{$file} failed to load");
}
}
}
public function test_views_use_rtl_if_rtl_language_is_set()
{
$this->asEditor()->withHtml($this->get('/'))->assertElementExists('html[dir="ltr"]');
setting()->putUser($this->users->editor(), 'language', 'ar');
$this->withHtml($this->get('/'))->assertElementExists('html[dir="rtl"]');
}
public function test_unknown_lang_does_not_break_app()
{
config()->set('app.locale', 'zz');
$loginReq = $this->get('/login', ['Accept-Language' => 'zz']);
$loginReq->assertOk();
$loginReq->assertSee('Log In');
}
public function test_all_activity_types_have_activity_text()
{
foreach (ActivityType::all() as $activityType) {
$langKey = 'activities.' . $activityType;
$this->assertNotEquals($langKey, trans($langKey, [], 'en'));
}
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/HomepageTest.php | tests/HomepageTest.php | <?php
namespace Tests;
use BookStack\Users\Models\Role;
use BookStack\Users\Models\User;
class HomepageTest extends TestCase
{
public function test_default_homepage_visible()
{
$this->asEditor();
$homeVisit = $this->get('/');
$homeVisit->assertSee('My Recently Viewed');
$homeVisit->assertSee('Recently Updated Pages');
$homeVisit->assertSee('Recent Activity');
$homeVisit->assertSee('home-default');
}
public function test_custom_homepage()
{
$this->asEditor();
$name = 'My custom homepage';
$content = str_repeat('This is the body content of my custom homepage.', 20);
$customPage = $this->entities->newPage(['name' => $name, 'html' => $content]);
$this->setSettings(['app-homepage' => $customPage->id]);
$this->setSettings(['app-homepage-type' => 'page']);
$homeVisit = $this->get('/');
$homeVisit->assertSee($name);
$homeVisit->assertSee($content);
$homeVisit->assertSee('My Recently Viewed');
$homeVisit->assertSee('Recently Updated Pages');
$homeVisit->assertSee('Recent Activity');
}
public function test_delete_custom_homepage()
{
$this->asEditor();
$name = 'My custom homepage';
$content = str_repeat('This is the body content of my custom homepage.', 20);
$customPage = $this->entities->newPage(['name' => $name, 'html' => $content]);
$this->setSettings([
'app-homepage' => $customPage->id,
'app-homepage-type' => 'page',
]);
$homeVisit = $this->get('/');
$homeVisit->assertSee($name);
$this->withHtml($homeVisit)->assertElementNotExists('#home-default');
$pageDeleteReq = $this->delete($customPage->getUrl());
$pageDeleteReq->assertStatus(302);
$pageDeleteReq->assertRedirect($customPage->getUrl());
$pageDeleteReq->assertSessionHas('error');
$pageDeleteReq->assertSessionMissing('success');
$homeVisit = $this->get('/');
$homeVisit->assertSee($name);
$homeVisit->assertStatus(200);
}
public function test_custom_homepage_can_be_deleted_once_custom_homepage_no_longer_used()
{
$this->asEditor();
$name = 'My custom homepage';
$content = str_repeat('This is the body content of my custom homepage.', 20);
$customPage = $this->entities->newPage(['name' => $name, 'html' => $content]);
$this->setSettings([
'app-homepage' => $customPage->id,
'app-homepage-type' => 'default',
]);
$pageDeleteReq = $this->delete($customPage->getUrl());
$pageDeleteReq->assertStatus(302);
$pageDeleteReq->assertSessionHas('success');
$pageDeleteReq->assertSessionMissing('error');
}
public function test_custom_homepage_cannot_be_deleted_from_parent_deletion()
{
$page = $this->entities->page();
$this->setSettings([
'app-homepage' => $page->id,
'app-homepage-type' => 'page',
]);
$this->asEditor()->delete($page->book->getUrl());
$this->assertSessionError('Cannot delete a page while it is set as a homepage');
$this->assertDatabaseMissing('deletions', ['deletable_id' => $page->book->id]);
$page->refresh();
$this->assertNull($page->deleted_at);
$this->assertNull($page->book->deleted_at);
}
public function test_custom_homepage_renders_includes()
{
$this->asEditor();
$included = $this->entities->page();
$content = str_repeat('This is the body content of my custom homepage.', 20);
$included->html = $content;
$included->save();
$name = 'My custom homepage';
$customPage = $this->entities->newPage(['name' => $name, 'html' => '{{@' . $included->id . '}}']);
$this->setSettings(['app-homepage' => $customPage->id]);
$this->setSettings(['app-homepage-type' => 'page']);
$homeVisit = $this->get('/');
$homeVisit->assertSee($name);
$homeVisit->assertSee($content);
}
public function test_set_book_homepage()
{
$editor = $this->users->editor();
setting()->putUser($editor, 'books_view_type', 'grid');
$this->setSettings(['app-homepage-type' => 'books']);
$this->asEditor();
$homeVisit = $this->get('/');
$homeVisit->assertSee('Books');
$homeVisit->assertSee('grid-card');
$homeVisit->assertSee('grid-card-content');
$homeVisit->assertSee('grid-card-footer');
$homeVisit->assertSee('featured-image-container');
}
public function test_set_bookshelves_homepage()
{
$editor = $this->users->editor();
setting()->putUser($editor, 'bookshelves_view_type', 'grid');
$shelf = $this->entities->shelf();
$this->setSettings(['app-homepage-type' => 'bookshelves']);
$this->asEditor();
$homeVisit = $this->get('/');
$homeVisit->assertSee('Shelves');
$homeVisit->assertSee('grid-card-content');
$homeVisit->assertSee('featured-image-container');
$this->withHtml($homeVisit)->assertElementContains('.grid-card', $shelf->name);
}
public function test_books_and_bookshelves_homepage_has_expected_actions()
{
$this->asEditor();
foreach (['bookshelves', 'books'] as $homepageType) {
$this->setSettings(['app-homepage-type' => $homepageType]);
$html = $this->withHtml($this->get('/'));
$html->assertElementContains('.actions button', 'Dark Mode');
$html->assertElementContains('.actions a[href$="/tags"]', 'View Tags');
}
}
public function test_shelves_list_homepage_adheres_to_book_visibility_permissions()
{
$editor = $this->users->editor();
setting()->putUser($editor, 'bookshelves_view_type', 'list');
$this->setSettings(['app-homepage-type' => 'bookshelves']);
$this->asEditor();
$shelf = $this->entities->shelf();
$book = $shelf->books()->first();
// Ensure initially visible
$homeVisit = $this->get('/');
$this->withHtml($homeVisit)->assertElementContains('.content-wrap', $shelf->name);
$this->withHtml($homeVisit)->assertElementContains('.content-wrap', $book->name);
// Ensure book no longer visible without view permission
$editor->roles()->detach();
$this->permissions->grantUserRolePermissions($editor, ['bookshelf-view-all']);
$homeVisit = $this->get('/');
$this->withHtml($homeVisit)->assertElementContains('.content-wrap', $shelf->name);
$this->withHtml($homeVisit)->assertElementNotContains('.content-wrap', $book->name);
// Ensure is visible again with entity-level view permission
$this->permissions->setEntityPermissions($book, ['view'], [$editor->roles()->first()]);
$homeVisit = $this->get('/');
$this->withHtml($homeVisit)->assertElementContains('.content-wrap', $shelf->name);
$this->withHtml($homeVisit)->assertElementContains('.content-wrap', $book->name);
}
public function test_new_users_dont_have_any_recently_viewed()
{
$user = User::factory()->create();
$viewRole = Role::getRole('Viewer');
$user->attachRole($viewRole);
$homeVisit = $this->actingAs($user)->get('/');
$this->withHtml($homeVisit)->assertElementContains('#recently-viewed', 'You have not viewed any pages');
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/TestCase.php | tests/TestCase.php | <?php
namespace Tests;
use BookStack\Entities\Models\Entity;
use BookStack\Http\HttpClientHistory;
use BookStack\Http\HttpRequestService;
use BookStack\Settings\SettingService;
use Exception;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Env;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Testing\Assert as PHPUnit;
use Illuminate\Testing\Constraints\HasInDatabase;
use Monolog\Handler\TestHandler;
use Monolog\Logger;
use Ssddanbrown\AssertHtml\TestsHtml;
use Tests\Helpers\EntityProvider;
use Tests\Helpers\FileProvider;
use Tests\Helpers\PermissionsProvider;
use Tests\Helpers\TestServiceProvider;
use Tests\Helpers\UserRoleProvider;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
use DatabaseTransactions;
use TestsHtml;
protected EntityProvider $entities;
protected UserRoleProvider $users;
protected PermissionsProvider $permissions;
protected FileProvider $files;
protected function setUp(): void
{
$this->entities = new EntityProvider();
$this->users = new UserRoleProvider();
$this->permissions = new PermissionsProvider($this->users);
$this->files = new FileProvider();
parent::setUp();
// We can uncomment the below to run tests with failings upon deprecations.
// Can't leave on since some deprecations can only be fixed upstream.
// $this->withoutDeprecationHandling();
}
/**
* The base URL to use while testing the application.
*/
protected string $baseUrl = 'http://localhost';
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
/** @var \Illuminate\Foundation\Application $app */
$app = require __DIR__ . '/../bootstrap/app.php';
$app->register(TestServiceProvider::class);
$app->make(Kernel::class)->bootstrap();
return $app;
}
/**
* Set the current user context to be an admin.
*/
public function asAdmin()
{
return $this->actingAs($this->users->admin());
}
/**
* Set the current user context to be an editor.
*/
public function asEditor()
{
return $this->actingAs($this->users->editor());
}
/**
* Set the current user context to be a viewer.
*/
public function asViewer()
{
return $this->actingAs($this->users->viewer());
}
/**
* Quickly sets an array of settings.
*/
protected function setSettings(array $settingsArray): void
{
$settings = app(SettingService::class);
foreach ($settingsArray as $key => $value) {
$settings->put($key, $value);
}
}
/**
* Mock the http client used in BookStack http calls.
*/
protected function mockHttpClient(array $responses = []): HttpClientHistory
{
return $this->app->make(HttpRequestService::class)->mockClient($responses);
}
/**
* Run a set test with the given env variable.
* Remembers the original and resets the value after test.
* Database config is juggled so the value can be restored when
* parallel testing are used, where multiple databases exist.
*/
protected function runWithEnv(array $valuesByKey, callable $callback, bool $handleDatabase = true): void
{
Env::disablePutenv();
$originals = [];
foreach ($valuesByKey as $key => $value) {
$originals[$key] = $_SERVER[$key] ?? null;
if (is_null($value)) {
unset($_SERVER[$key]);
} else {
$_SERVER[$key] = $value;
}
}
$database = config('database.connections.mysql_testing.database');
$this->refreshApplication();
if ($handleDatabase) {
DB::purge();
config()->set('database.connections.mysql_testing.database', $database);
DB::beginTransaction();
}
$callback();
if ($handleDatabase) {
DB::rollBack();
}
foreach ($originals as $key => $value) {
if (is_null($value)) {
unset($_SERVER[$key]);
} else {
$_SERVER[$key] = $value;
}
}
}
/**
* Check the keys and properties in the given map to include
* exist, albeit not exclusively, within the map to check.
*/
protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
{
$passed = true;
foreach ($mapToInclude as $key => $value) {
if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
$passed = false;
}
}
$toIncludeStr = print_r($mapToInclude, true);
$toCheckStr = print_r($mapToCheck, true);
self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
}
/**
* Assert a permission error has occurred.
*/
protected function assertPermissionError($response)
{
PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
}
/**
* Assert a permission error has occurred.
*/
protected function assertNotPermissionError($response)
{
PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
}
/**
* Check if the given response is a permission error.
*/
private function isPermissionError($response): bool
{
if ($response->status() === 403 && $response instanceof JsonResponse) {
$errMessage = $response->getData(true)['error']['message'] ?? '';
return str_contains($errMessage, 'do not have permission');
}
return $response->status() === 302
&& $response->headers->get('Location') === url('/')
&& str_starts_with(session()->pull('error', ''), 'You do not have permission to access');
}
/**
* Assert that the session has a particular error notification message set.
*/
protected function assertSessionError(string $message)
{
$error = session()->get('error');
PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
}
/**
* Assert the session contains a specific entry.
*/
protected function assertSessionHas(string $key): self
{
$this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");
return $this;
}
protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
{
return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
}
/**
* Set a test handler as the logging interface for the application.
* Allows capture of logs for checking against during tests.
*/
protected function withTestLogger(): TestHandler
{
$monolog = new Logger('testing');
$testHandler = new TestHandler();
$monolog->pushHandler($testHandler);
Log::extend('testing', function () use ($monolog) {
return $monolog;
});
Log::setDefaultDriver('testing');
return $testHandler;
}
/**
* Assert that an activity entry exists of the given key.
* Checks the activity belongs to the given entity if provided.
*/
protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
{
$detailsToCheck = ['type' => $type];
if ($entity) {
$detailsToCheck['loggable_type'] = $entity->getMorphClass();
$detailsToCheck['loggable_id'] = $entity->id;
}
if ($detail) {
$detailsToCheck['detail'] = $detail;
}
$this->assertDatabaseHas('activities', $detailsToCheck);
}
/**
* Assert the database has the given data for an entity type.
*/
protected function assertDatabaseHasEntityData(string $type, array $data = []): self
{
$entityFields = array_intersect_key($data, array_flip(Entity::$commonFields));
$extraFields = array_diff_key($data, $entityFields);
$extraTable = $type === 'page' ? 'entity_page_data' : 'entity_container_data';
$entityFields['type'] = $type;
$this->assertThat(
$this->getTable('entities'),
new HasInDatabase($this->getConnection(null, 'entities'), $entityFields)
);
if (!empty($extraFields)) {
$id = $entityFields['id'] ?? DB::table($this->getTable('entities'))
->where($entityFields)->orderByDesc('id')->first()->id ?? null;
if (is_null($id)) {
throw new Exception('Failed to find entity id for asserting database data');
}
if ($type !== 'page') {
$extraFields['entity_id'] = $id;
$extraFields['entity_type'] = $type;
} else {
$extraFields['page_id'] = $id;
}
$this->assertThat(
$this->getTable($extraTable),
new HasInDatabase($this->getConnection(null, $extraTable), $extraFields)
);
}
return $this;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/CreatesApplication.php | tests/CreatesApplication.php | <?php
namespace Tests;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Application;
trait CreatesApplication
{
/**
* Creates the application.
*/
public function createApplication(): Application
{
$app = require __DIR__ . '/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
return $app;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/FavouriteTest.php | tests/FavouriteTest.php | <?php
namespace Tests;
use BookStack\Activity\Models\Favourite;
use BookStack\Users\Models\User;
class FavouriteTest extends TestCase
{
public function test_page_add_favourite_flow()
{
$page = $this->entities->page();
$editor = $this->users->editor();
$resp = $this->actingAs($editor)->get($page->getUrl());
$this->withHtml($resp)->assertElementContains('button', 'Favourite');
$this->withHtml($resp)->assertElementExists('form[method="POST"][action$="/favourites/add"] input[name="type"][value="page"]');
$resp = $this->post('/favourites/add', [
'type' => $page->getMorphClass(),
'id' => $page->id,
]);
$resp->assertRedirect($page->getUrl());
$resp->assertSessionHas('success', "\"{$page->name}\" has been added to your favourites");
$this->assertDatabaseHas('favourites', [
'user_id' => $editor->id,
'favouritable_type' => $page->getMorphClass(),
'favouritable_id' => $page->id,
]);
}
public function test_page_remove_favourite_flow()
{
$page = $this->entities->page();
$editor = $this->users->editor();
Favourite::query()->forceCreate([
'user_id' => $editor->id,
'favouritable_id' => $page->id,
'favouritable_type' => $page->getMorphClass(),
]);
$resp = $this->actingAs($editor)->get($page->getUrl());
$this->withHtml($resp)->assertElementContains('button', 'Unfavourite');
$this->withHtml($resp)->assertElementExists('form[method="POST"][action$="/favourites/remove"]');
$resp = $this->post('/favourites/remove', [
'type' => $page->getMorphClass(),
'id' => $page->id,
]);
$resp->assertRedirect($page->getUrl());
$resp->assertSessionHas('success', "\"{$page->name}\" has been removed from your favourites");
$this->assertDatabaseMissing('favourites', [
'user_id' => $editor->id,
]);
}
public function test_add_and_remove_redirect_to_entity_without_history()
{
$page = $this->entities->page();
$resp = $this->asEditor()->post('/favourites/add', [
'type' => $page->getMorphClass(),
'id' => $page->id,
]);
$resp->assertRedirect($page->getUrl());
$resp = $this->asEditor()->post('/favourites/remove', [
'type' => $page->getMorphClass(),
'id' => $page->id,
]);
$resp->assertRedirect($page->getUrl());
}
public function test_favourite_flow_with_own_permissions()
{
$book = $this->entities->book();
$user = User::factory()->create();
$book->owned_by = $user->id;
$book->save();
$this->permissions->grantUserRolePermissions($user, ['book-view-own']);
$this->actingAs($user)->get($book->getUrl());
$resp = $this->post('/favourites/add', [
'type' => $book->getMorphClass(),
'id' => $book->id,
]);
$resp->assertRedirect($book->getUrl());
$this->assertDatabaseHas('favourites', [
'user_id' => $user->id,
'favouritable_type' => $book->getMorphClass(),
'favouritable_id' => $book->id,
]);
}
public function test_each_entity_type_shows_favourite_button()
{
$this->actingAs($this->users->editor());
foreach ($this->entities->all() as $entity) {
$resp = $this->get($entity->getUrl());
$this->withHtml($resp)->assertElementExists('form[method="POST"][action$="/favourites/add"]');
}
}
public function test_header_contains_link_to_favourites_page_when_logged_in()
{
$this->setSettings(['app-public' => 'true']);
$resp = $this->get('/');
$this->withHtml($resp)->assertElementNotContains('header', 'My Favourites');
$resp = $this->actingAs($this->users->viewer())->get('/');
$this->withHtml($resp)->assertElementContains('header a', 'My Favourites');
}
public function test_favourites_shown_on_homepage()
{
$editor = $this->users->editor();
$resp = $this->actingAs($editor)->get('/');
$this->withHtml($resp)->assertElementNotExists('#top-favourites');
$page = $this->entities->page();
$page->favourites()->save((new Favourite())->forceFill(['user_id' => $editor->id]));
$resp = $this->get('/');
$this->withHtml($resp)->assertElementExists('#top-favourites');
$this->withHtml($resp)->assertElementContains('#top-favourites', $page->name);
}
public function test_favourites_list_page_shows_favourites_and_has_working_pagination()
{
$page = $this->entities->page();
$editor = $this->users->editor();
$resp = $this->actingAs($editor)->get('/favourites');
$resp->assertDontSee($page->name);
$page->favourites()->save((new Favourite())->forceFill(['user_id' => $editor->id]));
$resp = $this->get('/favourites');
$resp->assertSee($page->name);
$resp = $this->get('/favourites?page=2');
$resp->assertDontSee($page->name);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/StatusTest.php | tests/StatusTest.php | <?php
namespace Tests;
use Exception;
use Illuminate\Cache\ArrayStore;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Mockery;
class StatusTest extends TestCase
{
public function test_returns_json_with_expected_results()
{
$resp = $this->get('/status');
$resp->assertStatus(200);
$resp->assertJson([
'database' => true,
'cache' => true,
'session' => true,
]);
}
public function test_returns_500_status_and_false_on_db_error()
{
DB::shouldReceive('table')->andThrow(new Exception());
$resp = $this->get('/status');
$resp->assertStatus(500);
$resp->assertJson([
'database' => false,
]);
}
public function test_returns_500_status_and_false_on_wrong_cache_return()
{
$mockStore = Mockery::mock(new ArrayStore())->makePartial();
Cache::swap($mockStore);
$mockStore->shouldReceive('pull')->andReturn('cat');
$resp = $this->get('/status');
$resp->assertStatus(500);
$resp->assertJson([
'cache' => false,
]);
}
public function test_returns_500_status_and_false_on_wrong_session_return()
{
$session = Session::getFacadeRoot();
$mockSession = Mockery::mock($session)->makePartial();
Session::swap($mockSession);
$mockSession->shouldReceive('get')->andReturn('cat');
$resp = $this->get('/status');
$resp->assertStatus(500);
$resp->assertJson([
'session' => false,
]);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/UrlTest.php | tests/UrlTest.php | <?php
namespace Tests;
use BookStack\Http\Request;
class UrlTest extends TestCase
{
public function test_url_helper_takes_custom_url_into_account()
{
$this->runWithEnv(['APP_URL' => 'http://example.com/bookstack'], function () {
$this->assertEquals('http://example.com/bookstack/books', url('/books'));
});
}
public function test_url_helper_sets_correct_scheme_even_when_request_scheme_is_different()
{
$this->runWithEnv(['APP_URL' => 'https://example.com/'], function () {
$this->get('http://example.com/login')->assertSee('https://example.com/dist/styles.css');
});
}
public function test_app_url_forces_overrides_on_base_request()
{
config()->set('app.url', 'https://donkey.example.com:8091/cool/docs');
// Have to manually get and wrap request in our custom type due to testing mechanics
$this->get('/login');
$bsRequest = Request::createFrom(request());
$this->assertEquals('https://donkey.example.com:8091', $bsRequest->getSchemeAndHttpHost());
$this->assertEquals('/cool/docs', $bsRequest->getBaseUrl());
$this->assertEquals('https://donkey.example.com:8091/cool/docs/login', $bsRequest->getUri());
}
public function test_app_url_without_path_does_not_duplicate_path_slash()
{
config()->set('app.url', 'https://donkey.example.com');
// Have to manually get and wrap request in our custom type due to testing mechanics
$this->get('/settings');
$bsRequest = Request::createFrom(request());
$this->assertEquals('https://donkey.example.com', $bsRequest->getSchemeAndHttpHost());
$this->assertEquals('', $bsRequest->getBaseUrl());
$this->assertEquals('/settings', $bsRequest->getPathInfo());
$this->assertEquals('https://donkey.example.com/settings', $bsRequest->getUri());
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/ThemeTest.php | tests/ThemeTest.php | <?php
namespace Tests;
use BookStack\Activity\ActivityType;
use BookStack\Activity\DispatchWebhookJob;
use BookStack\Activity\Models\Webhook;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Tools\PageContent;
use BookStack\Exceptions\ThemeException;
use BookStack\Facades\Theme;
use BookStack\Theming\ThemeEvents;
use BookStack\Users\Models\User;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use League\CommonMark\Environment\Environment;
class ThemeTest extends TestCase
{
protected string $themeFolderName;
protected string $themeFolderPath;
public function test_translation_text_can_be_overridden_via_theme()
{
$this->usingThemeFolder(function () {
$translationPath = theme_path('/lang/en');
File::makeDirectory($translationPath, 0777, true);
$customTranslations = '<?php
return [\'books\' => \'Sandwiches\'];
';
file_put_contents($translationPath . '/entities.php', $customTranslations);
$homeRequest = $this->actingAs($this->users->viewer())->get('/');
$this->withHtml($homeRequest)->assertElementContains('header nav', 'Sandwiches');
});
}
public function test_theme_functions_file_used_and_app_boot_event_runs()
{
$this->usingThemeFolder(function ($themeFolder) {
$functionsFile = theme_path('functions.php');
app()->alias('cat', 'dog');
file_put_contents($functionsFile, "<?php\nTheme::listen(\BookStack\Theming\ThemeEvents::APP_BOOT, function(\$app) { \$app->alias('cat', 'dog');});");
$this->runWithEnv(['APP_THEME' => $themeFolder], function () {
$this->assertEquals('cat', $this->app->getAlias('dog'));
});
});
}
public function test_theme_functions_loads_errors_are_caught_and_logged()
{
$this->usingThemeFolder(function ($themeFolder) {
$functionsFile = theme_path('functions.php');
file_put_contents($functionsFile, "<?php\n\\BookStack\\Biscuits::eat();");
$this->expectException(ThemeException::class);
$this->expectExceptionMessageMatches('/Failed loading theme functions file at ".*?" with error: Class "BookStack\\\\Biscuits" not found/');
$this->runWithEnv(['APP_THEME' => $themeFolder], fn() => null);
});
}
public function test_event_commonmark_environment_configure()
{
$callbackCalled = false;
$callback = function ($environment) use (&$callbackCalled) {
$this->assertInstanceOf(Environment::class, $environment);
$callbackCalled = true;
return $environment;
};
Theme::listen(ThemeEvents::COMMONMARK_ENVIRONMENT_CONFIGURE, $callback);
$page = $this->entities->page();
$content = new PageContent($page);
$content->setNewMarkdown('# test', $this->users->editor());
$this->assertTrue($callbackCalled);
}
public function test_event_web_middleware_before()
{
$callbackCalled = false;
$requestParam = null;
$callback = function ($request) use (&$callbackCalled, &$requestParam) {
$requestParam = $request;
$callbackCalled = true;
};
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $callback);
$this->get('/login', ['Donkey' => 'cat']);
$this->assertTrue($callbackCalled);
$this->assertInstanceOf(Request::class, $requestParam);
$this->assertEquals('cat', $requestParam->header('donkey'));
}
public function test_event_web_middleware_before_return_val_used_as_response()
{
$callback = function (Request $request) {
return response('cat', 412);
};
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_BEFORE, $callback);
$resp = $this->get('/login', ['Donkey' => 'cat']);
$resp->assertSee('cat');
$resp->assertStatus(412);
}
public function test_event_web_middleware_after()
{
$callbackCalled = false;
$requestParam = null;
$responseParam = null;
$callback = function ($request, Response $response) use (&$callbackCalled, &$requestParam, &$responseParam) {
$requestParam = $request;
$responseParam = $response;
$callbackCalled = true;
$response->header('donkey', 'cat123');
};
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_AFTER, $callback);
$resp = $this->get('/login', ['Donkey' => 'cat']);
$this->assertTrue($callbackCalled);
$this->assertInstanceOf(Request::class, $requestParam);
$this->assertInstanceOf(Response::class, $responseParam);
$resp->assertHeader('donkey', 'cat123');
}
public function test_event_web_middleware_after_return_val_used_as_response()
{
$callback = function () {
return response('cat456', 443);
};
Theme::listen(ThemeEvents::WEB_MIDDLEWARE_AFTER, $callback);
$resp = $this->get('/login', ['Donkey' => 'cat']);
$resp->assertSee('cat456');
$resp->assertStatus(443);
}
public function test_event_auth_login_standard()
{
$args = [];
$callback = function (...$eventArgs) use (&$args) {
$args = $eventArgs;
};
Theme::listen(ThemeEvents::AUTH_LOGIN, $callback);
$this->post('/login', ['email' => 'admin@admin.com', 'password' => 'password']);
$this->assertCount(2, $args);
$this->assertEquals('standard', $args[0]);
$this->assertInstanceOf(User::class, $args[1]);
}
public function test_event_auth_register_standard()
{
$args = [];
$callback = function (...$eventArgs) use (&$args) {
$args = $eventArgs;
};
Theme::listen(ThemeEvents::AUTH_REGISTER, $callback);
$this->setSettings(['registration-enabled' => 'true']);
$user = User::factory()->make();
$this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']);
$this->assertCount(2, $args);
$this->assertEquals('standard', $args[0]);
$this->assertInstanceOf(User::class, $args[1]);
}
public function test_event_auth_pre_register()
{
$args = [];
$callback = function (...$eventArgs) use (&$args) {
$args = $eventArgs;
};
Theme::listen(ThemeEvents::AUTH_PRE_REGISTER, $callback);
$this->setSettings(['registration-enabled' => 'true']);
$user = User::factory()->make();
$this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']);
$this->assertCount(2, $args);
$this->assertEquals('standard', $args[0]);
$this->assertEquals([
'email' => $user->email,
'name' => $user->name,
'password' => 'password',
], $args[1]);
$this->assertDatabaseHas('users', ['email' => $user->email]);
}
public function test_event_auth_pre_register_with_false_return_blocks_registration()
{
$callback = function () {
return false;
};
Theme::listen(ThemeEvents::AUTH_PRE_REGISTER, $callback);
$this->setSettings(['registration-enabled' => 'true']);
$user = User::factory()->make();
$resp = $this->post('/register', ['email' => $user->email, 'name' => $user->name, 'password' => 'password']);
$resp->assertRedirect('/login');
$this->assertSessionError('User account could not be registered for the provided details');
$this->assertDatabaseMissing('users', ['email' => $user->email]);
}
public function test_event_webhook_call_before()
{
$args = [];
$callback = function (...$eventArgs) use (&$args) {
$args = $eventArgs;
return ['test' => 'hello!'];
};
Theme::listen(ThemeEvents::WEBHOOK_CALL_BEFORE, $callback);
$responses = $this->mockHttpClient([new \GuzzleHttp\Psr7\Response(200, [], '')]);
$webhook = new Webhook(['name' => 'Test webhook', 'endpoint' => 'https://example.com']);
$webhook->save();
$event = ActivityType::PAGE_UPDATE;
$detail = Page::query()->first();
dispatch((new DispatchWebhookJob($webhook, $event, $detail)));
$this->assertCount(5, $args);
$this->assertEquals($event, $args[0]);
$this->assertEquals($webhook->id, $args[1]->id);
$this->assertEquals($detail->id, $args[2]->id);
$this->assertEquals(1, $responses->requestCount());
$request = $responses->latestRequest();
$reqData = json_decode($request->getBody(), true);
$this->assertEquals('hello!', $reqData['test']);
}
public function test_event_activity_logged()
{
$book = $this->entities->book();
$args = [];
$callback = function (...$eventArgs) use (&$args) {
$args = $eventArgs;
};
Theme::listen(ThemeEvents::ACTIVITY_LOGGED, $callback);
$this->asEditor()->put($book->getUrl(), ['name' => 'My cool update book!']);
$this->assertCount(2, $args);
$this->assertEquals(ActivityType::BOOK_UPDATE, $args[0]);
$this->assertTrue($args[1] instanceof Book);
$this->assertEquals($book->id, $args[1]->id);
}
public function test_event_page_include_parse()
{
/** @var Page $page */
/** @var Page $otherPage */
$page = $this->entities->page();
$otherPage = Page::query()->where('id', '!=', $page->id)->first();
$otherPage->html = '<p id="bkmrk-cool">This is a really cool section</p>';
$page->html = "<p>{{@{$otherPage->id}#bkmrk-cool}}</p>";
$page->save();
$otherPage->save();
$args = [];
$callback = function (...$eventArgs) use (&$args) {
$args = $eventArgs;
return '<strong>Big & content replace surprise!</strong>';
};
Theme::listen(ThemeEvents::PAGE_INCLUDE_PARSE, $callback);
$resp = $this->asEditor()->get($page->getUrl());
$this->withHtml($resp)->assertElementContains('.page-content strong', 'Big & content replace surprise!');
$this->assertCount(4, $args);
$this->assertEquals($otherPage->id . '#bkmrk-cool', $args[0]);
$this->assertEquals('This is a really cool section', $args[1]);
$this->assertTrue($args[2] instanceof Page);
$this->assertTrue($args[3] instanceof Page);
$this->assertEquals($page->id, $args[2]->id);
$this->assertEquals($otherPage->id, $args[3]->id);
}
public function test_event_routes_register_web_and_web_auth()
{
$functionsContent = <<<'END'
<?php
use BookStack\Theming\ThemeEvents;
use BookStack\Facades\Theme;
use Illuminate\Routing\Router;
Theme::listen(ThemeEvents::ROUTES_REGISTER_WEB, function (Router $router) {
$router->get('/cat', fn () => 'cat')->name('say.cat');
});
Theme::listen(ThemeEvents::ROUTES_REGISTER_WEB_AUTH, function (Router $router) {
$router->get('/dog', fn () => 'dog')->name('say.dog');
});
END;
$this->usingThemeFolder(function () use ($functionsContent) {
$functionsFile = theme_path('functions.php');
file_put_contents($functionsFile, $functionsContent);
$app = $this->createApplication();
/** @var \Illuminate\Routing\Router $router */
$router = $app->get('router');
/** @var \Illuminate\Routing\Route $catRoute */
$catRoute = $router->getRoutes()->getRoutesByName()['say.cat'];
$this->assertEquals(['web'], $catRoute->middleware());
/** @var \Illuminate\Routing\Route $dogRoute */
$dogRoute = $router->getRoutes()->getRoutesByName()['say.dog'];
$this->assertEquals(['web', 'auth'], $dogRoute->middleware());
});
}
public function test_add_social_driver()
{
Theme::addSocialDriver('catnet', [
'client_id' => 'abc123',
'client_secret' => 'def456',
], 'SocialiteProviders\Discord\DiscordExtendSocialite@handleTesting');
$this->assertEquals('catnet', config('services.catnet.name'));
$this->assertEquals('abc123', config('services.catnet.client_id'));
$this->assertEquals(url('/login/service/catnet/callback'), config('services.catnet.redirect'));
$loginResp = $this->get('/login');
$loginResp->assertSee('login/service/catnet');
}
public function test_add_social_driver_uses_name_in_config_if_given()
{
Theme::addSocialDriver('catnet', [
'client_id' => 'abc123',
'client_secret' => 'def456',
'name' => 'Super Cat Name',
], 'SocialiteProviders\Discord\DiscordExtendSocialite@handleTesting');
$this->assertEquals('Super Cat Name', config('services.catnet.name'));
$loginResp = $this->get('/login');
$loginResp->assertSee('Super Cat Name');
}
public function test_add_social_driver_allows_a_configure_for_redirect_callback_to_be_passed()
{
Theme::addSocialDriver(
'discord',
[
'client_id' => 'abc123',
'client_secret' => 'def456',
'name' => 'Super Cat Name',
],
'SocialiteProviders\Discord\DiscordExtendSocialite@handle',
function ($driver) {
$driver->with(['donkey' => 'donut']);
}
);
$loginResp = $this->get('/login/service/discord');
$redirect = $loginResp->headers->get('location');
$this->assertStringContainsString('donkey=donut', $redirect);
}
public function test_register_command_allows_provided_command_to_be_usable_via_artisan()
{
Theme::registerCommand(new MyCustomCommand());
Artisan::call('bookstack:test-custom-command', []);
$output = Artisan::output();
$this->assertStringContainsString('Command ran!', $output);
}
public function test_base_body_start_and_end_template_files_can_be_used()
{
$bodyStartStr = 'barry-fought-against-the-panther';
$bodyEndStr = 'barry-lost-his-fight-with-grace';
$this->usingThemeFolder(function (string $folder) use ($bodyStartStr, $bodyEndStr) {
$viewDir = theme_path('layouts/parts');
mkdir($viewDir, 0777, true);
file_put_contents($viewDir . '/base-body-start.blade.php', $bodyStartStr);
file_put_contents($viewDir . '/base-body-end.blade.php', $bodyEndStr);
$resp = $this->asEditor()->get('/');
$resp->assertSee($bodyStartStr);
$resp->assertSee($bodyEndStr);
});
}
public function test_export_body_start_and_end_template_files_can_be_used()
{
$bodyStartStr = 'garry-fought-against-the-panther';
$bodyEndStr = 'garry-lost-his-fight-with-grace';
$page = $this->entities->page();
$this->usingThemeFolder(function (string $folder) use ($bodyStartStr, $bodyEndStr, $page) {
$viewDir = theme_path('layouts/parts');
mkdir($viewDir, 0777, true);
file_put_contents($viewDir . '/export-body-start.blade.php', $bodyStartStr);
file_put_contents($viewDir . '/export-body-end.blade.php', $bodyEndStr);
$resp = $this->asEditor()->get($page->getUrl('/export/html'));
$resp->assertSee($bodyStartStr);
$resp->assertSee($bodyEndStr);
});
}
public function test_login_and_register_message_template_files_can_be_used()
{
$loginMessage = 'Welcome to this instance, login below you scallywag';
$registerMessage = 'You want to register? Enter the deets below you numpty';
$this->usingThemeFolder(function (string $folder) use ($loginMessage, $registerMessage) {
$viewDir = theme_path('auth/parts');
mkdir($viewDir, 0777, true);
file_put_contents($viewDir . '/login-message.blade.php', $loginMessage);
file_put_contents($viewDir . '/register-message.blade.php', $registerMessage);
$this->setSettings(['registration-enabled' => 'true']);
$this->get('/login')->assertSee($loginMessage);
$this->get('/register')->assertSee($registerMessage);
});
}
public function test_header_links_start_template_file_can_be_used()
{
$content = 'This is added text in the header bar';
$this->usingThemeFolder(function (string $folder) use ($content) {
$viewDir = theme_path('layouts/parts');
mkdir($viewDir, 0777, true);
file_put_contents($viewDir . '/header-links-start.blade.php', $content);
$this->setSettings(['registration-enabled' => 'true']);
$this->get('/login')->assertSee($content);
});
}
public function test_custom_settings_category_page_can_be_added_via_view_file()
{
$content = 'My SuperCustomSettings';
$this->usingThemeFolder(function (string $folder) use ($content) {
$viewDir = theme_path('settings/categories');
mkdir($viewDir, 0777, true);
file_put_contents($viewDir . '/beans.blade.php', $content);
$this->asAdmin()->get('/settings/beans')->assertSee($content);
});
}
public function test_public_folder_contents_accessible_via_route()
{
$this->usingThemeFolder(function (string $themeFolderName) {
$publicDir = theme_path('public');
mkdir($publicDir, 0777, true);
$text = 'some-text ' . md5(random_bytes(5));
$css = "body { background-color: tomato !important; }";
file_put_contents("{$publicDir}/file.txt", $text);
file_put_contents("{$publicDir}/file.css", $css);
copy($this->files->testFilePath('test-image.png'), "{$publicDir}/image.png");
$resp = $this->asAdmin()->get("/theme/{$themeFolderName}/file.txt");
$resp->assertStreamedContent($text);
$resp->assertHeader('Content-Type', 'text/plain; charset=utf-8');
$resp->assertHeader('Cache-Control', 'max-age=86400, private');
$resp = $this->asAdmin()->get("/theme/{$themeFolderName}/image.png");
$resp->assertHeader('Content-Type', 'image/png');
$resp->assertHeader('Cache-Control', 'max-age=86400, private');
$resp = $this->asAdmin()->get("/theme/{$themeFolderName}/file.css");
$resp->assertStreamedContent($css);
$resp->assertHeader('Content-Type', 'text/css; charset=utf-8');
$resp->assertHeader('Cache-Control', 'max-age=86400, private');
});
}
protected function usingThemeFolder(callable $callback)
{
// Create a folder and configure a theme
$themeFolderName = 'testing_theme_' . str_shuffle(rtrim(base64_encode(time()), '='));
config()->set('view.theme', $themeFolderName);
$themeFolderPath = theme_path('');
// Create theme folder and clean it up on application tear-down
File::makeDirectory($themeFolderPath);
$this->beforeApplicationDestroyed(fn() => File::deleteDirectory($themeFolderPath));
// Run provided callback with theme env option set
$this->runWithEnv(['APP_THEME' => $themeFolderName], function () use ($callback, $themeFolderName) {
call_user_func($callback, $themeFolderName);
});
}
}
class MyCustomCommand extends Command
{
protected $signature = 'bookstack:test-custom-command';
public function handle()
{
$this->line('Command ran!');
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/PublicActionTest.php | tests/PublicActionTest.php | <?php
namespace Tests;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Chapter;
use BookStack\Permissions\Models\RolePermission;
use BookStack\Users\Models\Role;
use BookStack\Users\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;
class PublicActionTest extends TestCase
{
public function test_app_not_public()
{
$this->setSettings(['app-public' => 'false']);
$book = $this->entities->book();
$this->get('/books')->assertRedirect('/login');
$this->get($book->getUrl())->assertRedirect('/login');
$page = $this->entities->page();
$this->get($page->getUrl())->assertRedirect('/login');
}
public function test_login_link_visible()
{
$this->setSettings(['app-public' => 'true']);
$resp = $this->get('/');
$this->withHtml($resp)->assertElementExists('a[href="' . url('/login') . '"]');
}
public function test_register_link_visible_when_enabled()
{
$this->setSettings(['app-public' => 'true']);
$home = $this->get('/');
$home->assertSee(url('/login'));
$home->assertDontSee(url('/register'));
$this->setSettings(['app-public' => 'true', 'registration-enabled' => 'true']);
$home = $this->get('/');
$home->assertSee(url('/login'));
$home->assertSee(url('/register'));
}
public function test_books_viewable()
{
$this->setSettings(['app-public' => 'true']);
$books = Book::query()->orderBy('name', 'asc')->take(10)->get();
$bookToVisit = $books[1];
// Check books index page is showing
$resp = $this->get('/books');
$resp->assertStatus(200);
$resp->assertSee($books[0]->name);
// Check individual book page is showing and it's child contents are visible.
$resp = $this->get($bookToVisit->getUrl());
$resp->assertSee($bookToVisit->name);
$resp->assertSee($bookToVisit->chapters()->first()->name);
}
public function test_chapters_viewable()
{
$this->setSettings(['app-public' => 'true']);
/** @var Chapter $chapterToVisit */
$chapterToVisit = Chapter::query()->first();
$pageToVisit = $chapterToVisit->pages()->first();
// Check chapters index page is showing
$resp = $this->get($chapterToVisit->getUrl());
$resp->assertStatus(200);
$resp->assertSee($chapterToVisit->name);
// Check individual chapter page is showing and it's child contents are visible.
$resp->assertSee($pageToVisit->name);
$resp = $this->get($pageToVisit->getUrl());
$resp->assertStatus(200);
$resp->assertSee($chapterToVisit->book->name);
$resp->assertSee($chapterToVisit->name);
}
public function test_public_page_creation()
{
$this->setSettings(['app-public' => 'true']);
$publicRole = Role::getSystemRole('public');
// Grant all permissions to public
$publicRole->permissions()->detach();
foreach (RolePermission::all() as $perm) {
$publicRole->attachPermission($perm);
}
user()->clearPermissionCache();
$chapter = $this->entities->chapter();
$resp = $this->get($chapter->getUrl());
$resp->assertSee('New Page');
$this->withHtml($resp)->assertElementExists('a[href="' . $chapter->getUrl('/create-page') . '"]');
$resp = $this->get($chapter->getUrl('/create-page'));
$resp->assertSee('Continue');
$resp->assertSee('Page Name');
$this->withHtml($resp)->assertElementExists('form[action="' . $chapter->getUrl('/create-guest-page') . '"]');
$resp = $this->post($chapter->getUrl('/create-guest-page'), ['name' => 'My guest page']);
$resp->assertRedirect($chapter->book->getUrl('/page/my-guest-page/edit'));
$user = $this->users->guest();
$this->assertDatabaseHasEntityData('page', [
'name' => 'My guest page',
'chapter_id' => $chapter->id,
'created_by' => $user->id,
'updated_by' => $user->id,
]);
}
public function test_content_not_listed_on_404_for_public_users()
{
$page = $this->entities->page();
$page->fill(['name' => 'my testing random unique page name'])->save();
$this->asAdmin()->get($page->getUrl()); // Fake visit to show on recents
$resp = $this->get('/cats/dogs/hippos');
$resp->assertStatus(404);
$resp->assertSee($page->name);
View::share('pageTitle', '');
Auth::logout();
$resp = $this->get('/cats/dogs/hippos');
$resp->assertStatus(404);
$resp->assertDontSee($page->name);
}
public function test_default_favicon_file_created_upon_access()
{
$faviconPath = public_path('favicon.ico');
if (file_exists($faviconPath)) {
unlink($faviconPath);
}
$this->assertFileDoesNotExist($faviconPath);
$this->get('/favicon.ico');
$this->assertFileExists($faviconPath);
}
public function test_public_view_then_login_redirects_to_previous_content()
{
$this->setSettings(['app-public' => 'true']);
$book = $this->entities->book();
$resp = $this->get($book->getUrl());
$resp->assertSee($book->name);
$this->get('/login');
$resp = $this->post('/login', ['email' => 'admin@admin.com', 'password' => 'password']);
$resp->assertRedirect($book->getUrl());
}
public function test_access_hidden_content_then_login_redirects_to_intended_content()
{
$this->setSettings(['app-public' => 'true']);
$book = $this->entities->book();
$this->permissions->setEntityPermissions($book);
$resp = $this->get($book->getUrl());
$resp->assertSee('Book not found');
$this->get('/login');
$resp = $this->post('/login', ['email' => 'admin@admin.com', 'password' => 'password']);
$resp->assertRedirect($book->getUrl());
$this->followRedirects($resp)->assertSee($book->name);
}
public function test_public_view_can_take_on_other_roles()
{
$this->setSettings(['app-public' => 'true']);
$newRole = $this->users->attachNewRole($this->users->guest(), []);
$page = $this->entities->page();
$this->permissions->disableEntityInheritedPermissions($page);
$this->permissions->addEntityPermission($page, ['view', 'update'], $newRole);
$resp = $this->get($page->getUrl());
$resp->assertOk();
$this->withHtml($resp)->assertLinkExists($page->getUrl('/edit'));
}
public function test_public_user_cannot_view_or_update_their_profile()
{
$this->setSettings(['app-public' => 'true']);
$guest = $this->users->guest();
$resp = $this->get($guest->getEditUrl());
$this->assertPermissionError($resp);
$resp = $this->put($guest->getEditUrl(), ['name' => 'My new guest name']);
$this->assertPermissionError($resp);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/SecurityHeaderTest.php | tests/SecurityHeaderTest.php | <?php
namespace Tests;
use BookStack\Util\CspService;
use Illuminate\Testing\TestResponse;
class SecurityHeaderTest extends TestCase
{
public function test_cookies_samesite_lax_by_default()
{
$resp = $this->get('/');
foreach ($resp->headers->getCookies() as $cookie) {
$this->assertEquals('lax', $cookie->getSameSite());
}
}
public function test_cookies_samesite_none_when_iframe_hosts_set()
{
$this->runWithEnv(['ALLOWED_IFRAME_HOSTS' => 'http://example.com'], function () {
$resp = $this->get('/');
foreach ($resp->headers->getCookies() as $cookie) {
$this->assertEquals('none', $cookie->getSameSite());
}
});
}
public function test_secure_cookies_controlled_by_app_url()
{
$this->runWithEnv(['APP_URL' => 'http://example.com'], function () {
$resp = $this->get('/');
foreach ($resp->headers->getCookies() as $cookie) {
$this->assertFalse($cookie->isSecure());
}
});
$this->runWithEnv(['APP_URL' => 'https://example.com'], function () {
$resp = $this->get('/');
foreach ($resp->headers->getCookies() as $cookie) {
$this->assertTrue($cookie->isSecure());
}
});
}
public function test_iframe_csp_self_only_by_default()
{
$resp = $this->get('/');
$frameHeader = $this->getCspHeader($resp, 'frame-ancestors');
$this->assertEquals('frame-ancestors \'self\'', $frameHeader);
}
public function test_iframe_csp_includes_extra_hosts_if_configured()
{
$this->runWithEnv(['ALLOWED_IFRAME_HOSTS' => 'https://a.example.com https://b.example.com'], function () {
$resp = $this->get('/');
$frameHeader = $this->getCspHeader($resp, 'frame-ancestors');
$this->assertNotEmpty($frameHeader);
$this->assertEquals('frame-ancestors \'self\' https://a.example.com https://b.example.com', $frameHeader);
});
}
public function test_script_csp_set_on_responses()
{
$resp = $this->get('/');
$scriptHeader = $this->getCspHeader($resp, 'script-src');
$this->assertStringContainsString('\'strict-dynamic\'', $scriptHeader);
$this->assertStringContainsString('\'nonce-', $scriptHeader);
}
public function test_script_csp_nonce_matches_nonce_used_in_custom_head()
{
$this->setSettings(['app-custom-head' => '<script>console.log("cat");</script>']);
$resp = $this->get('/login');
$scriptHeader = $this->getCspHeader($resp, 'script-src');
$nonce = app()->make(CspService::class)->getNonce();
$this->assertStringContainsString('nonce-' . $nonce, $scriptHeader);
$resp->assertSee('<script nonce="' . $nonce . '">console.log("cat");</script>', false);
}
public function test_script_csp_nonce_changes_per_request()
{
$resp = $this->get('/');
$firstHeader = $this->getCspHeader($resp, 'script-src');
$this->refreshApplication();
$resp = $this->get('/');
$secondHeader = $this->getCspHeader($resp, 'script-src');
$this->assertNotEquals($firstHeader, $secondHeader);
}
public function test_allow_content_scripts_settings_controls_csp_script_headers()
{
config()->set('app.allow_content_scripts', true);
$resp = $this->get('/');
$scriptHeader = $this->getCspHeader($resp, 'script-src');
$this->assertEmpty($scriptHeader);
config()->set('app.allow_content_scripts', false);
$resp = $this->get('/');
$scriptHeader = $this->getCspHeader($resp, 'script-src');
$this->assertNotEmpty($scriptHeader);
}
public function test_object_src_csp_header_set()
{
$resp = $this->get('/');
$scriptHeader = $this->getCspHeader($resp, 'object-src');
$this->assertEquals('object-src \'self\'', $scriptHeader);
}
public function test_base_uri_csp_header_set()
{
$resp = $this->get('/');
$scriptHeader = $this->getCspHeader($resp, 'base-uri');
$this->assertEquals('base-uri \'self\'', $scriptHeader);
}
public function test_frame_src_csp_header_set()
{
$resp = $this->get('/');
$scriptHeader = $this->getCspHeader($resp, 'frame-src');
$this->assertEquals('frame-src \'self\' https://*.draw.io https://*.youtube.com https://*.youtube-nocookie.com https://*.vimeo.com', $scriptHeader);
}
public function test_frame_src_csp_header_has_drawio_host_added()
{
config()->set([
'app.iframe_sources' => 'https://example.com',
'services.drawio' => 'https://diagrams.example.com/testing?cat=dog',
]);
$resp = $this->get('/');
$scriptHeader = $this->getCspHeader($resp, 'frame-src');
$this->assertEquals('frame-src \'self\' https://example.com https://diagrams.example.com', $scriptHeader);
}
public function test_frame_src_csp_header_drawio_host_includes_port_if_existing()
{
config()->set([
'app.iframe_sources' => 'https://example.com',
'services.drawio' => 'https://diagrams.example.com:8080/testing?cat=dog',
]);
$resp = $this->get('/');
$scriptHeader = $this->getCspHeader($resp, 'frame-src');
$this->assertEquals('frame-src \'self\' https://example.com https://diagrams.example.com:8080', $scriptHeader);
}
public function test_cache_control_headers_are_set_on_responses()
{
// Public access
$resp = $this->get('/');
$resp->assertHeader('Cache-Control', 'no-cache, no-store, private');
$resp->assertHeader('Expires', 'Sun, 12 Jul 2015 19:01:00 GMT');
// Authed access
$this->asEditor();
$resp = $this->get('/');
$resp->assertHeader('Cache-Control', 'no-cache, no-store, private');
$resp->assertHeader('Expires', 'Sun, 12 Jul 2015 19:01:00 GMT');
}
/**
* Get the value of the first CSP header of the given type.
*/
protected function getCspHeader(TestResponse $resp, string $type): string
{
$cspHeaders = explode('; ', $resp->headers->get('Content-Security-Policy'));
foreach ($cspHeaders as $cspHeader) {
if (strpos($cspHeader, $type) === 0) {
return $cspHeader;
}
}
return '';
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Meta/RobotsTest.php | tests/Meta/RobotsTest.php | <?php
namespace Tests\Meta;
use Tests\TestCase;
class RobotsTest extends TestCase
{
public function test_robots_effected_by_public_status()
{
$this->get('/robots.txt')->assertSee("User-agent: *\nDisallow: /");
$this->setSettings(['app-public' => 'true']);
$resp = $this->get('/robots.txt');
$resp->assertSee("User-agent: *\nDisallow:");
$resp->assertDontSee('Disallow: /');
}
public function test_robots_effected_by_setting()
{
$this->get('/robots.txt')->assertSee("User-agent: *\nDisallow: /");
config()->set('app.allow_robots', true);
$resp = $this->get('/robots.txt');
$resp->assertSee("User-agent: *\nDisallow:");
$resp->assertDontSee('Disallow: /');
// Check config overrides app-public setting
config()->set('app.allow_robots', false);
$this->setSettings(['app-public' => 'true']);
$this->get('/robots.txt')->assertSee("User-agent: *\nDisallow: /");
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Meta/OpensearchTest.php | tests/Meta/OpensearchTest.php | <?php
namespace Tests\Meta;
use Tests\TestCase;
class OpensearchTest extends TestCase
{
public function test_opensearch_endpoint()
{
$appName = 'MyAppNameThatsReallyLongLikeThis';
setting()->put('app-name', $appName);
$resultUrl = url('/search') . '?term={searchTerms}';
$selfUrl = url('/opensearch.xml');
$resp = $this->get('/opensearch.xml');
$resp->assertOk();
$resp->assertSee('<?xml version="1.0" encoding="UTF-8"?>' . "\n", false);
$html = $this->withHtml($resp);
$html->assertElementExists('OpenSearchDescription > ShortName');
$html->assertElementContains('OpenSearchDescription > ShortName', mb_strimwidth($appName, 0, 16));
$html->assertElementNotContains('OpenSearchDescription > ShortName', $appName);
$html->assertElementExists('OpenSearchDescription > Description');
$html->assertElementContains('OpenSearchDescription > Description', "Search {$appName}");
$html->assertElementExists('OpenSearchDescription > Image');
$html->assertElementExists('OpenSearchDescription > Url[rel="results"][template="' . htmlspecialchars($resultUrl) . '"]');
$html->assertElementExists('OpenSearchDescription > Url[rel="self"][template="' . htmlspecialchars($selfUrl) . '"]');
}
public function test_opensearch_linked_to_from_home()
{
$appName = setting('app-name');
$endpointUrl = url('/opensearch.xml');
$resp = $this->asViewer()->get('/');
$html = $this->withHtml($resp);
$html->assertElementExists('head > link[rel="search"][type="application/opensearchdescription+xml"][title="' . htmlspecialchars($appName) . '"][href="' . htmlspecialchars($endpointUrl) . '"]');
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Meta/PwaManifestTest.php | tests/Meta/PwaManifestTest.php | <?php
namespace Tests\Meta;
use Tests\TestCase;
class PwaManifestTest extends TestCase
{
public function test_manifest_access_and_format()
{
$this->setSettings(['app-color' => '#00ACED']);
$resp = $this->get('/manifest.json');
$resp->assertOk();
$resp->assertJson([
'name' => setting('app-name'),
'launch_handler' => [
'client_mode' => 'focus-existing'
],
'theme_color' => '#00ACED',
]);
}
public function test_pwa_meta_tags_in_head()
{
$html = $this->asViewer()->withHtml($this->get('/'));
$html->assertElementExists('head link[rel="manifest"][href$="manifest.json"]');
$html->assertElementExists('head meta[name="mobile-web-app-capable"][content="yes"]');
}
public function test_manifest_uses_configured_icons_if_existing()
{
$this->beforeApplicationDestroyed(fn() => $this->files->resetAppFavicon());
$resp = $this->get('/manifest.json');
$resp->assertJson([
'icons' => [[
"src" => 'http://localhost/icon-32.png',
"sizes" => "32x32",
"type" => "image/png"
]]
]);
$galleryFile = $this->files->uploadedImage('my-app-icon.png');
$this->asAdmin()->call('POST', '/settings/customization', [], [], ['app_icon' => $galleryFile], []);
$customIconUrl = setting()->get('app-icon-32');
$this->assertStringContainsString('my-app-icon', $customIconUrl);
$resp = $this->get('/manifest.json');
$resp->assertJson([
'icons' => [[
"src" => $customIconUrl,
"sizes" => "32x32",
"type" => "image/png"
]]
]);
}
public function test_manifest_changes_to_user_preferences()
{
$lightUser = $this->users->viewer();
$darkUser = $this->users->editor();
setting()->putUser($darkUser, 'dark-mode-enabled', 'true');
$resp = $this->actingAs($lightUser)->get('/manifest.json');
$resp->assertJson(['background_color' => '#F2F2F2']);
$resp = $this->actingAs($darkUser)->get('/manifest.json');
$resp->assertJson(['background_color' => '#111111']);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Meta/HelpTest.php | tests/Meta/HelpTest.php | <?php
namespace Tests\Meta;
use Tests\TestCase;
class HelpTest extends TestCase
{
public function test_tinymce_help_shows_tiny_and_tiny_license_link()
{
$resp = $this->get('/help/tinymce');
$resp->assertOk();
$this->withHtml($resp)->assertElementExists('a[href="https://www.tiny.cloud/"]');
$this->withHtml($resp)->assertElementExists('a[href="' . url('/libs/tinymce/license.txt') . '"]');
}
public function test_tiny_license_exists_where_expected()
{
$expectedPath = public_path('/libs/tinymce/license.txt');
$this->assertTrue(file_exists($expectedPath));
$contents = file_get_contents($expectedPath);
$this->assertStringContainsString('MIT License', $contents);
}
public function test_wysiwyg_help_shows_lexical_and_licenses_link()
{
$resp = $this->get('/help/wysiwyg');
$resp->assertOk();
$this->withHtml($resp)->assertElementExists('a[href="https://lexical.dev/"]');
$this->withHtml($resp)->assertElementExists('a[href="' . url('/licenses') . '"]');
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Meta/OpenGraphTest.php | tests/Meta/OpenGraphTest.php | <?php
namespace Tests\Meta;
use BookStack\Entities\Repos\BaseRepo;
use BookStack\Entities\Repos\BookRepo;
use Illuminate\Support\Str;
use Illuminate\Testing\TestResponse;
use Tests\TestCase;
class OpenGraphTest extends TestCase
{
public function test_page_tags()
{
$page = $this->entities->page();
$resp = $this->asEditor()->get($page->getUrl());
$tags = $this->getOpenGraphTags($resp);
$this->assertEquals($page->getShortName() . ' | BookStack', $tags['title']);
$this->assertEquals($page->getUrl(), $tags['url']);
$this->assertEquals(Str::limit($page->text, 100, '...'), $tags['description']);
}
public function test_chapter_tags()
{
$chapter = $this->entities->chapter();
$resp = $this->asEditor()->get($chapter->getUrl());
$tags = $this->getOpenGraphTags($resp);
$this->assertEquals($chapter->getShortName() . ' | BookStack', $tags['title']);
$this->assertEquals($chapter->getUrl(), $tags['url']);
$this->assertEquals(Str::limit($chapter->description, 100, '...'), $tags['description']);
}
public function test_book_tags()
{
$book = $this->entities->book();
$resp = $this->asEditor()->get($book->getUrl());
$tags = $this->getOpenGraphTags($resp);
$this->assertEquals($book->getShortName() . ' | BookStack', $tags['title']);
$this->assertEquals($book->getUrl(), $tags['url']);
$this->assertEquals(Str::limit($book->description, 100, '...'), $tags['description']);
$this->assertArrayNotHasKey('image', $tags);
// Test image set if image has cover image
$bookRepo = app(BookRepo::class);
$bookRepo->updateCoverImage($book, $this->files->uploadedImage('image.png'));
$resp = $this->asEditor()->get($book->getUrl());
$tags = $this->getOpenGraphTags($resp);
$this->assertEquals($book->coverInfo()->getUrl(), $tags['image']);
}
public function test_shelf_tags()
{
$shelf = $this->entities->shelf();
$resp = $this->asEditor()->get($shelf->getUrl());
$tags = $this->getOpenGraphTags($resp);
$this->assertEquals($shelf->getShortName() . ' | BookStack', $tags['title']);
$this->assertEquals($shelf->getUrl(), $tags['url']);
$this->assertEquals(Str::limit($shelf->description, 100, '...'), $tags['description']);
$this->assertArrayNotHasKey('image', $tags);
// Test image set if image has cover image
$baseRepo = app(BaseRepo::class);
$baseRepo->updateCoverImage($shelf, $this->files->uploadedImage('image.png'));
$resp = $this->asEditor()->get($shelf->getUrl());
$tags = $this->getOpenGraphTags($resp);
$this->assertEquals($shelf->coverInfo()->getUrl(), $tags['image']);
}
/**
* Parse the open graph tags from a test response.
*/
protected function getOpenGraphTags(TestResponse $resp): array
{
$tags = [];
libxml_use_internal_errors(true);
$doc = new \DOMDocument();
$doc->loadHTML($resp->getContent());
$metaElems = $doc->getElementsByTagName('meta');
/** @var \DOMElement $elem */
foreach ($metaElems as $elem) {
$prop = $elem->getAttribute('property');
$name = explode(':', $prop)[1] ?? null;
if ($name) {
$tags[$name] = $elem->getAttribute('content');
}
}
return $tags;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Meta/LicensesTest.php | tests/Meta/LicensesTest.php | <?php
namespace Tests\Meta;
use Tests\TestCase;
class LicensesTest extends TestCase
{
public function test_licenses_endpoint()
{
$resp = $this->get('/licenses');
$resp->assertOk();
$resp->assertSee('Licenses');
$resp->assertSee('PHP Library Licenses');
$resp->assertSee('Dan Brown and the BookStack project contributors');
$resp->assertSee('league/commonmark');
$resp->assertSee('@codemirror/lang-html');
}
public function test_licenses_linked_to_from_settings()
{
$resp = $this->asAdmin()->get('/settings/features');
$html = $this->withHtml($resp);
$html->assertLinkExists(url('/licenses'), 'License Details');
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Helpers/EntityProvider.php | tests/Helpers/EntityProvider.php | <?php
namespace Tests\Helpers;
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\Repos\BookRepo;
use BookStack\Entities\Repos\BookshelfRepo;
use BookStack\Entities\Repos\ChapterRepo;
use BookStack\Entities\Repos\PageRepo;
use BookStack\Entities\Tools\TrashCan;
use BookStack\Users\Models\User;
use Illuminate\Database\Eloquent\Builder;
/**
* Class to provider and action entity models for common test case
* operations. Tracks handled models and only returns fresh models.
* Does not dedupe against nested/child/parent models.
*/
class EntityProvider
{
/**
* @var array<string, int[]>
*/
protected array $fetchCache = [
'book' => [],
'page' => [],
'bookshelf' => [],
'chapter' => [],
];
/**
* Get an unfetched page from the system.
*/
public function page(callable|null $queryFilter = null): Page
{
/** @var Page $page */
$page = Page::query()->when($queryFilter, $queryFilter)->whereNotIn('id', $this->fetchCache['page'])->first();
$this->addToCache($page);
return $page;
}
public function pageWithinChapter(): Page
{
return $this->page(fn(Builder $query) => $query->whereHas('chapter')->with('chapter'));
}
public function pageNotWithinChapter(): Page
{
return $this->page(fn(Builder $query) => $query->whereNull('chapter_id'));
}
public function templatePage(): Page
{
$page = $this->page();
$page->template = true;
$page->save();
return $page;
}
/**
* Get an unfetched chapter from the system.
*/
public function chapter(callable|null $queryFilter = null): Chapter
{
/** @var Chapter $chapter */
$chapter = Chapter::query()->when($queryFilter, $queryFilter)->whereNotIn('id', $this->fetchCache['chapter'])->first();
$this->addToCache($chapter);
return $chapter;
}
public function chapterHasPages(): Chapter
{
return $this->chapter(fn(Builder $query) => $query->whereHas('pages'));
}
/**
* Get an unfetched book from the system.
*/
public function book(callable|null $queryFilter = null): Book
{
/** @var Book $book */
$book = Book::query()->when($queryFilter, $queryFilter)->whereNotIn('id', $this->fetchCache['book'])->first();
$this->addToCache($book);
return $book;
}
/**
* Get a book that has chapters and pages assigned.
*/
public function bookHasChaptersAndPages(): Book
{
return $this->book(function (Builder $query) {
$query->has('chapters')->has('pages')->with(['chapters', 'pages']);
});
}
/**
* Get an unfetched shelf from the system.
*/
public function shelf(callable|null $queryFilter = null): Bookshelf
{
/** @var Bookshelf $shelf */
$shelf = Bookshelf::query()->when($queryFilter, $queryFilter)->whereNotIn('id', $this->fetchCache['bookshelf'])->first();
$this->addToCache($shelf);
return $shelf;
}
/**
* Get all entity types from the system.
* @return array{page: Page, chapter: Chapter, book: Book, bookshelf: Bookshelf}
*/
public function all(): array
{
return [
'page' => $this->page(),
'chapter' => $this->chapter(),
'book' => $this->book(),
'bookshelf' => $this->shelf(),
];
}
public function updatePage(Page $page, array $data): Page
{
$this->addToCache($page);
return app()->make(PageRepo::class)->update($page, $data);
}
/**
* Create a book to page chain of entities that belong to a specific user.
* @return array{book: Book, chapter: Chapter, page: Page}
*/
public function createChainBelongingToUser(User $creatorUser, ?User $updaterUser = null): array
{
if (empty($updaterUser)) {
$updaterUser = $creatorUser;
}
$userAttrs = ['created_by' => $creatorUser->id, 'owned_by' => $creatorUser->id, 'updated_by' => $updaterUser->id];
/** @var Book $book */
$book = Book::factory()->create($userAttrs);
$chapter = Chapter::factory()->create(array_merge(['book_id' => $book->id], $userAttrs));
$page = Page::factory()->create(array_merge(['book_id' => $book->id, 'chapter_id' => $chapter->id], $userAttrs));
$book->rebuildPermissions();
$this->addToCache([$page, $chapter, $book]);
return compact('book', 'chapter', 'page');
}
/**
* Create and return a new bookshelf.
*/
public function newShelf(array $input = ['name' => 'test shelf', 'description' => 'My new test shelf']): Bookshelf
{
$shelf = app(BookshelfRepo::class)->create($input, []);
$this->addToCache($shelf);
return $shelf;
}
/**
* Create and return a new book.
*/
public function newBook(array $input = ['name' => 'test book', 'description' => 'My new test book']): Book
{
$book = app(BookRepo::class)->create($input);
$this->addToCache($book);
return $book;
}
/**
* Create and return a new test chapter.
*/
public function newChapter(array $input, Book $book): Chapter
{
$chapter = app(ChapterRepo::class)->create($input, $book);
$this->addToCache($chapter);
return $chapter;
}
/**
* Create and return a new test page.
*/
public function newPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
{
$book = $this->book();
$pageRepo = app(PageRepo::class);
$draftPage = $pageRepo->getNewDraftPage($book);
$this->addToCache($draftPage);
return $pageRepo->publishDraft($draftPage, $input);
}
/**
* Create and return a new test draft page.
*/
public function newDraftPage(array $input = ['name' => 'test page', 'html' => 'My new test page']): Page
{
$book = $this->book();
$pageRepo = app(PageRepo::class);
$draftPage = $pageRepo->getNewDraftPage($book);
$pageRepo->updatePageDraft($draftPage, $input);
$this->addToCache($draftPage);
return $draftPage;
}
/**
* Send an entity to the recycle bin.
*/
public function sendToRecycleBin(Entity $entity)
{
$trash = app()->make(TrashCan::class);
if ($entity instanceof Page) {
$trash->softDestroyPage($entity);
} elseif ($entity instanceof Chapter) {
$trash->softDestroyChapter($entity);
} elseif ($entity instanceof Book) {
$trash->softDestroyBook($entity);
} elseif ($entity instanceof Bookshelf) {
$trash->softDestroyBookshelf($entity);
}
$entity->refresh();
if (is_null($entity->deleted_at)) {
throw new \Exception("Could not send entity type [{$entity->getMorphClass()}] to the recycle bin");
}
}
/**
* Fully destroy the given entity from the system, bypassing the recycle bin
* stage. Still runs through main app deletion logic.
*/
public function destroy(Entity $entity)
{
$trash = app()->make(TrashCan::class);
$trash->destroyEntity($entity);
}
/**
* @param Entity|Entity[] $entities
*/
protected function addToCache($entities): void
{
if (!is_array($entities)) {
$entities = [$entities];
}
foreach ($entities as $entity) {
$this->fetchCache[$entity->getType()][] = $entity->id;
}
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Helpers/OidcJwtHelper.php | tests/Helpers/OidcJwtHelper.php | <?php
namespace Tests\Helpers;
use phpseclib3\Crypt\RSA;
/**
* A collection of functions to help with OIDC JWT testing.
* By default, unless overridden, content is provided in a correct working state.
*/
class OidcJwtHelper
{
public static function defaultIssuer(): string
{
return 'https://auth.example.com';
}
public static function defaultClientId(): string
{
return 'xxyyzz.aaa.bbccdd.123';
}
public static function defaultPayload(): array
{
return [
'sub' => 'abc1234def',
'name' => 'Barry Scott',
'email' => 'bscott@example.com',
'ver' => 1,
'iss' => static::defaultIssuer(),
'aud' => static::defaultClientId(),
'iat' => time(),
'exp' => time() + 720,
'jti' => 'ID.AaaBBBbbCCCcccDDddddddEEEeeeeee',
'amr' => ['pwd'],
'idp' => 'fghfghgfh546456dfgdfg',
'preferred_username' => 'xXBazzaXx',
'auth_time' => time(),
'at_hash' => 'sT4jbsdSGy9w12pq3iNYDA',
];
}
public static function idToken($payloadOverrides = [], $headerOverrides = []): string
{
$payload = array_merge(static::defaultPayload(), $payloadOverrides);
$header = array_merge([
'kid' => 'xyz456',
'alg' => 'RS256',
], $headerOverrides);
$top = implode('.', [
static::base64UrlEncode(json_encode($header)),
static::base64UrlEncode(json_encode($payload)),
]);
$privateKey = static::privateKeyInstance();
$signature = $privateKey->sign($top);
return $top . '.' . static::base64UrlEncode($signature);
}
public static function privateKeyInstance()
{
static $key;
if (is_null($key)) {
$key = RSA::loadPrivateKey(static::privatePemKey())->withPadding(RSA::SIGNATURE_PKCS1);
}
return $key;
}
public static function base64UrlEncode(string $decoded): string
{
return strtr(base64_encode($decoded), '+/', '-_');
}
public static function publicPemKey(): string
{
return '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqo1OmfNKec5S2zQC4SP9
DrHuUR0VgCi6oqcGERz7zqO36hqk3A3R3aCgJkEjfnbnMuszRRKs45NbXoOp9pvm
zXL16c93Obn7G8x8A3ao6yN5qKO5S5+CETqOZfKN/g75Xlz7VsC3igOhgsXnPx6i
iM6sbYbk0U/XpFaT84LXKI8VTIPUo7gTeZN1pTET//i9FlzAOzX+xfWBKdOqlEzl
+zihMHCZUUvQu99P+o0MDR0lMUT+vPJ6SJeRfnoHexwt6bZFiNnsZIEL03bX4QNk
WvsLta1+jNUee+8IPVhzCO8bvM86NzLaKUJ4k6NZ5IVrmdCFpFsjCWByOrDG8wdw
3wIDAQAB
-----END PUBLIC KEY-----';
}
public static function privatePemKey(): string
{
return '-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCqjU6Z80p5zlLb
NALhI/0Ose5RHRWAKLqipwYRHPvOo7fqGqTcDdHdoKAmQSN+ducy6zNFEqzjk1te
g6n2m+bNcvXpz3c5ufsbzHwDdqjrI3moo7lLn4IROo5l8o3+DvleXPtWwLeKA6GC
xec/HqKIzqxthuTRT9ekVpPzgtcojxVMg9SjuBN5k3WlMRP/+L0WXMA7Nf7F9YEp
06qUTOX7OKEwcJlRS9C730/6jQwNHSUxRP688npIl5F+egd7HC3ptkWI2exkgQvT
dtfhA2Ra+wu1rX6M1R577wg9WHMI7xu8zzo3MtopQniTo1nkhWuZ0IWkWyMJYHI6
sMbzB3DfAgMBAAECggEADm7K2ghWoxwsstQh8j+DaLzx9/dIHIJV2PHdd5FGVeRQ
6gS7MswQmHrBUrtsb4VMZ2iz/AJqkw+jScpGldH3pCc4XELsSfxNHbseO4TNIqjr
4LOKOLYU4bRc3I+8KGXIAI5JzrucTJemEVUCDrte8cjbmqExt+zTyNpyxsapworF
v+vnSdv40d62f+cS1xvwB+ymLK/B/wZ/DemDCi8jsi7ou/M7l5xNCzjH4iMSLtOW
fgEhejIBG9miMJWPiVpTXE3tMdNuN3OsWc4XXm2t4VRovlZdu30Fax1xWB+Locsv
HlHKLOFc8g+jZh0TL2KCNjPffMcC7kHhW3afshpIsQKBgQDhyWUnkqd6FzbwIX70
SnaMgKoUv5W/K5T+Sv/PA2CyN8Gu8ih/OsoNZSnI0uqe3XQIvvgN/Fq3wO1ttLzf
z5B6ZC7REfTgcR0190gihk6f5rtcj7d6Fy/oG2CE8sDSXgPnpEaBjvJVgN5v/U2s
HpVaidmHTyGLCfEszoeoy8jyrQKBgQDBX8caGylmzQLc6XNntZChlt3e18Nj8MPA
DxWLcoqgdDoofLDQAmLl+vPKyDmhQjos5eas1jgmVVEM4ge+MysaVezvuLBsSnOh
ihc0i63USU6i7YDE83DrCewCthpFHi/wW1S5FoCAzpVy8y99vwcqO4kOXcmf4O6Y
uW6sMsjvOwKBgQDbFtqB+MtsLCSSBF61W6AHHD5tna4H75lG2623yXZF2NanFLF5
K6muL9DI3ujtOMQETJJUt9+rWJjLEEsJ/dYa/SV0l7D/LKOEnyuu3JZkkLaTzZzi
6qcA2bfhqdCzEKlHV99WjkfV8hNlpex9rLuOPB8JLh7FVONicBGxF/UojQKBgDXs
IlYaSuI6utilVKQP0kPtEPOKERc2VS+iRSy8hQGXR3xwwNFQSQm+f+sFCGT6VcSd
W0TI+6Fc2xwPj38vP465dTentbKM1E+wdSYW6SMwSfhO6ECDbfJsst5Sr2Kkt1N7
9FUkfDLu6GfEfnK/KR1SurZB2u51R7NYyg7EnplvAoGAT0aTtOcck0oYN30g5mdf
efqXPwg2wAPYeiec49EbfnteQQKAkqNfJ9K69yE2naf6bw3/5mCBsq/cXeuaBMII
ylysUIRBqt2J0kWm2yCpFWR7H+Ilhdx9A7ZLCqYVt8e+vjO/BOI3cQDe2VPOLPSl
q/1PY4iJviGKddtmfClH3v4=
-----END PRIVATE KEY-----';
}
public static function publicJwkKeyArray(): array
{
return [
'kty' => 'RSA',
'alg' => 'RS256',
'kid' => '066e52af-8884-4926-801d-032a276f9f2a',
'use' => 'sig',
'e' => 'AQAB',
'n' => 'qo1OmfNKec5S2zQC4SP9DrHuUR0VgCi6oqcGERz7zqO36hqk3A3R3aCgJkEjfnbnMuszRRKs45NbXoOp9pvmzXL16c93Obn7G8x8A3ao6yN5qKO5S5-CETqOZfKN_g75Xlz7VsC3igOhgsXnPx6iiM6sbYbk0U_XpFaT84LXKI8VTIPUo7gTeZN1pTET__i9FlzAOzX-xfWBKdOqlEzl-zihMHCZUUvQu99P-o0MDR0lMUT-vPJ6SJeRfnoHexwt6bZFiNnsZIEL03bX4QNkWvsLta1-jNUee-8IPVhzCO8bvM86NzLaKUJ4k6NZ5IVrmdCFpFsjCWByOrDG8wdw3w',
];
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Helpers/TestServiceProvider.php | tests/Helpers/TestServiceProvider.php | <?php
namespace Tests\Helpers;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\ParallelTesting;
use Illuminate\Support\ServiceProvider;
class TestServiceProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
// Tell Laravel's parallel testing functionality to seed the test
// databases with the DummyContentSeeder upon creation.
// This is only done for initial database creation. Seeding
// won't occur on every run.
ParallelTesting::setUpTestDatabase(function ($database, $token) {
Artisan::call('db:seed --class=DummyContentSeeder');
});
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Helpers/PermissionsProvider.php | tests/Helpers/PermissionsProvider.php | <?php
namespace Tests\Helpers;
use BookStack\Entities\Models\Entity;
use BookStack\Permissions\Models\EntityPermission;
use BookStack\Permissions\Models\RolePermission;
use BookStack\Permissions\Permission;
use BookStack\Settings\SettingService;
use BookStack\Users\Models\Role;
use BookStack\Users\Models\User;
class PermissionsProvider
{
public function __construct(
protected UserRoleProvider $userRoleProvider
) {
}
public function makeAppPublic(): void
{
$settings = app(SettingService::class);
$settings->put('app-public', 'true');
}
/**
* Grant role permissions to the provided user.
*/
public function grantUserRolePermissions(User $user, array $permissions): void
{
$newRole = $this->userRoleProvider->createRole($permissions);
$user->attachRole($newRole);
$user->load('roles');
$user->clearPermissionCache();
}
/**
* Completely remove specific role permissions from the provided user.
*/
public function removeUserRolePermissions(User $user, array $permissions): void
{
foreach ($permissions as $permissionName) {
/** @var RolePermission $permission */
$permission = RolePermission::query()
->where('name', '=', $permissionName)
->firstOrFail();
$roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
$query->where('id', '=', $permission->id);
})->get();
/** @var Role $role */
foreach ($roles as $role) {
$role->detachPermission($permission);
}
$user->clearPermissionCache();
}
}
/**
* Change the owner of the given entity to the given user.
*/
public function changeEntityOwner(Entity $entity, User $newOwner): void
{
$entity->owned_by = $newOwner->id;
$entity->save();
$entity->rebuildPermissions();
}
/**
* Regenerate the permission for an entity.
* Centralised to manage clearing of cached elements between requests.
*/
public function regenerateForEntity(Entity $entity): void
{
$entity->rebuildPermissions();
}
/**
* Set the given entity as having restricted permissions, and apply the given
* permissions for the given roles.
* @param string[] $actions
* @param Role[] $roles
*/
public function setEntityPermissions(Entity $entity, array $actions = [], array $roles = [], $inherit = false): void
{
$entity->permissions()->delete();
$permissions = [];
if (!$inherit) {
// Set default permissions to not allow actions so that only the provided role permissions are at play.
$permissions[] = ['role_id' => 0, 'view' => false, 'create' => false, 'update' => false, 'delete' => false];
}
foreach ($roles as $role) {
$permissions[] = $this->actionListToEntityPermissionData($actions, $role->id);
}
$this->addEntityPermissionEntries($entity, $permissions);
}
public function addEntityPermission(Entity $entity, array $actionList, Role $role)
{
$permissionData = $this->actionListToEntityPermissionData($actionList, $role->id);
$this->addEntityPermissionEntries($entity, [$permissionData]);
}
public function setFallbackPermissions(Entity $entity, array $actionList)
{
$entity->permissions()->where('role_id', '=', 0)->delete();
$permissionData = $this->actionListToEntityPermissionData($actionList, 0);
$this->addEntityPermissionEntries($entity, [$permissionData]);
}
/**
* Disable inherited permissions on the given entity.
* Effectively sets the "Other Users" UI permission option to not inherit, with no permissions.
*/
public function disableEntityInheritedPermissions(Entity $entity): void
{
$entity->permissions()->where('role_id', '=', 0)->delete();
$fallback = $this->actionListToEntityPermissionData([]);
$this->addEntityPermissionEntries($entity, [$fallback]);
}
protected function addEntityPermissionEntries(Entity $entity, array $entityPermissionData): void
{
$entity->permissions()->createMany($entityPermissionData);
$entity->load('permissions');
$this->regenerateForEntity($entity);
}
/**
* For the given simple array of string actions (view, create, update, delete), convert
* the format to entity permission data, where permission is granted if the action is in the
* given actionList array.
*/
protected function actionListToEntityPermissionData(array $actionList, int $roleId = 0): array
{
$permissionData = ['role_id' => $roleId];
foreach (Permission::genericForEntity() as $permission) {
$permissionData[$permission->value] = in_array($permission->value, $actionList);
}
return $permissionData;
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Helpers/UserRoleProvider.php | tests/Helpers/UserRoleProvider.php | <?php
namespace Tests\Helpers;
use BookStack\Permissions\PermissionsRepo;
use BookStack\Users\Models\Role;
use BookStack\Users\Models\User;
class UserRoleProvider
{
protected ?User $admin = null;
protected ?User $editor = null;
/**
* Get a typical "Admin" user.
*/
public function admin(): User
{
if (is_null($this->admin)) {
$adminRole = Role::getSystemRole('admin');
$this->admin = $adminRole->users()->first();
}
return $this->admin;
}
/**
* Get a typical "Editor" user.
*/
public function editor(): User
{
if ($this->editor === null) {
$editorRole = Role::getRole('editor');
$this->editor = $editorRole->users->first();
}
return $this->editor;
}
/**
* Get a typical "Viewer" user.
*/
public function viewer(array $attributes = []): User
{
$user = Role::getRole('viewer')->users()->first();
if (!empty($attributes)) {
$user->forceFill($attributes)->save();
}
return $user;
}
/**
* Get the system "guest" user.
*/
public function guest(): User
{
return User::getGuest();
}
/**
* Create a new fresh user without any relations.
*/
public function newUser(array $attrs = []): User
{
return User::factory()->create($attrs);
}
/**
* Create a new fresh user, with the given attrs, that has assigned a fresh role
* that has the given role permissions.
* Intended as a helper to create a blank slate baseline user and role.
* @return array{0: User, 1: Role}
*/
public function newUserWithRole(array $userAttrs = [], array $rolePermissions = []): array
{
$user = $this->newUser($userAttrs);
$role = $this->attachNewRole($user, $rolePermissions);
return [$user, $role];
}
/**
* Attach a new role, with the given role permissions, to the given user
* and return that role.
*/
public function attachNewRole(User $user, array $rolePermissions = []): Role
{
$role = $this->createRole($rolePermissions);
$user->attachRole($role);
return $role;
}
/**
* Create a new basic role with the given role permissions.
*/
public function createRole(array $rolePermissions = []): Role
{
$permissionRepo = app(PermissionsRepo::class);
$roleData = Role::factory()->make()->toArray();
$roleData['permissions'] = $rolePermissions;
return $permissionRepo->saveNewRole($roleData);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Helpers/FileProvider.php | tests/Helpers/FileProvider.php | <?php
namespace Tests\Helpers;
use BookStack\Entities\Models\Page;
use BookStack\Uploads\Attachment;
use BookStack\Uploads\AttachmentService;
use Illuminate\Http\UploadedFile;
use Illuminate\Testing\TestResponse;
use stdClass;
use Tests\TestCase;
class FileProvider
{
/**
* Get the path to a file in the test-data-directory.
*/
public function testFilePath(string $fileName): string
{
return base_path('tests/test-data/' . $fileName);
}
/**
* Creates a new temporary image file using the given name,
* with the content decoded from the given bas64 file name.
* Is generally used for testing sketchy files that could trip AV.
*/
public function imageFromBase64File(string $base64FileName, string $imageFileName): UploadedFile
{
$imagePath = implode(DIRECTORY_SEPARATOR, [sys_get_temp_dir(), $imageFileName]);
$base64FilePath = $this->testFilePath($base64FileName);
$data = file_get_contents($base64FilePath);
$decoded = base64_decode($data);
file_put_contents($imagePath, $decoded);
return new UploadedFile($imagePath, $imageFileName, 'image/png', null, true);
}
/**
* Get a test image UploadedFile instance, that can be uploaded via test requests.
*/
public function uploadedImage(string $fileName, string $testDataFileName = ''): UploadedFile
{
return new UploadedFile($this->testFilePath($testDataFileName ?: 'test-image.png'), $fileName, 'image/png', null, true);
}
/**
* Get a test txt UploadedFile instance, that can be uploaded via test requests.
*/
public function uploadedTextFile(string $fileName): UploadedFile
{
return new UploadedFile($this->testFilePath('test-file.txt'), $fileName, 'text/plain', null, true);
}
/**
* Get raw data for a PNG image test file.
*/
public function pngImageData(): string
{
return file_get_contents($this->testFilePath('test-image.png'));
}
/**
* Get raw data for a Jpeg image test file.
*/
public function jpegImageData(): string
{
return file_get_contents($this->testFilePath('test-image.jpg'));
}
/**
* Get the expected relative path for an uploaded image of the given type and filename.
*/
public function expectedImagePath(string $imageType, string $fileName): string
{
return '/uploads/images/' . $imageType . '/' . date('Y-m') . '/' . $fileName;
}
/**
* Performs an image gallery upload request with the given name.
*/
public function uploadGalleryImage(TestCase $case, string $name, int $uploadedTo = 0, string $contentType = 'image/png', string $testDataFileName = ''): TestResponse
{
$file = $this->uploadedImage($name, $testDataFileName);
return $case->call('POST', '/images/gallery', ['uploaded_to' => $uploadedTo], [], ['file' => $file], ['CONTENT_TYPE' => $contentType]);
}
/**
* Upload a new gallery image and return a set of details about the image,
* including the json decoded response of the upload.
* Ensures the upload succeeds.
*
* @return array{name: string, path: string, page: Page, response: stdClass}
*/
public function uploadGalleryImageToPage(TestCase $case, Page $page, string $testDataFileName = ''): array
{
$imageName = $testDataFileName ?: 'first-image.png';
$relPath = $this->expectedImagePath('gallery', $imageName);
$this->deleteAtRelativePath($relPath);
$upload = $this->uploadGalleryImage($case, $imageName, $page->id, 'image/png', $testDataFileName);
$upload->assertStatus(200);
return [
'name' => $imageName,
'path' => $relPath,
'page' => $page,
'response' => json_decode($upload->getContent()),
];
}
/**
* Uploads an attachment file with the given name.
*/
public function uploadAttachmentFile(TestCase $case, string $name, int $uploadedTo = 0): TestResponse
{
$file = $this->uploadedTextFile($name);
return $case->call('POST', '/attachments/upload', ['uploaded_to' => $uploadedTo], [], ['file' => $file], []);
}
/**
* Upload a new attachment from the given raw data of the given type, to the given page.
* Returns the attachment
*/
public function uploadAttachmentDataToPage(TestCase $case, Page $page, string $filename, string $content, string $mimeType): Attachment
{
$file = tmpfile();
$filePath = stream_get_meta_data($file)['uri'];
file_put_contents($filePath, $content);
$upload = new UploadedFile($filePath, $filename, $mimeType, null, true);
$case->call('POST', '/attachments/upload', ['uploaded_to' => $page->id], [], ['file' => $upload], []);
return $page->attachments()->where('uploaded_to', '=', $page->id)->latest()->firstOrFail();
}
/**
* Delete an uploaded image.
*/
public function deleteAtRelativePath(string $path): void
{
$fullPath = $this->relativeToFullPath($path);
if (file_exists($fullPath)) {
unlink($fullPath);
}
}
/**
* Convert a relative path used by default in this provider to a full
* absolute local filesystem path.
*/
public function relativeToFullPath(string $path): string
{
return public_path($path);
}
/**
* Delete all uploaded files.
* To assist with cleanup.
*/
public function deleteAllAttachmentFiles(): void
{
$fileService = app()->make(AttachmentService::class);
foreach (Attachment::all() as $file) {
$fileService->deleteFile($file);
}
}
/**
* Reset the application favicon image in the public path.
*/
public function resetAppFavicon(): void
{
file_put_contents(public_path('favicon.ico'), file_get_contents(public_path('icon.ico')));
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/TagTest.php | tests/Entity/TagTest.php | <?php
namespace Tests\Entity;
use BookStack\Activity\Models\Tag;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Models\Page;
use Tests\TestCase;
class TagTest extends TestCase
{
protected int $defaultTagCount = 20;
/**
* Get an instance of a page that has many tags.
*/
protected function getEntityWithTags($class, ?array $tags = null): Entity
{
$entity = $class::first();
if (is_null($tags)) {
$tags = Tag::factory()->count($this->defaultTagCount)->make();
}
$entity->tags()->saveMany($tags);
return $entity;
}
public function test_tag_name_suggestions()
{
// Create some tags with similar names to test with
$attrs = collect();
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'country']));
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'color']));
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'city']));
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'county']));
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'planet']));
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'plans']));
$page = $this->getEntityWithTags(Page::class, $attrs->all());
$this->asAdmin()->get('/ajax/tags/suggest/names?search=dog')->assertSimilarJson([]);
$this->get('/ajax/tags/suggest/names?search=co')->assertSimilarJson(['color', 'country', 'county']);
$this->get('/ajax/tags/suggest/names?search=cou')->assertSimilarJson(['country', 'county']);
$this->get('/ajax/tags/suggest/names?search=pla')->assertSimilarJson(['planet', 'plans']);
}
public function test_tag_value_suggestions()
{
// Create some tags with similar values to test with
$attrs = collect();
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'country', 'value' => 'cats']));
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'color', 'value' => 'cattery']));
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'city', 'value' => 'castle']));
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'county', 'value' => 'dog']));
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'planet', 'value' => 'catapult']));
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'plans', 'value' => 'dodgy']));
$page = $this->getEntityWithTags(Page::class, $attrs->all());
$this->asAdmin()->get('/ajax/tags/suggest/values?search=ora')->assertSimilarJson([]);
$this->get('/ajax/tags/suggest/values?search=cat')->assertSimilarJson(['cats', 'cattery', 'catapult']);
$this->get('/ajax/tags/suggest/values?search=do')->assertSimilarJson(['dog', 'dodgy']);
$this->get('/ajax/tags/suggest/values?search=cas')->assertSimilarJson(['castle']);
}
public function test_entity_permissions_effect_tag_suggestions()
{
// Create some tags with similar names to test with and save to a page
$attrs = collect();
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'country']));
$attrs = $attrs->merge(Tag::factory()->count(5)->make(['name' => 'color']));
$page = $this->getEntityWithTags(Page::class, $attrs->all());
$this->asAdmin()->get('/ajax/tags/suggest/names?search=co')->assertSimilarJson(['color', 'country']);
$this->asEditor()->get('/ajax/tags/suggest/names?search=co')->assertSimilarJson(['color', 'country']);
// Set restricted permission the page
$this->permissions->setEntityPermissions($page, [], []);
$this->asAdmin()->get('/ajax/tags/suggest/names?search=co')->assertSimilarJson(['color', 'country']);
$this->asEditor()->get('/ajax/tags/suggest/names?search=co')->assertSimilarJson([]);
}
public function test_tags_shown_on_search_listing()
{
$tags = [
Tag::factory()->make(['name' => 'category', 'value' => 'buckets']),
Tag::factory()->make(['name' => 'color', 'value' => 'red']),
];
$page = $this->getEntityWithTags(Page::class, $tags);
$resp = $this->asEditor()->get('/search?term=[category]');
$resp->assertSee($page->name);
$this->withHtml($resp)->assertElementContains('[href="' . $page->getUrl() . '"]', 'category');
$this->withHtml($resp)->assertElementContains('[href="' . $page->getUrl() . '"]', 'buckets');
$this->withHtml($resp)->assertElementContains('[href="' . $page->getUrl() . '"]', 'color');
$this->withHtml($resp)->assertElementContains('[href="' . $page->getUrl() . '"]', 'red');
}
public function test_tags_index_shows_tag_name_as_expected_with_right_counts()
{
$page = $this->entities->page();
$page->tags()->create(['name' => 'Category', 'value' => 'GreatTestContent']);
$page->tags()->create(['name' => 'Category', 'value' => 'OtherTestContent']);
$resp = $this->asEditor()->get('/tags');
$resp->assertSee('Category');
$html = $this->withHtml($resp);
$html->assertElementCount('.tag-item', 1);
$resp->assertDontSee('GreatTestContent');
$resp->assertDontSee('OtherTestContent');
$html->assertElementContains('a[title="Total tag usages"]', '2');
$html->assertElementContains('a[title="Assigned to Pages"]', '2');
$html->assertElementContains('a[title="Assigned to Books"]', '0');
$html->assertElementContains('a[title="Assigned to Chapters"]', '0');
$html->assertElementContains('a[title="Assigned to Shelves"]', '0');
$html->assertElementContains('a[href$="/tags?name=Category"]', '2 unique values');
$book = $this->entities->book();
$book->tags()->create(['name' => 'Category', 'value' => 'GreatTestContent']);
$resp = $this->asEditor()->get('/tags');
$this->withHtml($resp)->assertElementContains('a[title="Total tag usages"]', '3');
$this->withHtml($resp)->assertElementContains('a[title="Assigned to Books"]', '1');
$this->withHtml($resp)->assertElementContains('a[href$="/tags?name=Category"]', '2 unique values');
}
public function test_tag_index_can_be_searched()
{
$page = $this->entities->page();
$page->tags()->create(['name' => 'Category', 'value' => 'GreatTestContent']);
$resp = $this->asEditor()->get('/tags?search=cat');
$this->withHtml($resp)->assertElementContains('.tag-item .tag-name', 'Category');
$resp = $this->asEditor()->get('/tags?search=content');
$this->withHtml($resp)->assertElementContains('.tag-item .tag-name', 'Category');
$this->withHtml($resp)->assertElementContains('.tag-item .tag-value', 'GreatTestContent');
$resp = $this->asEditor()->get('/tags?search=other');
$this->withHtml($resp)->assertElementNotExists('.tag-item .tag-name');
}
public function test_tag_index_search_will_show_mulitple_values_of_a_single_tag_name()
{
$page = $this->entities->page();
$page->tags()->create(['name' => 'Animal', 'value' => 'Catfish']);
$page->tags()->create(['name' => 'Animal', 'value' => 'Catdog']);
$resp = $this->asEditor()->get('/tags?search=cat');
$this->withHtml($resp)->assertElementContains('.tag-item .tag-value', 'Catfish');
$this->withHtml($resp)->assertElementContains('.tag-item .tag-value', 'Catdog');
}
public function test_tag_index_can_be_scoped_to_specific_tag_name()
{
$page = $this->entities->page();
$page->tags()->create(['name' => 'Category', 'value' => 'GreatTestContent']);
$page->tags()->create(['name' => 'Category', 'value' => 'OtherTestContent']);
$page->tags()->create(['name' => 'OtherTagName', 'value' => 'OtherValue']);
$resp = $this->asEditor()->get('/tags?name=Category');
$resp->assertSee('Category');
$resp->assertSee('GreatTestContent');
$resp->assertSee('OtherTestContent');
$resp->assertDontSee('OtherTagName');
$resp->assertSee('Active Filter:');
$this->withHtml($resp)->assertElementCount('.item-list .tag-item', 2);
$this->withHtml($resp)->assertElementContains('form[action$="/tags"]', 'Clear Filter');
}
public function test_tags_index_adheres_to_page_permissions()
{
$page = $this->entities->page();
$page->tags()->create(['name' => 'SuperCategory', 'value' => 'GreatTestContent']);
$resp = $this->asEditor()->get('/tags');
$resp->assertSee('SuperCategory');
$resp = $this->get('/tags?name=SuperCategory');
$resp->assertSee('GreatTestContent');
$this->permissions->setEntityPermissions($page, [], []);
$resp = $this->asEditor()->get('/tags');
$resp->assertDontSee('SuperCategory');
$resp = $this->get('/tags?name=SuperCategory');
$resp->assertDontSee('GreatTestContent');
}
public function test_tag_index_shows_message_on_no_results()
{
$resp = $this->asEditor()->get('/tags?search=testingval');
$resp->assertSee('No items available');
$resp->assertSee('Tags can be assigned via the page editor sidebar');
}
public function test_tag_index_does_not_include_tags_on_recycle_bin_items()
{
$page = $this->entities->page();
$page->tags()->create(['name' => 'DeleteRecord', 'value' => 'itemToDeleteTest']);
$resp = $this->asEditor()->get('/tags');
$resp->assertSee('DeleteRecord');
$resp = $this->asEditor()->get('/tags?name=DeleteRecord');
$resp->assertSee('itemToDeleteTest');
$this->entities->sendToRecycleBin($page);
$resp = $this->asEditor()->get('/tags');
$resp->assertDontSee('DeleteRecord');
$resp = $this->asEditor()->get('/tags?name=DeleteRecord');
$resp->assertDontSee('itemToDeleteTest');
}
public function test_tag_classes_visible_on_entities()
{
$this->asEditor();
foreach ($this->entities->all() as $entity) {
$entity->tags()->create(['name' => 'My Super Tag Name', 'value' => 'An-awesome-value']);
$html = $this->withHtml($this->get($entity->getUrl()));
$html->assertElementExists('body.tag-name-mysupertagname.tag-value-anawesomevalue.tag-pair-mysupertagname-anawesomevalue');
}
}
public function test_tag_classes_are_escaped()
{
$page = $this->entities->page();
$page->tags()->create(['name' => '<>']);
$resp = $this->asEditor()->get($page->getUrl());
$resp->assertDontSee('tag-name-<>', false);
$resp->assertSee('tag-name-<>', false);
}
public function test_parent_tag_classes_visible()
{
$page = $this->entities->pageWithinChapter();
$page->chapter->tags()->create(['name' => 'My Chapter Tag', 'value' => 'abc123']);
$page->book->tags()->create(['name' => 'My Book Tag', 'value' => 'def456']);
$this->asEditor();
$html = $this->withHtml($this->get($page->getUrl()));
$html->assertElementExists('body.chapter-tag-pair-mychaptertag-abc123');
$html->assertElementExists('body.book-tag-pair-mybooktag-def456');
$html = $this->withHtml($this->get($page->chapter->getUrl()));
$html->assertElementExists('body.book-tag-pair-mybooktag-def456');
}
public function test_parent_tag_classes_not_visible_if_cannot_see_parent()
{
$page = $this->entities->pageWithinChapter();
$page->chapter->tags()->create(['name' => 'My Chapter Tag', 'value' => 'abc123']);
$page->book->tags()->create(['name' => 'My Book Tag', 'value' => 'def456']);
$editor = $this->users->editor();
$this->actingAs($editor);
$this->permissions->setEntityPermissions($page, ['view'], [$editor->roles()->first()]);
$this->permissions->disableEntityInheritedPermissions($page->chapter);
$html = $this->withHtml($this->get($page->getUrl()));
$html->assertElementNotExists('body.chapter-tag-pair-mychaptertag-abc123');
$html->assertElementExists('body.book-tag-pair-mybooktag-def456');
$this->permissions->disableEntityInheritedPermissions($page->book);
$html = $this->withHtml($this->get($page->getUrl()));
$html->assertElementNotExists('body.book-tag-pair-mybooktag-def456');
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/ChapterTest.php | tests/Entity/ChapterTest.php | <?php
namespace Tests\Entity;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Models\Page;
use Tests\TestCase;
class ChapterTest extends TestCase
{
public function test_create()
{
$book = $this->entities->book();
$chapter = Chapter::factory()->make([
'name' => 'My First Chapter',
]);
$resp = $this->asEditor()->get($book->getUrl());
$this->withHtml($resp)->assertElementContains('a[href="' . $book->getUrl('/create-chapter') . '"]', 'New Chapter');
$resp = $this->get($book->getUrl('/create-chapter'));
$this->withHtml($resp)->assertElementContains('form[action="' . $book->getUrl('/create-chapter') . '"][method="POST"]', 'Save Chapter');
$resp = $this->post($book->getUrl('/create-chapter'), $chapter->only('name', 'description_html'));
$resp->assertRedirect($book->getUrl('/chapter/my-first-chapter'));
$resp = $this->get($book->getUrl('/chapter/my-first-chapter'));
$resp->assertSee($chapter->name);
$resp->assertSee($chapter->description_html, false);
}
public function test_show_view_displays_description_if_no_description_html_set()
{
$chapter = $this->entities->chapter();
$chapter->description_html = '';
$chapter->description = "My great\ndescription\n\nwith newlines";
$chapter->save();
$resp = $this->asEditor()->get($chapter->getUrl());
$resp->assertSee("<p>My great<br>\ndescription<br>\n<br>\nwith newlines</p>", false);
}
public function test_delete()
{
$chapter = Chapter::query()->whereHas('pages')->first();
$this->assertNull($chapter->deleted_at);
$pageCount = $chapter->pages()->count();
$deleteViewReq = $this->asEditor()->get($chapter->getUrl('/delete'));
$deleteViewReq->assertSeeText('Are you sure you want to delete this chapter?');
$deleteReq = $this->delete($chapter->getUrl());
$deleteReq->assertRedirect($chapter->getParent()->getUrl());
$this->assertActivityExists('chapter_delete', $chapter);
$chapter->refresh();
$this->assertNotNull($chapter->deleted_at);
$this->assertTrue($chapter->pages()->count() === 0);
$this->assertTrue($chapter->pages()->withTrashed()->count() === $pageCount);
$this->assertTrue($chapter->deletions()->count() === 1);
$redirectReq = $this->get($deleteReq->baseResponse->headers->get('location'));
$this->assertNotificationContains($redirectReq, 'Chapter Successfully Deleted');
}
public function test_sort_book_action_visible_if_permissions_allow()
{
$chapter = $this->entities->chapter();
$resp = $this->actingAs($this->users->viewer())->get($chapter->getUrl());
$this->withHtml($resp)->assertLinkNotExists($chapter->book->getUrl('sort'));
$resp = $this->asEditor()->get($chapter->getUrl());
$this->withHtml($resp)->assertLinkExists($chapter->book->getUrl('sort'));
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/PageTemplateTest.php | tests/Entity/PageTemplateTest.php | <?php
namespace Tests\Entity;
use BookStack\Entities\Models\Page;
use Tests\TestCase;
class PageTemplateTest extends TestCase
{
public function test_active_templates_visible_on_page_view()
{
$page = $this->entities->page();
$this->asEditor();
$templateView = $this->get($page->getUrl());
$templateView->assertDontSee('Page Template');
$page->template = true;
$page->save();
$templateView = $this->get($page->getUrl());
$templateView->assertSee('Page Template');
}
public function test_manage_templates_permission_required_to_change_page_template_status()
{
$page = $this->entities->page();
$editor = $this->users->editor();
$this->actingAs($editor);
$pageUpdateData = [
'name' => $page->name,
'html' => $page->html,
'template' => 'true',
];
$this->put($page->getUrl(), $pageUpdateData);
$this->assertDatabaseHasEntityData('page', [
'id' => $page->id,
'template' => false,
]);
$this->permissions->grantUserRolePermissions($editor, ['templates-manage']);
$this->put($page->getUrl(), $pageUpdateData);
$this->assertDatabaseHasEntityData('page', [
'id' => $page->id,
'template' => true,
]);
}
public function test_templates_content_should_be_fetchable_only_if_page_marked_as_template()
{
$content = '<div>my_custom_template_content</div>';
$page = $this->entities->page();
$editor = $this->users->editor();
$this->actingAs($editor);
$templateFetch = $this->get('/templates/' . $page->id);
$templateFetch->assertStatus(404);
$page->html = $content;
$page->template = true;
$page->save();
$templateFetch = $this->get('/templates/' . $page->id);
$templateFetch->assertStatus(200);
$templateFetch->assertJson([
'html' => $content,
'markdown' => '',
]);
}
public function test_template_endpoint_returns_paginated_list_of_templates()
{
$editor = $this->users->editor();
$this->actingAs($editor);
$toBeTemplates = Page::query()->orderBy('name', 'asc')->take(12)->get();
$page = $toBeTemplates->first();
$emptyTemplatesFetch = $this->get('/templates');
$emptyTemplatesFetch->assertDontSee($page->name);
Page::query()->whereIn('id', $toBeTemplates->pluck('id')->toArray())->update(['template' => true]);
$templatesFetch = $this->get('/templates');
$templatesFetch->assertSee($page->name);
$templatesFetch->assertSee('pagination');
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/PageDraftTest.php | tests/Entity/PageDraftTest.php | <?php
namespace Tests\Entity;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Models\PageRevision;
use BookStack\Entities\Repos\PageRepo;
use Tests\TestCase;
class PageDraftTest extends TestCase
{
protected Page $page;
protected PageRepo $pageRepo;
protected function setUp(): void
{
parent::setUp();
$this->page = $this->entities->page();
$this->pageRepo = app()->make(PageRepo::class);
}
public function test_draft_content_shows_if_available()
{
$addedContent = '<p>test message content</p>';
$resp = $this->asAdmin()->get($this->page->getUrl('/edit'));
$this->withHtml($resp)->assertElementNotContains('[name="html"]', $addedContent);
$newContent = $this->page->html . $addedContent;
$this->pageRepo->updatePageDraft($this->page, ['html' => $newContent]);
$resp = $this->asAdmin()->get($this->page->getUrl('/edit'));
$this->withHtml($resp)->assertElementContains('[name="html"]', $newContent);
}
public function test_draft_not_visible_by_others()
{
$addedContent = '<p>test message content</p>';
$resp = $this->asAdmin()->get($this->page->getUrl('/edit'));
$this->withHtml($resp)->assertElementNotContains('[name="html"]', $addedContent);
$newContent = $this->page->html . $addedContent;
$newUser = $this->users->editor();
$this->pageRepo->updatePageDraft($this->page, ['html' => $newContent]);
$resp = $this->actingAs($newUser)->get($this->page->getUrl('/edit'));
$this->withHtml($resp)->assertElementNotContains('[name="html"]', $newContent);
}
public function test_alert_message_shows_if_editing_draft()
{
$this->asAdmin();
$this->pageRepo->updatePageDraft($this->page, ['html' => 'test content']);
$this->asAdmin()->get($this->page->getUrl('/edit'))
->assertSee('You are currently editing a draft');
}
public function test_alert_message_shows_if_someone_else_editing()
{
$nonEditedPage = Page::query()->take(10)->get()->last();
$addedContent = '<p>test message content</p>';
$resp = $this->asAdmin()->get($this->page->getUrl('/edit'));
$this->withHtml($resp)->assertElementNotContains('[name="html"]', $addedContent);
$newContent = $this->page->html . $addedContent;
$newUser = $this->users->editor();
$this->pageRepo->updatePageDraft($this->page, ['html' => $newContent]);
$this->actingAs($newUser)
->get($this->page->getUrl('/edit'))
->assertSee('Admin has started editing this page');
$this->flushSession();
$resp = $this->get($nonEditedPage->getUrl() . '/edit');
$this->withHtml($resp)->assertElementNotContains('.notification', 'Admin has started editing this page');
}
public function test_draft_save_shows_alert_if_draft_older_than_last_page_update()
{
$admin = $this->users->admin();
$editor = $this->users->editor();
$page = $this->entities->page();
$this->actingAs($editor)->put('/ajax/page/' . $page->id . '/save-draft', [
'name' => $page->name,
'html' => '<p>updated draft</p>',
]);
/** @var PageRevision $draft */
$draft = $page->allRevisions()
->where('type', '=', 'update_draft')
->where('created_by', '=', $editor->id)
->first();
$draft->created_at = now()->subMinute(1);
$draft->save();
$this->actingAs($admin)->put($page->refresh()->getUrl(), [
'name' => $page->name,
'html' => '<p>admin update</p>',
]);
$resp = $this->actingAs($editor)->put('/ajax/page/' . $page->id . '/save-draft', [
'name' => $page->name,
'html' => '<p>updated draft again</p>',
]);
$resp->assertJson([
'warning' => 'This page has been updated since this draft was created. It is recommended that you discard this draft or take care not to overwrite any page changes.',
]);
}
public function test_draft_save_shows_alert_if_draft_edit_started_by_someone_else()
{
$admin = $this->users->admin();
$editor = $this->users->editor();
$page = $this->entities->page();
$this->actingAs($admin)->put('/ajax/page/' . $page->id . '/save-draft', [
'name' => $page->name,
'html' => '<p>updated draft</p>',
]);
$resp = $this->actingAs($editor)->put('/ajax/page/' . $page->id . '/save-draft', [
'name' => $page->name,
'html' => '<p>updated draft again</p>',
]);
$resp->assertJson([
'warning' => 'Admin has started editing this page in the last 60 minutes. Take care not to overwrite each other\'s updates!',
]);
}
public function test_draft_pages_show_on_homepage()
{
$book = $this->entities->book();
$resp = $this->asAdmin()->get('/');
$this->withHtml($resp)->assertElementNotContains('#recent-drafts', 'New Page');
$this->get($book->getUrl() . '/create-page');
$this->withHtml($this->get('/'))->assertElementContains('#recent-drafts', 'New Page');
}
public function test_draft_pages_not_visible_by_others()
{
$book = $this->entities->book();
$chapter = $book->chapters->first();
$newUser = $this->users->editor();
$this->actingAs($newUser)->get($book->getUrl('/create-page'));
$this->get($chapter->getUrl('/create-page'));
$resp = $this->get($book->getUrl());
$this->withHtml($resp)->assertElementContains('.book-contents', 'New Page');
$resp = $this->asAdmin()->get($book->getUrl());
$this->withHtml($resp)->assertElementNotContains('.book-contents', 'New Page');
$resp = $this->get($chapter->getUrl());
$this->withHtml($resp)->assertElementNotContains('.book-contents', 'New Page');
}
public function test_page_html_in_ajax_fetch_response()
{
$this->asAdmin();
$page = $this->entities->page();
$this->getJson('/ajax/page/' . $page->id)->assertJson([
'html' => $page->html,
]);
}
public function test_user_draft_removed_on_user_drafts_delete_call()
{
$editor = $this->users->editor();
$page = $this->entities->page();
$this->actingAs($editor)->put('/ajax/page/' . $page->id . '/save-draft', [
'name' => $page->name,
'html' => '<p>updated draft again</p>',
]);
$revisionData = [
'type' => 'update_draft',
'created_by' => $editor->id,
'page_id' => $page->id,
];
$this->assertDatabaseHas('page_revisions', $revisionData);
$resp = $this->delete("/page-revisions/user-drafts/{$page->id}");
$resp->assertOk();
$this->assertDatabaseMissing('page_revisions', $revisionData);
}
public function test_updating_page_draft_with_markdown_retains_markdown_content()
{
$book = $this->entities->book();
$this->asEditor()->get($book->getUrl('/create-page'));
/** @var Page $draft */
$draft = Page::query()->where('draft', '=', true)->where('book_id', '=', $book->id)->firstOrFail();
$resp = $this->put('/ajax/page/' . $draft->id . '/save-draft', [
'name' => 'My updated draft',
'markdown' => "# My markdown page\n\n[A link](https://example.com)",
'html' => '<p>checking markdown takes priority over this</p>',
]);
$resp->assertOk();
$this->assertDatabaseHasEntityData('page', [
'id' => $draft->id,
'draft' => true,
'name' => 'My updated draft',
'markdown' => "# My markdown page\n\n[A link](https://example.com)",
]);
$draft->refresh();
$this->assertStringContainsString('href="https://example.com"', $draft->html);
}
public function test_slug_generated_on_draft_publish_to_page_when_no_name_change()
{
$book = $this->entities->book();
$this->asEditor()->get($book->getUrl('/create-page'));
/** @var Page $draft */
$draft = Page::query()->where('draft', '=', true)->where('book_id', '=', $book->id)->firstOrFail();
$this->put('/ajax/page/' . $draft->id . '/save-draft', [
'name' => 'My page',
'markdown' => 'Update test',
])->assertOk();
$draft->refresh();
$this->assertEmpty($draft->slug);
$this->post($draft->getUrl(), [
'name' => 'My page',
'markdown' => '# My markdown page',
]);
$this->assertDatabaseHasEntityData('page', [
'id' => $draft->id,
'draft' => false,
'slug' => 'my-page',
]);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
BookStackApp/BookStack | https://github.com/BookStackApp/BookStack/blob/e6b754fad029d6c35e139b907d04e6510775997b/tests/Entity/SlugTest.php | tests/Entity/SlugTest.php | <?php
namespace Tests\Entity;
use BookStack\Entities\Models\SlugHistory;
use Tests\TestCase;
class SlugTest extends TestCase
{
public function test_slug_multi_byte_url_safe()
{
$book = $this->entities->newBook([
'name' => 'информация',
]);
$this->assertEquals('informaciia', $book->slug);
$book = $this->entities->newBook([
'name' => '¿Qué?',
]);
$this->assertEquals('que', $book->slug);
}
public function test_slug_format()
{
$book = $this->entities->newBook([
'name' => 'PartA / PartB / PartC',
]);
$this->assertEquals('parta-partb-partc', $book->slug);
}
public function test_old_page_slugs_redirect_to_new_pages()
{
$page = $this->entities->page();
$pageUrl = $page->getUrl();
$this->asAdmin()->put($pageUrl, [
'name' => 'super test page',
'html' => '<p></p>',
]);
$this->get($pageUrl)
->assertRedirect("/books/{$page->book->slug}/page/super-test-page");
}
public function test_old_shelf_slugs_redirect_to_new_shelf()
{
$shelf = $this->entities->shelf();
$shelfUrl = $shelf->getUrl();
$this->asAdmin()->put($shelf->getUrl(), [
'name' => 'super test shelf',
]);
$this->get($shelfUrl)
->assertRedirect("/shelves/super-test-shelf");
}
public function test_old_book_slugs_redirect_to_new_book()
{
$book = $this->entities->book();
$bookUrl = $book->getUrl();
$this->asAdmin()->put($book->getUrl(), [
'name' => 'super test book',
]);
$this->get($bookUrl)
->assertRedirect("/books/super-test-book");
}
public function test_old_chapter_slugs_redirect_to_new_chapter()
{
$chapter = $this->entities->chapter();
$chapterUrl = $chapter->getUrl();
$this->asAdmin()->put($chapter->getUrl(), [
'name' => 'super test chapter',
]);
$this->get($chapterUrl)
->assertRedirect("/books/{$chapter->book->slug}/chapter/super-test-chapter");
}
public function test_old_book_slugs_in_page_urls_redirect_to_current_page_url()
{
$page = $this->entities->page();
$book = $page->book;
$pageUrl = $page->getUrl();
$this->asAdmin()->put($book->getUrl(), [
'name' => 'super test book',
]);
$this->get($pageUrl)
->assertRedirect("/books/super-test-book/page/{$page->slug}");
}
public function test_old_book_slugs_in_chapter_urls_redirect_to_current_chapter_url()
{
$chapter = $this->entities->chapter();
$book = $chapter->book;
$chapterUrl = $chapter->getUrl();
$this->asAdmin()->put($book->getUrl(), [
'name' => 'super test book',
]);
$this->get($chapterUrl)
->assertRedirect("/books/super-test-book/chapter/{$chapter->slug}");
}
public function test_slug_lookup_controlled_by_permissions()
{
$editor = $this->users->editor();
$pageA = $this->entities->page();
$pageB = $this->entities->page();
SlugHistory::factory()->create(['sluggable_id' => $pageA->id, 'sluggable_type' => 'page', 'slug' => 'monkey', 'parent_slug' => 'animals', 'created_at' => now()]);
SlugHistory::factory()->create(['sluggable_id' => $pageB->id, 'sluggable_type' => 'page', 'slug' => 'monkey', 'parent_slug' => 'animals', 'created_at' => now()->subDay()]);
// Defaults to latest where visible
$this->actingAs($editor)->get("/books/animals/page/monkey")->assertRedirect($pageA->getUrl());
$this->permissions->disableEntityInheritedPermissions($pageA);
// Falls back to other entry where the latest is not visible
$this->actingAs($editor)->get("/books/animals/page/monkey")->assertRedirect($pageB->getUrl());
// Original still accessible where permissions allow
$this->asAdmin()->get("/books/animals/page/monkey")->assertRedirect($pageA->getUrl());
}
public function test_slugs_recorded_in_history_on_page_update()
{
$page = $this->entities->page();
$this->asAdmin()->put($page->getUrl(), [
'name' => 'new slug',
'html' => '<p></p>',
]);
$oldSlug = $page->slug;
$page->refresh();
$this->assertNotEquals($oldSlug, $page->slug);
$this->assertDatabaseHas('slug_history', [
'sluggable_id' => $page->id,
'sluggable_type' => 'page',
'slug' => $oldSlug,
'parent_slug' => $page->book->slug,
]);
}
public function test_slugs_recorded_in_history_on_chapter_update()
{
$chapter = $this->entities->chapter();
$this->asAdmin()->put($chapter->getUrl(), [
'name' => 'new slug',
]);
$oldSlug = $chapter->slug;
$chapter->refresh();
$this->assertNotEquals($oldSlug, $chapter->slug);
$this->assertDatabaseHas('slug_history', [
'sluggable_id' => $chapter->id,
'sluggable_type' => 'chapter',
'slug' => $oldSlug,
'parent_slug' => $chapter->book->slug,
]);
}
public function test_slugs_recorded_in_history_on_book_update()
{
$book = $this->entities->book();
$this->asAdmin()->put($book->getUrl(), [
'name' => 'new slug',
]);
$oldSlug = $book->slug;
$book->refresh();
$this->assertNotEquals($oldSlug, $book->slug);
$this->assertDatabaseHas('slug_history', [
'sluggable_id' => $book->id,
'sluggable_type' => 'book',
'slug' => $oldSlug,
'parent_slug' => null,
]);
}
public function test_slugs_recorded_in_history_on_shelf_update()
{
$shelf = $this->entities->shelf();
$this->asAdmin()->put($shelf->getUrl(), [
'name' => 'new slug',
]);
$oldSlug = $shelf->slug;
$shelf->refresh();
$this->assertNotEquals($oldSlug, $shelf->slug);
$this->assertDatabaseHas('slug_history', [
'sluggable_id' => $shelf->id,
'sluggable_type' => 'bookshelf',
'slug' => $oldSlug,
'parent_slug' => null,
]);
}
}
| php | MIT | e6b754fad029d6c35e139b907d04e6510775997b | 2026-01-04T15:02:34.418809Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.