name: analyse-php
-on: [push, pull_request]
+on:
+ push:
+ paths:
+ - '**.php'
+ pull_request:
+ paths:
+ - '**.php'
jobs:
build:
name: lint-js
-on: [push, pull_request]
+on:
+ push:
+ paths:
+ - '**.js'
+ - '**.json'
+ pull_request:
+ paths:
+ - '**.js'
+ - '**.json'
jobs:
build:
name: lint-php
-on: [push, pull_request]
+on:
+ push:
+ paths:
+ - '**.php'
+ pull_request:
+ paths:
+ - '**.php'
jobs:
build:
name: test-migrations
-on: [push, pull_request]
+on:
+ push:
+ paths:
+ - '**.php'
+ - 'composer.*'
+ pull_request:
+ paths:
+ - '**.php'
+ - 'composer.*'
jobs:
build:
name: test-php
-on: [push, pull_request]
+on:
+ push:
+ paths:
+ - '**.php'
+ - 'composer.*'
+ pull_request:
+ paths:
+ - '**.php'
+ - 'composer.*'
jobs:
build:
$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());
+ }
}
--- /dev/null
+<?php
+
+namespace BookStack\App;
+
+class PwaManifestBuilder
+{
+ public function build(): array
+ {
+ $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" => "portrait",
+ "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"
+ ],
+ ],
+ ];
+ }
+}
--- /dev/null
+<?php
+
+namespace BookStack\Console\Commands;
+
+use BookStack\Users\Models\User;
+use Exception;
+use Illuminate\Console\Command;
+
+/**
+ * @mixin Command
+ */
+trait HandlesSingleUser
+{
+ /**
+ * Fetch a user provided to this command.
+ * Expects the command to accept 'id' and 'email' options.
+ * @throws Exception
+ */
+ private function fetchProvidedUser(): User
+ {
+ $id = $this->option('id');
+ $email = $this->option('email');
+ if (!$id && !$email) {
+ throw new Exception("Either a --id=<number> or --email=<email> option must be provided.\nRun this command with `--help` to show more options.");
+ }
+
+ $field = $id ? 'id' : 'email';
+ $value = $id ?: $email;
+
+ $user = User::query()
+ ->where($field, '=', $value)
+ ->first();
+
+ if (!$user) {
+ throw new Exception("A user where {$field}={$value} could not be found.");
+ }
+
+ return $user;
+ }
+}
--- /dev/null
+<?php
+
+namespace BookStack\Console\Commands;
+
+use BookStack\Users\Models\User;
+use Exception;
+use Illuminate\Console\Command;
+use BookStack\Uploads\UserAvatars;
+
+class RefreshAvatarCommand extends Command
+{
+ use HandlesSingleUser;
+
+ /**
+ * The name and signature of the console command.
+ *
+ * @var string
+ */
+ protected $signature = 'bookstack:refresh-avatar
+ {--id= : Numeric ID of the user to refresh avatar for}
+ {--email= : Email address of the user to refresh avatar for}
+ {--users-without-avatars : Refresh avatars for users that currently have no avatar}
+ {--a|all : Refresh avatars for all users}
+ {--f|force : Actually run the update, Defaults to a dry-run}';
+
+ /**
+ * The console command description.
+ *
+ * @var string
+ */
+ protected $description = 'Refresh avatar for the given user(s)';
+
+ public function handle(UserAvatars $userAvatar): int
+ {
+ if (!$userAvatar->avatarFetchEnabled()) {
+ $this->error("Avatar fetching is disabled on this instance.");
+ return self::FAILURE;
+ }
+
+ if ($this->option('users-without-avatars')) {
+ return $this->processUsers(User::query()->whereDoesntHave('avatar')->get()->all(), $userAvatar);
+ }
+
+ if ($this->option('all')) {
+ return $this->processUsers(User::query()->get()->all(), $userAvatar);
+ }
+
+ try {
+ $user = $this->fetchProvidedUser();
+ return $this->processUsers([$user], $userAvatar);
+ } catch (Exception $exception) {
+ $this->error($exception->getMessage());
+ return self::FAILURE;
+ }
+ }
+
+ /**
+ * @param User[] $users
+ */
+ private function processUsers(array $users, UserAvatars $userAvatar): int
+ {
+ $dryRun = !$this->option('force');
+ $this->info(count($users) . " user(s) found to update avatars for.");
+
+ if (count($users) === 0) {
+ return self::SUCCESS;
+ }
+
+ if (!$dryRun) {
+ $fetchHost = parse_url($userAvatar->getAvatarUrl(), PHP_URL_HOST);
+ $this->warn("This will destroy any existing avatar images these users have, and attempt to fetch new avatar images from {$fetchHost}.");
+ $proceed = !$this->input->isInteractive() || $this->confirm('Are you sure you want to proceed?');
+ if (!$proceed) {
+ return self::SUCCESS;
+ }
+ }
+
+ $this->info("");
+
+ $exitCode = self::SUCCESS;
+ foreach ($users as $user) {
+ $linePrefix = "[ID: {$user->id}] $user->email -";
+
+ if ($dryRun) {
+ $this->warn("{$linePrefix} Not updated");
+ continue;
+ }
+
+ if ($this->fetchAvatar($userAvatar, $user)) {
+ $this->info("{$linePrefix} Updated");
+ } else {
+ $this->error("{$linePrefix} Not updated");
+ $exitCode = self::FAILURE;
+ }
+ }
+
+ if ($dryRun) {
+ $this->comment("");
+ $this->comment("Dry run, no avatars were updated.");
+ $this->comment('Run with -f or --force to perform the update.');
+ }
+
+ return $exitCode;
+ }
+
+ private function fetchAvatar(UserAvatars $userAvatar, User $user): bool
+ {
+ $oldId = $user->avatar->id ?? 0;
+
+ $userAvatar->fetchAndAssignToUser($user);
+
+ $user->refresh();
+ $newId = $user->avatar->id ?? $oldId;
+ return $oldId !== $newId;
+ }
+}
namespace BookStack\Console\Commands;
-use BookStack\Users\Models\User;
+use Exception;
use Illuminate\Console\Command;
class ResetMfaCommand extends Command
{
+ use HandlesSingleUser;
+
/**
* The name and signature of the console command.
*
*/
public function handle(): int
{
- $id = $this->option('id');
- $email = $this->option('email');
- if (!$id && !$email) {
- $this->error('Either a --id=<number> or --email=<email> option must be provided.');
-
- return 1;
- }
-
- $field = $id ? 'id' : 'email';
- $value = $id ?: $email;
-
- /** @var User $user */
- $user = User::query()
- ->where($field, '=', $value)
- ->first();
-
- if (!$user) {
- $this->error("A user where {$field}={$value} could not be found.");
-
+ try {
+ $user = $this->fetchProvidedUser();
+ } catch (Exception $exception) {
+ $this->error($exception->getMessage());
return 1;
}
/**
* Returns book cover image, if book cover not exists return default cover image.
- *
- * @param int $width - Width of the image
- * @param int $height - Height of the image
- *
- * @return string
*/
- public function getBookCover($width = 440, $height = 250)
+ public function getBookCover(int $width = 440, int $height = 250): string
{
$default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
- if (!$this->image_id) {
+ if (!$this->image_id || !$this->cover) {
return $default;
}
try {
- $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
+ return $this->cover->getThumb($width, $height, false) ?? $default;
} catch (Exception $err) {
- $cover = $default;
+ return $default;
}
-
- return $cover;
}
/**
namespace BookStack\Entities\Models;
use BookStack\Uploads\Image;
+use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
}
/**
- * Returns BookShelf cover image, if cover does not exists return default cover image.
- *
- * @param int $width - Width of the image
- * @param int $height - Height of the image
- *
- * @return string
+ * Returns shelf cover image, if cover not exists return default cover image.
*/
- public function getBookCover($width = 440, $height = 250)
+ public function getBookCover(int $width = 440, int $height = 250): string
{
// TODO - Make generic, focused on books right now, Perhaps set-up a better image
$default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
- if (!$this->image_id) {
+ if (!$this->image_id || !$this->cover) {
return $default;
}
try {
- $cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
- } catch (\Exception $err) {
- $cover = $default;
+ return $this->cover->getThumb($width, $height, false) ?? $default;
+ } catch (Exception $err) {
+ return $default;
}
-
- return $cover;
}
/**
foreach ($imageTagsOutput[0] as $index => $imgMatch) {
$oldImgTagString = $imgMatch;
$srcString = $imageTagsOutput[2][$index];
- $imageEncoded = $this->imageService->imageUriToBase64($srcString);
+ $imageEncoded = $this->imageService->imageUrlToBase64($srcString);
if ($imageEncoded === null) {
$imageEncoded = $srcString;
}
* Converts the page contents into simple plain text.
* This method filters any bad looking content to provide a nice final output.
*/
- public function pageToPlainText(Page $page): string
+ public function pageToPlainText(Page $page, bool $pageRendered = false, bool $fromParent = false): string
{
- $html = (new PageContent($page))->render();
- $text = strip_tags($html);
+ $html = $pageRendered ? $page->html : (new PageContent($page))->render();
+ // Add proceeding spaces before tags so spaces remain between
+ // text within elements after stripping tags.
+ $html = str_replace('<', " <", $html);
+ $text = trim(strip_tags($html));
// Replace multiple spaces with single spaces
- $text = preg_replace('/\ {2,}/', ' ', $text);
+ $text = preg_replace('/ {2,}/', ' ', $text);
// Reduce multiple horrid whitespace characters.
$text = preg_replace('/(\x0A|\xA0|\x0A|\r|\n){2,}/su', "\n\n", $text);
$text = html_entity_decode($text);
// Add title
- $text = $page->name . "\n\n" . $text;
+ $text = $page->name . ($fromParent ? "\n" : "\n\n") . $text;
return $text;
}
*/
public function chapterToPlainText(Chapter $chapter): string
{
- $text = $chapter->name . "\n\n";
- $text .= $chapter->description . "\n\n";
+ $text = $chapter->name . "\n" . $chapter->description;
+ $text = trim($text) . "\n\n";
+
+ $parts = [];
foreach ($chapter->getVisiblePages() as $page) {
- $text .= $this->pageToPlainText($page);
+ $parts[] = $this->pageToPlainText($page, false, true);
}
- return $text;
+ return $text . implode("\n\n", $parts);
}
/**
*/
public function bookToPlainText(Book $book): string
{
- $bookTree = (new BookContents($book))->getTree(false, false);
- $text = $book->name . "\n\n";
+ $bookTree = (new BookContents($book))->getTree(false, true);
+ $text = $book->name . "\n" . $book->description;
+ $text = rtrim($text) . "\n\n";
+
+ $parts = [];
foreach ($bookTree as $bookChild) {
if ($bookChild->isA('chapter')) {
- $text .= $this->chapterToPlainText($bookChild);
+ $parts[] = $this->chapterToPlainText($bookChild);
} else {
- $text .= $this->pageToPlainText($bookChild);
+ $parts[] = $this->pageToPlainText($bookChild, true, true);
}
}
- return $text;
+ return $text . implode("\n\n", $parts);
}
/**
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
+use Illuminate\Http\Exceptions\PostTooLargeException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
+use Symfony\Component\ErrorHandler\Error\FatalError;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Throwable;
'password_confirmation',
];
+ /**
+ * A function to run upon out of memory.
+ * If it returns a response, that will be provided back to the request
+ * upon an out of memory event.
+ *
+ * @var ?callable<?\Illuminate\Http\Response>
+ */
+ protected $onOutOfMemory = null;
+
/**
* Report or log an exception.
*
*/
public function render($request, Throwable $e)
{
+ if ($e instanceof FatalError && str_contains($e->getMessage(), 'bytes exhausted (tried to allocate') && $this->onOutOfMemory) {
+ $response = call_user_func($this->onOutOfMemory);
+ if ($response) {
+ return $response;
+ }
+ }
+
+ if ($e instanceof PostTooLargeException) {
+ $e = new NotifyException(trans('errors.server_post_limit'), '/', 413);
+ }
+
if ($this->isApiRequest($request)) {
return $this->renderApiException($e);
}
return parent::render($request, $e);
}
+ /**
+ * Provide a function to be called when an out of memory event occurs.
+ * If the callable returns a response, this response will be returned
+ * to the request upon error.
+ */
+ public function prepareForOutOfMemory(callable $onOutOfMemory)
+ {
+ $this->onOutOfMemory = $onOutOfMemory;
+ }
+
+ /**
+ * Forget the current out of memory handler, if existing.
+ */
+ public function forgetOutOfMemoryHandler()
+ {
+ $this->onOutOfMemory = null;
+ }
+
/**
* Check if the given request is an API request.
*/
protected function isApiRequest(Request $request): bool
{
- return strpos($request->path(), 'api/') === 0;
+ return str_starts_with($request->path(), 'api/');
}
/**
$inputs = $request->only(['search', 'types', 'filters', 'exact', 'tags']);
$parsedStandardTerms = static::parseStandardTermString($inputs['search'] ?? '');
- $instance->searches = $parsedStandardTerms['terms'];
- $instance->exacts = $parsedStandardTerms['exacts'];
+ $instance->searches = array_filter($parsedStandardTerms['terms']);
+ $instance->exacts = array_filter($parsedStandardTerms['exacts']);
array_push($instance->exacts, ...array_filter($inputs['exact'] ?? []));
];
$patterns = [
- 'exacts' => '/"(.*?)"/',
+ 'exacts' => '/"((?:\\\\.|[^"\\\\])*)"/',
'tags' => '/\[(.*?)\]/',
'filters' => '/\{(.*?)\}/',
];
}
}
+ // Unescape exacts and backslash escapes
+ foreach ($terms['exacts'] as $index => $exact) {
+ $terms['exacts'][$index] = static::decodeEscapes($exact);
+ }
+
// Parse standard terms
$parsedStandardTerms = static::parseStandardTermString($searchString);
array_push($terms['searches'], ...$parsedStandardTerms['terms']);
}
$terms['filters'] = $splitFilters;
+ // Filter down terms where required
+ $terms['exacts'] = array_filter($terms['exacts']);
+ $terms['searches'] = array_filter($terms['searches']);
+
return $terms;
}
+ /**
+ * Decode backslash escaping within the input string.
+ */
+ protected static function decodeEscapes(string $input): string
+ {
+ $decoded = "";
+ $escaping = false;
+
+ foreach (str_split($input) as $char) {
+ if ($escaping) {
+ $decoded .= $char;
+ $escaping = false;
+ } else if ($char === '\\') {
+ $escaping = true;
+ } else {
+ $decoded .= $char;
+ }
+ }
+
+ return $decoded;
+ }
+
/**
* Parse a standard search term string into individual search terms and
- * extract any exact terms searches to be made.
+ * convert any required terms to exact matches. This is done since some
+ * characters will never be in the standard index, since we use them as
+ * delimiters, and therefore we convert a term to be exact if it
+ * contains one of those delimiter characters.
*
* @return array{terms: array<string>, exacts: array<string>}
*/
continue;
}
- $parsedList = (strpbrk($searchTerm, $indexDelimiters) === false) ? 'terms' : 'exacts';
- $parsed[$parsedList][] = $searchTerm;
+ $becomeExact = (strpbrk($searchTerm, $indexDelimiters) !== false);
+ $parsed[$becomeExact ? 'exacts' : 'terms'][] = $searchTerm;
}
return $parsed;
*/
public function toString(): string
{
- $string = implode(' ', $this->searches ?? []);
+ $parts = $this->searches;
foreach ($this->exacts as $term) {
- $string .= ' "' . $term . '"';
+ $escaped = str_replace('\\', '\\\\', $term);
+ $escaped = str_replace('"', '\"', $escaped);
+ $parts[] = '"' . $escaped . '"';
}
foreach ($this->tags as $term) {
- $string .= " [{$term}]";
+ $parts[] = "[{$term}]";
}
foreach ($this->filters as $filterName => $filterVal) {
- $string .= ' {' . $filterName . ($filterVal ? ':' . $filterVal : '') . '}';
+ $parts[] = '{' . $filterName . ($filterVal ? ':' . $filterVal : '') . '}';
}
- return $string;
+ return implode(' ', $parts);
}
}
use BookStack\Exceptions\ImageUploadException;
use BookStack\Http\Controller;
use BookStack\Uploads\ImageRepo;
+use BookStack\Uploads\ImageResizer;
+use BookStack\Util\OutOfMemoryHandler;
use Exception;
use Illuminate\Http\Request;
class DrawioImageController extends Controller
{
- protected $imageRepo;
-
- public function __construct(ImageRepo $imageRepo)
- {
- $this->imageRepo = $imageRepo;
+ public function __construct(
+ protected ImageRepo $imageRepo
+ ) {
}
/**
* Get a list of gallery images, in a list.
* Can be paged and filtered by entity.
*/
- public function list(Request $request)
+ public function list(Request $request, ImageResizer $resizer)
{
$page = $request->get('page', 1);
$searchTerm = $request->get('search', null);
$parentTypeFilter = $request->get('filter_type', null);
$imgData = $this->imageRepo->getEntityFiltered('drawio', $parentTypeFilter, $page, 24, $uploadedToFilter, $searchTerm);
-
- return view('pages.parts.image-manager-list', [
+ $viewData = [
+ 'warning' => '',
'images' => $imgData['images'],
'hasMore' => $imgData['has_more'],
- ]);
+ ];
+
+ new OutOfMemoryHandler(function () use ($viewData) {
+ $viewData['warning'] = trans('errors.image_gallery_thumbnail_memory_limit');
+ return response()->view('pages.parts.image-manager-list', $viewData, 200);
+ });
+
+ $resizer->loadGalleryThumbnailsForMany($imgData['images']);
+
+ return view('pages.parts.image-manager-list', $viewData);
}
/**
use BookStack\Exceptions\ImageUploadException;
use BookStack\Http\Controller;
use BookStack\Uploads\ImageRepo;
+use BookStack\Uploads\ImageResizer;
+use BookStack\Util\OutOfMemoryHandler;
use Illuminate\Http\Request;
+use Illuminate\Support\Facades\App;
+use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
class GalleryImageController extends Controller
* Get a list of gallery images, in a list.
* Can be paged and filtered by entity.
*/
- public function list(Request $request)
+ public function list(Request $request, ImageResizer $resizer)
{
$page = $request->get('page', 1);
$searchTerm = $request->get('search', null);
$parentTypeFilter = $request->get('filter_type', null);
$imgData = $this->imageRepo->getEntityFiltered('gallery', $parentTypeFilter, $page, 30, $uploadedToFilter, $searchTerm);
-
- return view('pages.parts.image-manager-list', [
+ $viewData = [
+ 'warning' => '',
'images' => $imgData['images'],
'hasMore' => $imgData['has_more'],
- ]);
+ ];
+
+ new OutOfMemoryHandler(function () use ($viewData) {
+ $viewData['warning'] = trans('errors.image_gallery_thumbnail_memory_limit');
+ return response()->view('pages.parts.image-manager-list', $viewData, 200);
+ });
+
+ $resizer->loadGalleryThumbnailsForMany($imgData['images']);
+
+ return view('pages.parts.image-manager-list', $viewData);
}
/**
return $this->jsonError(implode("\n", $exception->errors()['file']));
}
+ new OutOfMemoryHandler(function () {
+ return $this->jsonError(trans('errors.image_upload_memory_limit'));
+ });
+
try {
$imageUpload = $request->file('file');
$uploadedTo = $request->get('uploaded_to', 0);
use BookStack\Exceptions\ImageUploadException;
use BookStack\Exceptions\NotFoundException;
+use BookStack\Exceptions\NotifyException;
use BookStack\Http\Controller;
use BookStack\Uploads\Image;
use BookStack\Uploads\ImageRepo;
+use BookStack\Uploads\ImageResizer;
use BookStack\Uploads\ImageService;
+use BookStack\Util\OutOfMemoryHandler;
use Exception;
use Illuminate\Http\Request;
-use Illuminate\Validation\ValidationException;
class ImageController extends Controller
{
public function __construct(
protected ImageRepo $imageRepo,
- protected ImageService $imageService
+ protected ImageService $imageService,
+ protected ImageResizer $imageResizer,
) {
}
/**
* Update image details.
- *
- * @throws ImageUploadException
- * @throws ValidationException
*/
public function update(Request $request, string $id)
{
- $this->validate($request, [
+ $data = $this->validate($request, [
'name' => ['required', 'min:2', 'string'],
]);
$this->checkImagePermission($image);
$this->checkOwnablePermission('image-update', $image);
- $image = $this->imageRepo->updateImageDetails($image, $request->all());
-
- $this->imageRepo->loadThumbs($image);
+ $image = $this->imageRepo->updateImageDetails($image, $data);
return view('pages.parts.image-manager-form', [
'image' => $image,
$this->checkOwnablePermission('image-update', $image);
$file = $request->file('file');
+ new OutOfMemoryHandler(function () {
+ return $this->jsonError(trans('errors.image_upload_memory_limit'));
+ });
+
try {
$this->imageRepo->updateImageFile($image, $file);
} catch (ImageUploadException $exception) {
$dependantPages = $this->imageRepo->getPagesUsingImage($image);
}
- $this->imageRepo->loadThumbs($image);
-
- return view('pages.parts.image-manager-form', [
+ $viewData = [
'image' => $image,
'dependantPages' => $dependantPages ?? null,
- ]);
+ 'warning' => '',
+ ];
+
+ new OutOfMemoryHandler(function () use ($viewData) {
+ $viewData['warning'] = trans('errors.image_thumbnail_memory_limit');
+ return response()->view('pages.parts.image-manager-form', $viewData);
+ });
+
+ $this->imageResizer->loadGalleryThumbnailsForImage($image, false);
+
+ return view('pages.parts.image-manager-form', $viewData);
}
/**
return response('');
}
+ /**
+ * Rebuild the thumbnails for the given image.
+ */
+ public function rebuildThumbnails(string $id)
+ {
+ $image = $this->imageRepo->getById($id);
+ $this->checkImagePermission($image);
+ $this->checkOwnablePermission('image-update', $image);
+
+ new OutOfMemoryHandler(function () {
+ return $this->jsonError(trans('errors.image_thumbnail_memory_limit'));
+ });
+
+ $this->imageResizer->loadGalleryThumbnailsForImage($image, true);
+
+ return response(trans('components.image_rebuild_thumbs_success'));
+ }
+
/**
* Check related page permission and ensure type is drawio or gallery.
+ * @throws NotifyException
*/
- protected function checkImagePermission(Image $image)
+ protected function checkImagePermission(Image $image): void
{
if ($image->type !== 'drawio' && $image->type !== 'gallery') {
$this->showPermissionError();
use BookStack\Http\ApiController;
use BookStack\Uploads\Image;
use BookStack\Uploads\ImageRepo;
+use BookStack\Uploads\ImageResizer;
use Illuminate\Http\Request;
class ImageGalleryApiController extends ApiController
];
public function __construct(
- protected ImageRepo $imageRepo
+ protected ImageRepo $imageRepo,
+ protected ImageResizer $imageResizer,
) {
}
*/
protected function formatForSingleResponse(Image $image): array
{
- $this->imageRepo->loadThumbs($image);
+ $this->imageResizer->loadGalleryThumbnailsForImage($image, false);
$data = $image->toArray();
$data['created_by'] = $image->createdBy;
$data['updated_by'] = $image->updatedBy;
$escapedUrl = htmlentities($image->url);
$escapedName = htmlentities($image->name);
+
if ($image->type === 'drawio') {
$data['content']['html'] = "<div drawio-diagram=\"{$image->id}\"><img src=\"{$escapedUrl}\"></div>";
$data['content']['markdown'] = $data['content']['html'];
}
/**
- * Get a thumbnail for this image.
+ * Get a thumbnail URL for this image.
+ * Attempts to generate the thumbnail if not already existing.
*
* @throws \Exception
*/
- public function getThumb(?int $width, ?int $height, bool $keepRatio = false): string
+ public function getThumb(?int $width, ?int $height, bool $keepRatio = false): ?string
{
- return app()->make(ImageService::class)->getThumbnail($this, $width, $height, $keepRatio);
+ return app()->make(ImageResizer::class)->resizeToThumbnailUrl($this, $width, $height, $keepRatio, false);
}
/**
{
public function __construct(
protected ImageService $imageService,
- protected PermissionApplicator $permissions
+ protected PermissionApplicator $permissions,
+ protected ImageResizer $imageResizer,
) {
}
* Execute a paginated query, returning in a standard format.
* Also runs the query through the restriction system.
*/
- private function returnPaginated($query, $page = 1, $pageSize = 24): array
+ protected function returnPaginated(Builder $query, int $page = 1, int $pageSize = 24): array
{
$images = $query->orderBy('created_at', 'desc')->skip($pageSize * ($page - 1))->take($pageSize + 1)->get();
- $hasMore = count($images) > $pageSize;
-
- $returnImages = $images->take($pageSize);
- $returnImages->each(function (Image $image) {
- $this->loadThumbs($image);
- });
return [
- 'images' => $returnImages,
- 'has_more' => $hasMore,
+ 'images' => $images->take($pageSize),
+ 'has_more' => count($images) > $pageSize,
];
}
$image = $this->imageService->saveNewFromUpload($uploadFile, $type, $uploadedTo, $resizeWidth, $resizeHeight, $keepRatio);
if ($type !== 'system') {
- $this->loadThumbs($image);
+ $this->imageResizer->loadGalleryThumbnailsForImage($image, true);
}
return $image;
public function saveNewFromData(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
{
$image = $this->imageService->saveNew($imageName, $imageData, $type, $uploadedTo);
- $this->loadThumbs($image);
+ $this->imageResizer->loadGalleryThumbnailsForImage($image, true);
return $image;
}
$image->fill($updateDetails);
$image->updated_by = user()->id;
$image->save();
- $this->loadThumbs($image);
+ $this->imageResizer->loadGalleryThumbnailsForImage($image, false);
return $image;
}
$image->updated_by = user()->id;
$image->touch();
$image->save();
+
$this->imageService->replaceExistingFromUpload($image->path, $image->type, $file);
- $this->loadThumbs($image, true);
+ $this->imageResizer->loadGalleryThumbnailsForImage($image, true);
}
/**
}
}
- /**
- * Load thumbnails onto an image object.
- */
- public function loadThumbs(Image $image, bool $forceCreate = false): void
- {
- $image->setAttribute('thumbs', [
- 'gallery' => $this->getThumbnail($image, 150, 150, false, $forceCreate),
- 'display' => $this->getThumbnail($image, 1680, null, true, $forceCreate),
- ]);
- }
-
- /**
- * Get the thumbnail for an image.
- * If $keepRatio is true only the width will be used.
- * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
- */
- protected function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio, bool $forceCreate): ?string
- {
- try {
- return $this->imageService->getThumbnail($image, $width, $height, $keepRatio, $forceCreate);
- } catch (Exception $exception) {
- return null;
- }
- }
-
/**
* Get the raw image data from an Image.
*/
--- /dev/null
+<?php
+
+namespace BookStack\Uploads;
+
+use BookStack\Exceptions\ImageUploadException;
+use Exception;
+use GuzzleHttp\Psr7\Utils;
+use Illuminate\Support\Facades\Cache;
+use Intervention\Image\Image as InterventionImage;
+use Intervention\Image\ImageManager;
+
+class ImageResizer
+{
+ protected const THUMBNAIL_CACHE_TIME = 604_800; // 1 week
+
+ public function __construct(
+ protected ImageManager $intervention,
+ protected ImageStorage $storage,
+ ) {
+ }
+
+ /**
+ * Load gallery thumbnails for a set of images.
+ * @param iterable<Image> $images
+ */
+ public function loadGalleryThumbnailsForMany(iterable $images, bool $shouldCreate = false): void
+ {
+ foreach ($images as $image) {
+ $this->loadGalleryThumbnailsForImage($image, $shouldCreate);
+ }
+ }
+
+ /**
+ * Load gallery thumbnails into the given image instance.
+ */
+ public function loadGalleryThumbnailsForImage(Image $image, bool $shouldCreate): void
+ {
+ $thumbs = ['gallery' => null, 'display' => null];
+
+ try {
+ $thumbs['gallery'] = $this->resizeToThumbnailUrl($image, 150, 150, false, $shouldCreate);
+ $thumbs['display'] = $this->resizeToThumbnailUrl($image, 1680, null, true, $shouldCreate);
+ } catch (Exception $exception) {
+ // Prevent thumbnail errors from stopping execution
+ }
+
+ $image->setAttribute('thumbs', $thumbs);
+ }
+
+ /**
+ * Get the thumbnail for an image.
+ * If $keepRatio is true only the width will be used.
+ * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
+ *
+ * @throws Exception
+ */
+ public function resizeToThumbnailUrl(
+ Image $image,
+ ?int $width,
+ ?int $height,
+ bool $keepRatio = false,
+ bool $shouldCreate = false
+ ): ?string {
+ // Do not resize GIF images where we're not cropping
+ if ($keepRatio && $this->isGif($image)) {
+ return $this->storage->getPublicUrl($image->path);
+ }
+
+ $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
+ $imagePath = $image->path;
+ $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
+
+ $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
+
+ // Return path if in cache
+ $cachedThumbPath = Cache::get($thumbCacheKey);
+ if ($cachedThumbPath && !$shouldCreate) {
+ return $this->storage->getPublicUrl($cachedThumbPath);
+ }
+
+ // If thumbnail has already been generated, serve that and cache path
+ $disk = $this->storage->getDisk($image->type);
+ if (!$shouldCreate && $disk->exists($thumbFilePath)) {
+ Cache::put($thumbCacheKey, $thumbFilePath, static::THUMBNAIL_CACHE_TIME);
+
+ return $this->storage->getPublicUrl($thumbFilePath);
+ }
+
+ $imageData = $disk->get($imagePath);
+
+ // Do not resize apng images where we're not cropping
+ if ($keepRatio && $this->isApngData($image, $imageData)) {
+ Cache::put($thumbCacheKey, $image->path, static::THUMBNAIL_CACHE_TIME);
+
+ return $this->storage->getPublicUrl($image->path);
+ }
+
+ // If not in cache and thumbnail does not exist, generate thumb and cache path
+ $thumbData = $this->resizeImageData($imageData, $width, $height, $keepRatio);
+ $disk->put($thumbFilePath, $thumbData, true);
+ Cache::put($thumbCacheKey, $thumbFilePath, static::THUMBNAIL_CACHE_TIME);
+
+ return $this->storage->getPublicUrl($thumbFilePath);
+ }
+
+ /**
+ * Resize the image of given data to the specified size, and return the new image data.
+ *
+ * @throws ImageUploadException
+ */
+ public function resizeImageData(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
+ {
+ try {
+ $thumb = $this->intervention->make($imageData);
+ } catch (Exception $e) {
+ throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
+ }
+
+ $this->orientImageToOriginalExif($thumb, $imageData);
+
+ if ($keepRatio) {
+ $thumb->resize($width, $height, function ($constraint) {
+ $constraint->aspectRatio();
+ $constraint->upsize();
+ });
+ } else {
+ $thumb->fit($width, $height);
+ }
+
+ $thumbData = (string) $thumb->encode();
+
+ // Use original image data if we're keeping the ratio
+ // and the resizing does not save any space.
+ if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
+ return $imageData;
+ }
+
+ return $thumbData;
+ }
+
+ /**
+ * Orientate the given intervention image based upon the given original image data.
+ * Intervention does have an `orientate` method but the exif data it needs is lost before it
+ * can be used (At least when created using binary string data) so we need to do some
+ * implementation on our side to use the original image data.
+ * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php
+ * Copyright (c) Oliver Vogel, MIT License.
+ */
+ protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void
+ {
+ if (!extension_loaded('exif')) {
+ return;
+ }
+
+ $stream = Utils::streamFor($originalData)->detach();
+ $exif = @exif_read_data($stream);
+ $orientation = $exif ? ($exif['Orientation'] ?? null) : null;
+
+ switch ($orientation) {
+ case 2:
+ $image->flip();
+ break;
+ case 3:
+ $image->rotate(180);
+ break;
+ case 4:
+ $image->rotate(180)->flip();
+ break;
+ case 5:
+ $image->rotate(270)->flip();
+ break;
+ case 6:
+ $image->rotate(270);
+ break;
+ case 7:
+ $image->rotate(90)->flip();
+ break;
+ case 8:
+ $image->rotate(90);
+ break;
+ }
+ }
+
+ /**
+ * Checks if the image is a gif. Returns true if it is, else false.
+ */
+ protected function isGif(Image $image): bool
+ {
+ return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
+ }
+
+ /**
+ * Check if the given image and image data is apng.
+ */
+ protected function isApngData(Image $image, string &$imageData): bool
+ {
+ $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
+ if (!$isPng) {
+ return false;
+ }
+
+ $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
+
+ return str_contains($initialHeader, 'acTL');
+ }
+}
use BookStack\Entities\Models\Bookshelf;
use BookStack\Entities\Models\Page;
use BookStack\Exceptions\ImageUploadException;
-use ErrorException;
use Exception;
-use GuzzleHttp\Psr7\Utils;
-use Illuminate\Contracts\Cache\Repository as Cache;
-use Illuminate\Contracts\Filesystem\FileNotFoundException;
-use Illuminate\Contracts\Filesystem\Filesystem as Storage;
-use Illuminate\Filesystem\FilesystemAdapter;
-use Illuminate\Filesystem\FilesystemManager;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
-use Intervention\Image\Exception\NotSupportedException;
-use Intervention\Image\Image as InterventionImage;
-use Intervention\Image\ImageManager;
-use League\Flysystem\WhitespacePathNormalizer;
-use Psr\SimpleCache\InvalidArgumentException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ImageService
{
- protected ImageManager $imageTool;
- protected Cache $cache;
- protected FilesystemManager $fileSystem;
-
protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
- public function __construct(ImageManager $imageTool, FilesystemManager $fileSystem, Cache $cache)
- {
- $this->imageTool = $imageTool;
- $this->fileSystem = $fileSystem;
- $this->cache = $cache;
- }
-
- /**
- * Get the storage that will be used for storing images.
- */
- protected function getStorageDisk(string $imageType = ''): Storage
- {
- return $this->fileSystem->disk($this->getStorageDiskName($imageType));
- }
-
- /**
- * Check if local secure image storage (Fetched behind authentication)
- * is currently active in the instance.
- */
- protected function usingSecureImages(string $imageType = 'gallery'): bool
- {
- return $this->getStorageDiskName($imageType) === 'local_secure_images';
- }
-
- /**
- * Check if "local secure restricted" (Fetched behind auth, with permissions enforced)
- * is currently active in the instance.
- */
- protected function usingSecureRestrictedImages()
- {
- return config('filesystems.images') === 'local_secure_restricted';
- }
-
- /**
- * Change the originally provided path to fit any disk-specific requirements.
- * This also ensures the path is kept to the expected root folders.
- */
- protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
- {
- $path = (new WhitespacePathNormalizer())->normalizePath(str_replace('uploads/images/', '', $path));
-
- if ($this->usingSecureImages($imageType)) {
- return $path;
- }
-
- return 'uploads/images/' . $path;
- }
-
- /**
- * Get the name of the storage disk to use.
- */
- protected function getStorageDiskName(string $imageType): string
- {
- $storageType = config('filesystems.images');
- $localSecureInUse = ($storageType === 'local_secure' || $storageType === 'local_secure_restricted');
-
- // Ensure system images (App logo) are uploaded to a public space
- if ($imageType === 'system' && $localSecureInUse) {
- return 'local';
- }
-
- // Rename local_secure options to get our image specific storage driver which
- // is scoped to the relevant image directories.
- if ($localSecureInUse) {
- return 'local_secure_images';
- }
-
- return $storageType;
+ public function __construct(
+ protected ImageStorage $storage,
+ protected ImageResizer $resizer,
+ ) {
}
/**
* Saves a new image from an upload.
*
* @throws ImageUploadException
- *
- * @return mixed
*/
public function saveNewFromUpload(
UploadedFile $uploadedFile,
int $resizeWidth = null,
int $resizeHeight = null,
bool $keepRatio = true
- ) {
+ ): Image {
$imageName = $uploadedFile->getClientOriginalName();
$imageData = file_get_contents($uploadedFile->getRealPath());
if ($resizeWidth !== null || $resizeHeight !== null) {
- $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
+ $imageData = $this->resizer->resizeImageData($imageData, $resizeWidth, $resizeHeight, $keepRatio);
}
return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
*/
public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
{
- $storage = $this->getStorageDisk($type);
+ $disk = $this->storage->getDisk($type);
$secureUploads = setting('app-secure-images');
- $fileName = $this->cleanImageFileName($imageName);
+ $fileName = $this->storage->cleanImageFileName($imageName);
$imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
- while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
+ while ($disk->exists($imagePath . $fileName)) {
$fileName = Str::random(3) . $fileName;
}
}
try {
- $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
+ $disk->put($fullPath, $imageData, true);
} catch (Exception $e) {
Log::error('Error when attempting image upload:' . $e->getMessage());
$imageDetails = [
'name' => $imageName,
'path' => $fullPath,
- 'url' => $this->getPublicUrl($fullPath),
+ 'url' => $this->storage->getPublicUrl($fullPath),
'type' => $type,
'uploaded_to' => $uploadedTo,
];
return $image;
}
- public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void
- {
- $imageData = file_get_contents($file->getRealPath());
- $storage = $this->getStorageDisk($type);
- $adjustedPath = $this->adjustPathForStorageDisk($path, $type);
- $storage->put($adjustedPath, $imageData);
- }
-
- /**
- * Save image data for the given path in the public space, if possible,
- * for the provided storage mechanism.
- */
- protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
- {
- $storage->put($path, $data);
-
- // Set visibility when a non-AWS-s3, s3-like storage option is in use.
- // Done since this call can break s3-like services but desired for other image stores.
- // Attempting to set ACL during above put request requires different permissions
- // hence would technically be a breaking change for actual s3 usage.
- $usingS3 = strtolower(config('filesystems.images')) === 's3';
- $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
- if (!$usingS3Like) {
- $storage->setVisibility($path, 'public');
- }
- }
-
- /**
- * Clean up an image file name to be both URL and storage safe.
- */
- protected function cleanImageFileName(string $name): string
- {
- $name = str_replace(' ', '-', $name);
- $nameParts = explode('.', $name);
- $extension = array_pop($nameParts);
- $name = implode('-', $nameParts);
- $name = Str::slug($name);
-
- if (strlen($name) === 0) {
- $name = Str::random(10);
- }
-
- return $name . '.' . $extension;
- }
-
- /**
- * Checks if the image is a gif. Returns true if it is, else false.
- */
- protected function isGif(Image $image): bool
- {
- return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
- }
-
- /**
- * Check if the given image and image data is apng.
- */
- protected function isApngData(Image $image, string &$imageData): bool
- {
- $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
- if (!$isPng) {
- return false;
- }
-
- $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
-
- return strpos($initialHeader, 'acTL') !== false;
- }
-
/**
- * Get the thumbnail for an image.
- * If $keepRatio is true only the width will be used.
- * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
- *
- * @throws Exception
- * @throws InvalidArgumentException
+ * Replace an existing image file in the system using the given file.
*/
- public function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio = false, bool $forceCreate = false): string
- {
- // Do not resize GIF images where we're not cropping
- if ($keepRatio && $this->isGif($image)) {
- return $this->getPublicUrl($image->path);
- }
-
- $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
- $imagePath = $image->path;
- $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
-
- $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
-
- // Return path if in cache
- $cachedThumbPath = $this->cache->get($thumbCacheKey);
- if ($cachedThumbPath && !$forceCreate) {
- return $this->getPublicUrl($cachedThumbPath);
- }
-
- // If thumbnail has already been generated, serve that and cache path
- $storage = $this->getStorageDisk($image->type);
- if (!$forceCreate && $storage->exists($this->adjustPathForStorageDisk($thumbFilePath, $image->type))) {
- $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
-
- return $this->getPublicUrl($thumbFilePath);
- }
-
- $imageData = $storage->get($this->adjustPathForStorageDisk($imagePath, $image->type));
-
- // Do not resize apng images where we're not cropping
- if ($keepRatio && $this->isApngData($image, $imageData)) {
- $this->cache->put($thumbCacheKey, $image->path, 60 * 60 * 72);
-
- return $this->getPublicUrl($image->path);
- }
-
- // If not in cache and thumbnail does not exist, generate thumb and cache path
- $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
- $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
- $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
-
- return $this->getPublicUrl($thumbFilePath);
- }
-
- /**
- * Resize the image of given data to the specified size, and return the new image data.
- *
- * @throws ImageUploadException
- */
- protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
- {
- try {
- $thumb = $this->imageTool->make($imageData);
- } catch (ErrorException | NotSupportedException $e) {
- throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
- }
-
- $this->orientImageToOriginalExif($thumb, $imageData);
-
- if ($keepRatio) {
- $thumb->resize($width, $height, function ($constraint) {
- $constraint->aspectRatio();
- $constraint->upsize();
- });
- } else {
- $thumb->fit($width, $height);
- }
-
- $thumbData = (string) $thumb->encode();
-
- // Use original image data if we're keeping the ratio
- // and the resizing does not save any space.
- if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
- return $imageData;
- }
-
- return $thumbData;
- }
-
- /**
- * Orientate the given intervention image based upon the given original image data.
- * Intervention does have an `orientate` method but the exif data it needs is lost before it
- * can be used (At least when created using binary string data) so we need to do some
- * implementation on our side to use the original image data.
- * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php
- * Copyright (c) Oliver Vogel, MIT License.
- */
- protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void
+ public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void
{
- if (!extension_loaded('exif')) {
- return;
- }
-
- $stream = Utils::streamFor($originalData)->detach();
- $exif = @exif_read_data($stream);
- $orientation = $exif ? ($exif['Orientation'] ?? null) : null;
-
- switch ($orientation) {
- case 2:
- $image->flip();
- break;
- case 3:
- $image->rotate(180);
- break;
- case 4:
- $image->rotate(180)->flip();
- break;
- case 5:
- $image->rotate(270)->flip();
- break;
- case 6:
- $image->rotate(270);
- break;
- case 7:
- $image->rotate(90)->flip();
- break;
- case 8:
- $image->rotate(90);
- break;
- }
+ $imageData = file_get_contents($file->getRealPath());
+ $disk = $this->storage->getDisk($type);
+ $disk->put($path, $imageData);
}
/**
* Get the raw data content from an image.
*
- * @throws FileNotFoundException
+ * @throws Exception
*/
public function getImageData(Image $image): string
{
- $storage = $this->getStorageDisk();
+ $disk = $this->storage->getDisk();
- return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
+ return $disk->get($image->path);
}
/**
*
* @throws Exception
*/
- public function destroy(Image $image)
+ public function destroy(Image $image): void
{
- $this->destroyImagesFromPath($image->path, $image->type);
+ $disk = $this->storage->getDisk($image->type);
+ $disk->destroyAllMatchingNameFromPath($image->path);
$image->delete();
}
- /**
- * Destroys an image at the given path.
- * Searches for image thumbnails in addition to main provided path.
- */
- protected function destroyImagesFromPath(string $path, string $imageType): bool
- {
- $path = $this->adjustPathForStorageDisk($path, $imageType);
- $storage = $this->getStorageDisk($imageType);
-
- $imageFolder = dirname($path);
- $imageFileName = basename($path);
- $allImages = collect($storage->allFiles($imageFolder));
-
- // Delete image files
- $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
- return basename($imagePath) === $imageFileName;
- });
- $storage->delete($imagesToDelete->all());
-
- // Cleanup of empty folders
- $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
- foreach ($foldersInvolved as $directory) {
- if ($this->isFolderEmpty($storage, $directory)) {
- $storage->deleteDirectory($directory);
- }
- }
-
- return true;
- }
-
- /**
- * Check whether a folder is empty.
- */
- protected function isFolderEmpty(Storage $storage, string $path): bool
- {
- $files = $storage->files($path);
- $folders = $storage->directories($path);
-
- return count($files) === 0 && count($folders) === 0;
- }
-
/**
* Delete gallery and drawings that are not within HTML content of pages or page revisions.
* Checks based off of only the image name.
*
* Returns the path of the images that would be/have been deleted.
*/
- public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
+ public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true): array
{
$types = ['gallery', 'drawio'];
$deletedPaths = [];
* Attempts to convert the URL to a system storage url then
* fetch the data from the disk or storage location.
* Returns null if the image data cannot be fetched from storage.
- *
- * @throws FileNotFoundException
*/
- public function imageUriToBase64(string $uri): ?string
+ public function imageUrlToBase64(string $url): ?string
{
- $storagePath = $this->imageUrlToStoragePath($uri);
- if (empty($uri) || is_null($storagePath)) {
+ $storagePath = $this->storage->urlToPath($url);
+ if (empty($url) || is_null($storagePath)) {
return null;
}
- $storagePath = $this->adjustPathForStorageDisk($storagePath);
-
// Apply access control when local_secure_restricted images are active
- if ($this->usingSecureRestrictedImages()) {
+ if ($this->storage->usingSecureRestrictedImages()) {
if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
return null;
}
}
- $storage = $this->getStorageDisk();
+ $disk = $this->storage->getDisk();
$imageData = null;
- if ($storage->exists($storagePath)) {
- $imageData = $storage->get($storagePath);
+ if ($disk->exists($storagePath)) {
+ $imageData = $disk->get($storagePath);
}
if (is_null($imageData)) {
return null;
}
- $extension = pathinfo($uri, PATHINFO_EXTENSION);
+ $extension = pathinfo($url, PATHINFO_EXTENSION);
if ($extension === 'svg') {
$extension = 'svg+xml';
}
*/
public function pathAccessibleInLocalSecure(string $imagePath): bool
{
- /** @var FilesystemAdapter $disk */
- $disk = $this->getStorageDisk('gallery');
+ $disk = $this->storage->getDisk('gallery');
- if ($this->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
+ if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
return false;
}
// Check local_secure is active
- return $this->usingSecureImages()
- && $disk instanceof FilesystemAdapter
+ return $disk->usingSecureImages()
// Check the image file exists
&& $disk->exists($imagePath)
// Check the file is likely an image file
- && strpos($disk->mimeType($imagePath), 'image/') === 0;
+ && str_starts_with($disk->mimeType($imagePath), 'image/');
}
/**
*/
protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
{
- if (strpos($path, '/uploads/images/') === 0) {
+ if (str_starts_with($path, 'uploads/images/')) {
$path = substr($path, 15);
}
// Strip thumbnail element from path if existing
$originalPathSplit = array_filter(explode('/', $path), function (string $part) {
- $resizedDir = (strpos($part, 'thumbs-') === 0 || strpos($part, 'scaled-') === 0);
- $missingExtension = strpos($part, '.') === false;
+ $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
+ $missingExtension = !str_contains($part, '.');
return !($resizedDir && $missingExtension);
});
*/
public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
{
- $disk = $this->getStorageDisk($imageType);
+ $disk = $this->storage->getDisk($imageType);
return $disk->response($path);
}
{
return in_array($extension, static::$supportedExtensions);
}
-
- /**
- * Get a storage path for the given image URL.
- * Ensures the path will start with "uploads/images".
- * Returns null if the url cannot be resolved to a local URL.
- */
- private function imageUrlToStoragePath(string $url): ?string
- {
- $url = ltrim(trim($url), '/');
-
- // Handle potential relative paths
- $isRelative = strpos($url, 'http') !== 0;
- if ($isRelative) {
- if (strpos(strtolower($url), 'uploads/images') === 0) {
- return trim($url, '/');
- }
-
- return null;
- }
-
- // Handle local images based on paths on the same domain
- $potentialHostPaths = [
- url('uploads/images/'),
- $this->getPublicUrl('/uploads/images/'),
- ];
-
- foreach ($potentialHostPaths as $potentialBasePath) {
- $potentialBasePath = strtolower($potentialBasePath);
- if (strpos(strtolower($url), $potentialBasePath) === 0) {
- return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
- }
- }
-
- return null;
- }
-
- /**
- * Gets a public facing url for an image by checking relevant environment variables.
- * If s3-style store is in use it will default to guessing a public bucket URL.
- */
- private function getPublicUrl(string $filePath): string
- {
- $storageUrl = config('filesystems.url');
-
- // Get the standard public s3 url if s3 is set as storage type
- // Uses the nice, short URL if bucket name has no periods in otherwise the longer
- // region-based url will be used to prevent http issues.
- if (!$storageUrl && config('filesystems.images') === 's3') {
- $storageDetails = config('filesystems.disks.s3');
- if (strpos($storageDetails['bucket'], '.') === false) {
- $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
- } else {
- $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
- }
- }
-
- $basePath = $storageUrl ?: url('/');
-
- return rtrim($basePath, '/') . $filePath;
- }
}
--- /dev/null
+<?php
+
+namespace BookStack\Uploads;
+
+use Illuminate\Filesystem\FilesystemManager;
+use Illuminate\Support\Str;
+
+class ImageStorage
+{
+ public function __construct(
+ protected FilesystemManager $fileSystem,
+ ) {
+ }
+
+ /**
+ * Get the storage disk for the given image type.
+ */
+ public function getDisk(string $imageType = ''): ImageStorageDisk
+ {
+ $diskName = $this->getDiskName($imageType);
+
+ return new ImageStorageDisk(
+ $diskName,
+ $this->fileSystem->disk($diskName),
+ );
+ }
+
+ /**
+ * Check if "local secure restricted" (Fetched behind auth, with permissions enforced)
+ * is currently active in the instance.
+ */
+ public function usingSecureRestrictedImages(): bool
+ {
+ return config('filesystems.images') === 'local_secure_restricted';
+ }
+
+ /**
+ * Clean up an image file name to be both URL and storage safe.
+ */
+ public function cleanImageFileName(string $name): string
+ {
+ $name = str_replace(' ', '-', $name);
+ $nameParts = explode('.', $name);
+ $extension = array_pop($nameParts);
+ $name = implode('-', $nameParts);
+ $name = Str::slug($name);
+
+ if (strlen($name) === 0) {
+ $name = Str::random(10);
+ }
+
+ return $name . '.' . $extension;
+ }
+
+ /**
+ * Get the name of the storage disk to use.
+ */
+ protected function getDiskName(string $imageType): string
+ {
+ $storageType = strtolower(config('filesystems.images'));
+ $localSecureInUse = ($storageType === 'local_secure' || $storageType === 'local_secure_restricted');
+
+ // Ensure system images (App logo) are uploaded to a public space
+ if ($imageType === 'system' && $localSecureInUse) {
+ return 'local';
+ }
+
+ // Rename local_secure options to get our image specific storage driver which
+ // is scoped to the relevant image directories.
+ if ($localSecureInUse) {
+ return 'local_secure_images';
+ }
+
+ return $storageType;
+ }
+
+ /**
+ * Get a storage path for the given image URL.
+ * Ensures the path will start with "uploads/images".
+ * Returns null if the url cannot be resolved to a local URL.
+ */
+ public function urlToPath(string $url): ?string
+ {
+ $url = ltrim(trim($url), '/');
+
+ // Handle potential relative paths
+ $isRelative = !str_starts_with($url, 'http');
+ if ($isRelative) {
+ if (str_starts_with(strtolower($url), 'uploads/images')) {
+ return trim($url, '/');
+ }
+
+ return null;
+ }
+
+ // Handle local images based on paths on the same domain
+ $potentialHostPaths = [
+ url('uploads/images/'),
+ $this->getPublicUrl('/uploads/images/'),
+ ];
+
+ foreach ($potentialHostPaths as $potentialBasePath) {
+ $potentialBasePath = strtolower($potentialBasePath);
+ if (str_starts_with(strtolower($url), $potentialBasePath)) {
+ return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Gets a public facing url for an image by checking relevant environment variables.
+ * If s3-style store is in use it will default to guessing a public bucket URL.
+ */
+ public function getPublicUrl(string $filePath): string
+ {
+ $storageUrl = config('filesystems.url');
+
+ // Get the standard public s3 url if s3 is set as storage type
+ // Uses the nice, short URL if bucket name has no periods in otherwise the longer
+ // region-based url will be used to prevent http issues.
+ if (!$storageUrl && config('filesystems.images') === 's3') {
+ $storageDetails = config('filesystems.disks.s3');
+ if (!str_contains($storageDetails['bucket'], '.')) {
+ $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
+ } else {
+ $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
+ }
+ }
+
+ $basePath = $storageUrl ?: url('/');
+
+ return rtrim($basePath, '/') . $filePath;
+ }
+}
--- /dev/null
+<?php
+
+namespace BookStack\Uploads;
+
+use Illuminate\Contracts\Filesystem\Filesystem;
+use Illuminate\Filesystem\FilesystemAdapter;
+use League\Flysystem\WhitespacePathNormalizer;
+use Symfony\Component\HttpFoundation\StreamedResponse;
+
+class ImageStorageDisk
+{
+ public function __construct(
+ protected string $diskName,
+ protected Filesystem $filesystem,
+ ) {
+ }
+
+ /**
+ * Check if local secure image storage (Fetched behind authentication)
+ * is currently active in the instance.
+ */
+ public function usingSecureImages(): bool
+ {
+ return $this->diskName === 'local_secure_images';
+ }
+
+ /**
+ * Change the originally provided path to fit any disk-specific requirements.
+ * This also ensures the path is kept to the expected root folders.
+ */
+ protected function adjustPathForDisk(string $path): string
+ {
+ $path = (new WhitespacePathNormalizer())->normalizePath(str_replace('uploads/images/', '', $path));
+
+ if ($this->usingSecureImages()) {
+ return $path;
+ }
+
+ return 'uploads/images/' . $path;
+ }
+
+ /**
+ * Check if a file at the given path exists.
+ */
+ public function exists(string $path): bool
+ {
+ return $this->filesystem->exists($this->adjustPathForDisk($path));
+ }
+
+ /**
+ * Get the file at the given path.
+ */
+ public function get(string $path): ?string
+ {
+ return $this->filesystem->get($this->adjustPathForDisk($path));
+ }
+
+ /**
+ * Save the given image data at the given path. Can choose to set
+ * the image as public which will update its visibility after saving.
+ */
+ public function put(string $path, string $data, bool $makePublic = false): void
+ {
+ $path = $this->adjustPathForDisk($path);
+ $this->filesystem->put($path, $data);
+
+ // Set visibility when a non-AWS-s3, s3-like storage option is in use.
+ // Done since this call can break s3-like services but desired for other image stores.
+ // Attempting to set ACL during above put request requires different permissions
+ // hence would technically be a breaking change for actual s3 usage.
+ if ($makePublic && !$this->isS3Like()) {
+ $this->filesystem->setVisibility($path, 'public');
+ }
+ }
+
+ /**
+ * Destroys an image at the given path.
+ * Searches for image thumbnails in addition to main provided path.
+ */
+ public function destroyAllMatchingNameFromPath(string $path): void
+ {
+ $path = $this->adjustPathForDisk($path);
+
+ $imageFolder = dirname($path);
+ $imageFileName = basename($path);
+ $allImages = collect($this->filesystem->allFiles($imageFolder));
+
+ // Delete image files
+ $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
+ return basename($imagePath) === $imageFileName;
+ });
+ $this->filesystem->delete($imagesToDelete->all());
+
+ // Cleanup of empty folders
+ $foldersInvolved = array_merge([$imageFolder], $this->filesystem->directories($imageFolder));
+ foreach ($foldersInvolved as $directory) {
+ if ($this->isFolderEmpty($directory)) {
+ $this->filesystem->deleteDirectory($directory);
+ }
+ }
+ }
+
+ /**
+ * Get the mime type of the file at the given path.
+ * Only works for local filesystem adapters.
+ */
+ public function mimeType(string $path): string
+ {
+ $path = $this->adjustPathForDisk($path);
+ return $this->filesystem instanceof FilesystemAdapter ? $this->filesystem->mimeType($path) : '';
+ }
+
+ /**
+ * Get a stream response for the image at the given path.
+ */
+ public function response(string $path): StreamedResponse
+ {
+ return $this->filesystem->response($this->adjustPathForDisk($path));
+ }
+
+ /**
+ * Check if the image storage in use is an S3-like (but not likely S3) external system.
+ */
+ protected function isS3Like(): bool
+ {
+ $usingS3 = $this->diskName === 's3';
+ return $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
+ }
+
+ /**
+ * Check whether a folder is empty.
+ */
+ protected function isFolderEmpty(string $path): bool
+ {
+ $files = $this->filesystem->files($path);
+ $folders = $this->filesystem->directories($path);
+
+ return count($files) === 0 && count($folders) === 0;
+ }
+}
/**
* Destroy all user avatars uploaded to the given user.
*/
- public function destroyAllForUser(User $user)
+ public function destroyAllForUser(User $user): void
{
$profileImages = Image::query()->where('type', '=', 'user')
->where('uploaded_to', '=', $user->id)
/**
* Save an avatar image from an external service.
*
- * @throws Exception
+ * @throws HttpFetchException
*/
protected function saveAvatarImage(User $user, int $size = 500): Image
{
try {
$client = $this->http->buildClient(5);
$response = $client->sendRequest(new Request('GET', $url));
- $imageData = (string) $response->getBody();
+ if ($response->getStatusCode() !== 200) {
+ throw new HttpFetchException(trans('errors.cannot_get_image_from_url', ['url' => $url]));
+ }
+
+ return (string) $response->getBody();
} catch (ClientExceptionInterface $exception) {
throw new HttpFetchException(trans('errors.cannot_get_image_from_url', ['url' => $url]), $exception->getCode(), $exception);
}
-
- return $imageData;
}
/**
* Check if fetching external avatars is enabled.
*/
- protected function avatarFetchEnabled(): bool
+ public function avatarFetchEnabled(): bool
{
$fetchUrl = $this->getAvatarUrl();
/**
* Get the URL to fetch avatars from.
*/
- protected function getAvatarUrl(): string
+ public function getAvatarUrl(): string
{
$configOption = config('services.avatar_url');
if ($configOption === false) {
}
try {
- $avatar = $this->avatar ? url($this->avatar->getThumb($size, $size, false)) : $default;
+ $avatar = $this->avatar?->getThumb($size, $size, false) ?? $default;
} catch (Exception $err) {
$avatar = $default;
}
--- /dev/null
+<?php
+
+namespace BookStack\Util;
+
+use BookStack\Exceptions\Handler;
+use Illuminate\Contracts\Debug\ExceptionHandler;
+
+/**
+ * Create a handler which runs the provided actions upon an
+ * out-of-memory event. This allows reserving of memory to allow
+ * the desired action to run as needed.
+ *
+ * Essentially provides a wrapper and memory reserving around the
+ * memory handling added to the default app error handler.
+ */
+class OutOfMemoryHandler
+{
+ protected $onOutOfMemory;
+ protected string $memoryReserve = '';
+
+ public function __construct(callable $onOutOfMemory, int $memoryReserveMB = 4)
+ {
+ $this->onOutOfMemory = $onOutOfMemory;
+
+ $this->memoryReserve = str_repeat('x', $memoryReserveMB * 1_000_000);
+ $this->getHandler()->prepareForOutOfMemory(function () {
+ return $this->handle();
+ });
+ }
+
+ protected function handle(): mixed
+ {
+ $result = null;
+ $this->memoryReserve = '';
+
+ if ($this->onOutOfMemory) {
+ $result = call_user_func($this->onOutOfMemory);
+ $this->forget();
+ }
+
+ return $result;
+ }
+
+ /**
+ * Forget the handler so no action is taken place on out of memory.
+ */
+ public function forget(): void
+ {
+ $this->memoryReserve = '';
+ $this->onOutOfMemory = null;
+ $this->getHandler()->forgetOutOfMemoryHandler();
+ }
+
+ protected function getHandler(): Handler
+ {
+ return app()->make(ExceptionHandler::class);
+ }
+}
'image_delete_success' => 'Image successfully deleted',
'image_replace' => 'Replace Image',
'image_replace_success' => 'Image file successfully updated',
+ 'image_rebuild_thumbs' => 'Regenerate Size Variations',
+ 'image_rebuild_thumbs_success' => 'Image size variations successfully rebuilt!',
// Code Editor
'code_editor' => 'Edit Code',
'cannot_get_image_from_url' => 'Cannot get image from :url',
'cannot_create_thumbs' => 'The server cannot create thumbnails. Please check you have the GD PHP extension installed.',
'server_upload_limit' => 'The server does not allow uploads of this size. Please try a smaller file size.',
+ 'server_post_limit' => 'The server cannot receive the provided amount of data. Try again with less data or a smaller file.',
'uploaded' => 'The server does not allow uploads of this size. Please try a smaller file size.',
// Drawing & Images
'image_upload_error' => 'An error occurred uploading the image',
'image_upload_type_error' => 'The image type being uploaded is invalid',
'image_upload_replace_type' => 'Image file replacements must be of the same type',
+ 'image_upload_memory_limit' => 'Failed to handle image upload and/or create thumbnails due to system resource limits.',
+ 'image_thumbnail_memory_limit' => 'Failed to create image size variations due to system resource limits.',
+ 'image_gallery_thumbnail_memory_limit' => 'Failed to create gallery thumbnails due to system resource limits.',
'drawing_data_not_found' => 'Drawing data could not be loaded. The drawing file might no longer exist or you may not have permission to access it.',
// Attachments
[](https://gh-stats.bookstackapp.com/)
[](https://discord.gg/ztkBqR2)
[](https://fosstodon.org/@bookstack)
-[](https://twitter.com/bookstack_app)
+[](https://x.com/bookstack_app)
+
[](https://foss.video/c/bookstack)
[](https://www.youtube.com/bookstackapp)
* [BookStack Blog](https://www.bookstackapp.com/blog)
* [Issue List](https://github.com/BookStackApp/BookStack/issues)
* [Discord Chat](https://discord.gg/ztkBqR2)
+* [Support Options](https://www.bookstackapp.com/support/)
## 📚 Project Definition
<td><a href="https://www.practicali.be" target="_blank">
<img width="240" src="https://media.githubusercontent.com/media/BookStackApp/website/main/static/images/sponsors/practicali.png" alt="Practicali">
</a></td>
+</tr><tr>
+<td><a href="https://www.stellarhosted.com/bookstack/" target="_blank">
+ <img width="240" src="https://media.githubusercontent.com/media/BookStackApp/website/main/static/images/sponsors/stellarhosted.png" alt="Stellar Hosted">
+</a></td>
<td><a href="https://torutec.com/" target="_blank">
<img width="240" src="https://media.githubusercontent.com/media/BookStackApp/website/main/static/images/sponsors/torutec.png" alt="Torutec">
</a></td>
+</tr>
+<tr>
+<td colspan="2" align="center" style="text-align: center"><a href="https://nws.netways.de/apps/bookstack/" target="_blank">
+ <img width="240" src="https://media.githubusercontent.com/media/BookStackApp/website/main/static/images/sponsors/netways.png" alt="NETWAYS Web Services">
+</a></td>
</tr></tbody></table>
## 🛣️ Road Map
},
event => {
event.preventDefault();
- this.selectSuggestion(event.target.textContent);
+ const selectionValue = event.target.textContent;
+ if (selectionValue) {
+ this.selectSuggestion(selectionValue);
+ }
},
);
navHandler.shareHandlingToEl(this.input);
window.$events.listen('entity-select-confirm', this.handleConfirmedSelection.bind(this));
}
- show(callback) {
+ show(callback, searchText = '') {
this.callback = callback;
this.getPopup().show();
+
+ if (searchText) {
+ this.getSelector().searchText(searchText);
+ }
+
this.getSelector().focusSearch();
}
this.searchInput.focus();
}
+ searchText(queryText) {
+ this.searchInput.value = queryText;
+ this.searchEntities(queryText);
+ }
+
showLoading() {
this.loading.style.display = 'block';
this.resultsContainer.style.display = 'none';
}
});
+ // Rebuild thumbs click
+ onChildEvent(this.formContainer, '#image-manager-rebuild-thumbs', 'click', async (_, button) => {
+ button.disabled = true;
+ if (this.lastSelected) {
+ await this.rebuildThumbnails(this.lastSelected.id);
+ }
+ button.disabled = false;
+ });
+
// Edit form submit
this.formContainer.addEventListener('ajax-form-success', () => {
this.refreshGallery();
this.loadGallery();
}
- onImageSelectEvent(event) {
- const image = JSON.parse(event.detail.data);
+ async onImageSelectEvent(event) {
+ let image = JSON.parse(event.detail.data);
const isDblClick = ((image && image.id === this.lastSelected.id)
&& Date.now() - this.lastSelectedTime < 400);
const alreadySelected = event.target.classList.contains('selected');
el.classList.remove('selected');
});
- if (!alreadySelected) {
+ if (!alreadySelected && !isDblClick) {
event.target.classList.add('selected');
- this.loadImageEditForm(image.id);
- } else {
+ image = await this.loadImageEditForm(image.id);
+ } else if (!isDblClick) {
this.resetEditForm();
+ } else if (isDblClick) {
+ image = this.lastSelected;
}
+
this.selectButton.classList.toggle('hidden', alreadySelected);
if (isDblClick && this.callback) {
this.formContainer.innerHTML = formHtml;
this.formContainerPlaceholder.setAttribute('hidden', '');
window.$components.init(this.formContainer);
+
+ const imageDataEl = this.formContainer.querySelector('#image-manager-form-image-data');
+ return JSON.parse(imageDataEl.text);
}
runLoadMore() {
return this.loadMore.querySelector('button') && !this.loadMore.hasAttribute('hidden');
}
+ async rebuildThumbnails(imageId) {
+ try {
+ const response = await window.$http.put(`/images/${imageId}/rebuild-thumbnails`);
+ window.$events.success(response.data);
+ this.refreshGallery();
+ } catch (err) {
+ window.$events.showResponseError(err);
+ }
+ }
+
}
const imageManager = window.$components.first('image-manager');
imageManager.show(image => {
- const imageUrl = image.thumbs.display || image.url;
+ const imageUrl = image.thumbs?.display || image.url;
const selectedText = this.#getSelectionText();
const newText = `[](${image.url})`;
this.#replaceSelection(newText, newText.length);
/** @type {EntitySelectorPopup} * */
const selector = window.$components.first('entity-selector-popup');
+ const selectionText = this.#getSelectionText(selectionRange);
selector.show(entity => {
- const selectedText = this.#getSelectionText(selectionRange) || entity.name;
+ const selectedText = selectionText || entity.name;
const newText = `[${selectedText}](${entity.link})`;
this.#replaceSelection(newText, newText.length, selectionRange);
- });
+ }, selectionText);
}
// Show draw.io if enabled and handle save.
const newContent = `[](${data.url})`;
this.#findAndReplaceContent(placeHolderText, newContent);
} catch (err) {
- window.$events.emit('error', this.editor.config.text.imageUploadError);
+ window.$events.error(err?.data?.message || this.editor.config.text.imageUploadError);
this.#findAndReplaceContent(placeHolderText, '');
console.error(err);
}
if (meta.filetype === 'file') {
/** @type {EntitySelectorPopup} * */
const selector = window.$components.first('entity-selector-popup');
+ const selectionText = this.selection.getContent({format: 'text'}).trim();
selector.show(entity => {
callback(entity.link, {
text: entity.name,
title: entity.name,
});
- });
+ }, selectionText);
}
if (meta.filetype === 'image') {
editor.dom.replace(newEl, id);
}).catch(err => {
editor.dom.remove(id);
- window.$events.emit('error', options.translations.imageUploadErrorText);
+ window.$events.error(err?.data?.message || options.translations.imageUploadErrorText);
console.error(err);
});
}, 10);
/** @type {ImageManager} * */
const imageManager = window.$components.first('image-manager');
imageManager.show(image => {
- const imageUrl = image.thumbs.display || image.url;
+ const imageUrl = image.thumbs?.display || image.url;
let html = `<a href="${image.url}" target="_blank">`;
html += `<img src="${imageUrl}" alt="${image.name}">`;
html += '</a>';
editor.shortcuts.add('meta+shift+K', '', () => {
/** @var {EntitySelectorPopup} * */
const selectorPopup = window.$components.first('entity-selector-popup');
+ const selectionText = editor.selection.getContent({format: 'text'}).trim();
selectorPopup.show(entity => {
if (editor.selection.isCollapsed()) {
editor.insertContent(editor.dom.createHTML('a', {href: entity.link}, editor.dom.encode(entity.name)));
editor.selection.collapse(false);
editor.focus();
- });
+ }, selectionText);
});
}
.image-manager-list {
padding: 3px;
display: grid;
- grid-template-columns: repeat( auto-fit, minmax(140px, 1fr) );
+ grid-template-columns: repeat( auto-fill, minmax(max(140px, 17%), 1fr) );
gap: 3px;
z-index: 3;
> div {
text-align: center;
}
+.image-manager-list .image-manager-list-warning {
+ grid-column: 1 / -1;
+ aspect-ratio: auto;
+}
+
+.image-manager-warning {
+ @include lightDark(background, #FFF, #333);
+ color: var(--color-warning);
+ font-weight: bold;
+ border-inline: 3px solid var(--color-warning);
+}
+
.image-manager-sidebar {
width: 300px;
margin: 0 auto;
* Includes the main navigation header and the faded toolbar.
*/
-header .grid {
+header.grid {
grid-template-columns: minmax(max-content, 2fr) 1fr minmax(max-content, 2fr);
}
@include smaller-than($l) {
- header .grid {
+ header.grid {
grid-template-columns: 1fr;
grid-row-gap: 0;
}
-@use "sass:math";
-@import "variables";
-
-header {
- display: none;
-}
-
html, body {
font-size: 12px;
background-color: #FFF;
@import "pages";
@import "content";
+@media print {
+ @import "print";
+}
+
// Jquery Sortable Styles
.dragged {
position: absolute;
@section('body')
- <div class="mb-s">
+ <div class="mb-s print-hidden">
@include('entities.breadcrumbs', ['crumbs' => [
$book,
]])
+++ /dev/null
-<header id="header" component="header-mobile-toggle" class="primary-background">
- <div class="grid mx-l">
-
- <div>
- <a href="{{ url('/') }}" data-shortcut="home_view" class="logo">
- @if(setting('app-logo', '') !== 'none')
- <img class="logo-image" src="{{ setting('app-logo', '') === '' ? url('/logo.png') : url(setting('app-logo', '')) }}" alt="Logo">
- @endif
- @if (setting('app-name-header'))
- <span class="logo-text">{{ setting('app-name') }}</span>
- @endif
- </a>
- <button type="button"
- refs="header-mobile-toggle@toggle"
- title="{{ trans('common.header_menu_expand') }}"
- aria-expanded="false"
- class="mobile-menu-toggle hide-over-l">@icon('more')</button>
- </div>
-
- <div class="flex-container-column items-center justify-center hide-under-l">
- @if (user()->hasAppAccess())
- <form component="global-search" action="{{ url('/search') }}" method="GET" class="search-box" role="search" tabindex="0">
- <button id="header-search-box-button"
- refs="global-search@button"
- type="submit"
- aria-label="{{ trans('common.search') }}"
- tabindex="-1">@icon('search')</button>
- <input id="header-search-box-input"
- refs="global-search@input"
- type="text"
- name="term"
- data-shortcut="global_search"
- autocomplete="off"
- aria-label="{{ trans('common.search') }}" placeholder="{{ trans('common.search') }}"
- value="{{ $searchTerm ?? '' }}">
- <div refs="global-search@suggestions" class="global-search-suggestions card">
- <div refs="global-search@loading" class="text-center px-m global-search-loading">@include('common.loading-icon')</div>
- <div refs="global-search@suggestion-results" class="px-m"></div>
- <button class="text-button card-footer-link" type="submit">{{ trans('common.view_all') }}</button>
- </div>
- </form>
- @endif
- </div>
-
- <nav refs="header-mobile-toggle@menu" class="header-links">
- <div class="links text-center">
- @if (user()->hasAppAccess())
- <a class="hide-over-l" href="{{ url('/search') }}">@icon('search'){{ trans('common.search') }}</a>
- @if(userCanOnAny('view', \BookStack\Entities\Models\Bookshelf::class) || userCan('bookshelf-view-all') || userCan('bookshelf-view-own'))
- <a href="{{ url('/shelves') }}" data-shortcut="shelves_view">@icon('bookshelf'){{ trans('entities.shelves') }}</a>
- @endif
- <a href="{{ url('/books') }}" data-shortcut="books_view">@icon('books'){{ trans('entities.books') }}</a>
- @if(!user()->isGuest() && userCan('settings-manage'))
- <a href="{{ url('/settings') }}" data-shortcut="settings_view">@icon('settings'){{ trans('settings.settings') }}</a>
- @endif
- @if(!user()->isGuest() && userCan('users-manage') && !userCan('settings-manage'))
- <a href="{{ url('/settings/users') }}" data-shortcut="settings_view">@icon('users'){{ trans('settings.users') }}</a>
- @endif
- @endif
-
- @if(user()->isGuest())
- @if(setting('registration-enabled') && config('auth.method') === 'standard')
- <a href="{{ url('/register') }}">@icon('new-user'){{ trans('auth.sign_up') }}</a>
- @endif
- <a href="{{ url('/login') }}">@icon('login'){{ trans('auth.log_in') }}</a>
- @endif
- </div>
- @if(!user()->isGuest())
- @include('common.header-user-menu', ['user' => user()])
- @endif
- </nav>
-
- </div>
-</header>
</a>
@endif
@include('entities.view-toggle', ['view' => $view, 'type' => 'books'])
+ <a href="{{ url('/tags') }}" class="icon-list-item">
+ <span>@icon('tag')</span>
+ <span>{{ trans('entities.tags_view_tags') }}</span>
+ </a>
@include('home.parts.expand-toggle', ['classes' => 'text-link', 'target' => '.entity-list.compact .entity-item-snippet', 'key' => 'home-details'])
@include('common.dark-mode-toggle', ['classes' => 'icon-list-item text-link'])
</div>
</a>
@endif
@include('entities.view-toggle', ['view' => $view, 'type' => 'bookshelves'])
+ <a href="{{ url('/tags') }}" class="icon-list-item">
+ <span>@icon('tag')</span>
+ <span>{{ trans('entities.tags_view_tags') }}</span>
+ </a>
@include('home.parts.expand-toggle', ['classes' => 'text-link', 'target' => '.entity-list.compact .entity-item-snippet', 'key' => 'home-details'])
@include('common.dark-mode-toggle', ['classes' => 'icon-list-item text-link'])
</div>
<meta name="viewport" content="width=device-width">
<meta name="token" content="{{ csrf_token() }}">
<meta name="base-url" content="{{ url('/') }}">
- <meta name="theme-color" content="{{ setting('app-color') }}"/>
+ <meta name="theme-color" content="{{(setting()->getForCurrentUser('dark-mode-enabled') ? setting('app-color-dark') : setting('app-color'))}}"/>
<!-- Social Cards Meta -->
<meta property="og:title" content="{{ isset($pageTitle) ? $pageTitle . ' | ' : '' }}{{ setting('app-name') }}">
<meta property="og:url" content="{{ url()->current() }}">
@stack('social-meta')
- <!-- Styles and Fonts -->
+ <!-- Styles -->
<link rel="stylesheet" href="{{ versioned_asset('dist/styles.css') }}">
- <link rel="stylesheet" media="print" href="{{ versioned_asset('dist/print-styles.css') }}">
<!-- Icons -->
<link rel="icon" type="image/png" sizes="256x256" href="{{ setting('app-icon') ?: url('/icon.png') }}">
<link rel="icon" type="image/png" sizes="64x64" href="{{ setting('app-icon-64') ?: url('/icon-64.png') }}">
<link rel="icon" type="image/png" sizes="32x32" href="{{ setting('app-icon-32') ?: url('/icon-32.png') }}">
+ <!-- PWA -->
+ <link rel="manifest" href="{{ url('/manifest.json') }}" crossorigin="use-credentials">
+ <meta name="mobile-web-app-capable" content="yes">
+
@yield('head')
<!-- Custom Styles & Head Content -->
- @include('common.custom-styles')
- @include('common.custom-head')
+ @include('layouts.parts.custom-styles')
+ @include('layouts.parts.custom-head')
@stack('head')
class="@stack('body-class')">
@include('layouts.parts.base-body-start')
- @include('common.skip-to-content')
- @include('common.notifications')
- @include('common.header')
+ @include('layouts.parts.skip-to-content')
+ @include('layouts.parts.notifications')
+ @include('layouts.parts.header')
<div id="content" components="@yield('content-components')" class="block">
@yield('content')
</div>
- @include('common.footer')
+ @include('layouts.parts.footer')
<div component="back-to-top" class="back-to-top print-hidden">
<div class="inner">
@if(count(setting('app-footer-links', [])) > 0)
-<footer>
+<footer class="print-hidden">
@foreach(setting('app-footer-links', []) as $link)
<a href="{{ $link['url'] }}" target="_blank" rel="noopener">{{ strpos($link['label'], 'trans::') === 0 ? trans(str_replace('trans::', '', $link['label'])) : $link['label'] }}</a>
@endforeach
--- /dev/null
+{{-- This is a placeholder template file provided as a --}}
+{{-- convenience to users of the visual theme system. --}}
\ No newline at end of file
--- /dev/null
+@include('layouts.parts.header-links-start')
+
+@if (user()->hasAppAccess())
+ <a class="hide-over-l" href="{{ url('/search') }}">@icon('search'){{ trans('common.search') }}</a>
+ @if(userCanOnAny('view', \BookStack\Entities\Models\Bookshelf::class) || userCan('bookshelf-view-all') || userCan('bookshelf-view-own'))
+ <a href="{{ url('/shelves') }}"
+ data-shortcut="shelves_view">@icon('bookshelf'){{ trans('entities.shelves') }}</a>
+ @endif
+ <a href="{{ url('/books') }}" data-shortcut="books_view">@icon('books'){{ trans('entities.books') }}</a>
+ @if(!user()->isGuest() && userCan('settings-manage'))
+ <a href="{{ url('/settings') }}"
+ data-shortcut="settings_view">@icon('settings'){{ trans('settings.settings') }}</a>
+ @endif
+ @if(!user()->isGuest() && userCan('users-manage') && !userCan('settings-manage'))
+ <a href="{{ url('/settings/users') }}"
+ data-shortcut="settings_view">@icon('users'){{ trans('settings.users') }}</a>
+ @endif
+@endif
+
+@if(user()->isGuest())
+ @if(setting('registration-enabled') && config('auth.method') === 'standard')
+ <a href="{{ url('/register') }}">@icon('new-user'){{ trans('auth.sign_up') }}</a>
+ @endif
+ <a href="{{ url('/login') }}">@icon('login'){{ trans('auth.log_in') }}</a>
+@endif
\ No newline at end of file
--- /dev/null
+<a href="{{ url('/') }}" data-shortcut="home_view" class="logo">
+ @if(setting('app-logo', '') !== 'none')
+ <img class="logo-image" src="{{ setting('app-logo', '') === '' ? url('/logo.png') : url(setting('app-logo', '')) }}" alt="Logo">
+ @endif
+ @if (setting('app-name-header'))
+ <span class="logo-text">{{ setting('app-name') }}</span>
+ @endif
+</a>
\ No newline at end of file
--- /dev/null
+<form component="global-search" action="{{ url('/search') }}" method="GET" class="search-box" role="search" tabindex="0">
+ <button id="header-search-box-button"
+ refs="global-search@button"
+ type="submit"
+ aria-label="{{ trans('common.search') }}"
+ tabindex="-1">@icon('search')</button>
+ <input id="header-search-box-input"
+ refs="global-search@input"
+ type="text"
+ name="term"
+ data-shortcut="global_search"
+ autocomplete="off"
+ aria-label="{{ trans('common.search') }}" placeholder="{{ trans('common.search') }}"
+ value="{{ $searchTerm ?? '' }}">
+ <div refs="global-search@suggestions" class="global-search-suggestions card">
+ <div refs="global-search@loading" class="text-center px-m global-search-loading">@include('common.loading-icon')</div>
+ <div refs="global-search@suggestion-results" class="px-m"></div>
+ <button class="text-button card-footer-link" type="submit">{{ trans('common.view_all') }}</button>
+ </div>
+</form>
\ No newline at end of file
--- /dev/null
+<header id="header" component="header-mobile-toggle" class="primary-background px-xl grid print-hidden">
+ <div>
+ @include('layouts.parts.header-logo')
+ <button type="button"
+ refs="header-mobile-toggle@toggle"
+ title="{{ trans('common.header_menu_expand') }}"
+ aria-expanded="false"
+ class="mobile-menu-toggle hide-over-l">@icon('more')</button>
+ </div>
+
+ <div class="flex-container-column items-center justify-center hide-under-l">
+ @if(user()->hasAppAccess())
+ @include('layouts.parts.header-search')
+ @endif
+ </div>
+
+ <nav refs="header-mobile-toggle@menu" class="header-links">
+ <div class="links text-center">
+ @include('layouts.parts.header-links')
+ </div>
+ @if(!user()->isGuest())
+ @include('layouts.parts.header-user-menu', ['user' => user()])
+ @endif
+ </nav>
+</header>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
- <!-- Styles and Fonts -->
+ <!-- Styles -->
<link rel="stylesheet" href="{{ versioned_asset('dist/styles.css') }}">
- <link rel="stylesheet" media="print" href="{{ versioned_asset('dist/print-styles.css') }}">
<!-- Custom Styles & Head Content -->
- @include('common.custom-styles')
- @include('common.custom-head')
+ @include('layouts.parts.custom-styles')
+ @include('layouts.parts.custom-head')
</head>
<body>
@yield('content')
option:dropzone:file-accept="image/*"
class="image-manager-details">
+ @if($warning ?? '')
+ <div class="image-manager-warning px-m py-xs flex-container-row gap-xs items-center mb-l">
+ <div>@icon('warning')</div>
+ <div class="flex">{{ $warning }}</div>
+ </div>
+ @endif
+
<div refs="dropzone@status-area dropzone@drop-target"></div>
+ <script id="image-manager-form-image-data" type="application/json">@json($image)</script>
+
<form component="ajax-form"
option:ajax-form:success-message="{{ trans('components.image_update_success') }}"
option:ajax-form:method="put"
id="image-manager-replace"
refs="dropzone@select-button"
class="text-item">{{ trans('components.image_replace') }}</button>
+ <button type="button"
+ id="image-manager-rebuild-thumbs"
+ class="text-item">{{ trans('components.image_rebuild_thumbs') }}</button>
@endif
</div>
</div>
+@if($warning ?? '')
+ <div class="image-manager-list-warning image-manager-warning px-m py-xs flex-container-row gap-xs items-center">
+ <div>@icon('warning')</div>
+ <div class="flex">{{ $warning }}</div>
+ </div>
+@endif
@foreach($images as $index => $image)
<div>
<button component="event-emit-select"
option:event-emit-select:data="{{ json_encode($image) }}"
class="image anim fadeIn text-link"
style="animation-delay: {{ min($index * 10, 260) . 'ms' }};">
- <img src="{{ $image->thumbs['gallery'] }}"
+ <img src="{{ $image->thumbs['gallery'] ?? '' }}"
alt="{{ $image->name }}"
role="none"
width="150"
@if ($commentTree->enabled())
@if(($previous || $next))
- <div class="px-xl">
+ <div class="px-xl print-hidden">
<hr class="darker">
</div>
@endif
@section('body')
- <div class="mb-s">
+ <div class="mb-s print-hidden">
@include('entities.breadcrumbs', ['crumbs' => [
$shelf,
]])
Route::get('/status', [SettingControllers\StatusController::class, 'show']);
Route::get('/robots.txt', [HomeController::class, 'robots']);
Route::get('/favicon.ico', [HomeController::class, 'favicon']);
+Route::get('/manifest.json', [HomeController::class, 'pwaManifest']);
// Authenticated routes...
Route::middleware('auth')->group(function () {
Route::post('/images/drawio', [UploadControllers\DrawioImageController::class, 'create']);
Route::get('/images/edit/{id}', [UploadControllers\ImageController::class, 'edit']);
Route::put('/images/{id}/file', [UploadControllers\ImageController::class, 'updateFile']);
+ Route::put('/images/{id}/rebuild-thumbnails', [UploadControllers\ImageController::class, 'rebuildThumbnails']);
Route::put('/images/{id}', [UploadControllers\ImageController::class, 'update']);
Route::delete('/images/{id}', [UploadControllers\ImageController::class, 'destroy']);
--- /dev/null
+<?php
+
+namespace Tests\Commands;
+
+use BookStack\Uploads\Image;
+use BookStack\Users\Models\User;
+use GuzzleHttp\Psr7\Response;
+use Illuminate\Database\Eloquent\Collection;
+use Tests\TestCase;
+
+class RefreshAvatarCommandTest extends TestCase
+{
+ public function setUp(): void
+ {
+ parent::setUp();
+
+ config()->set([
+ 'services.disable_services' => false,
+ 'services.avatar_url' => 'https://avatars.example.com?a=b',
+ ]);
+ }
+
+ public function test_command_errors_if_avatar_fetch_disabled()
+ {
+ config()->set(['services.avatar_url' => false]);
+
+ $this->artisan('bookstack:refresh-avatar')
+ ->expectsOutputToContain("Avatar fetching is disabled on this instance")
+ ->assertExitCode(1);
+ }
+
+ public function test_command_requires_email_or_id_option()
+ {
+ $this->artisan('bookstack:refresh-avatar')
+ ->expectsOutputToContain("Either a --id=<number> or --email=<email> option must be provided")
+ ->assertExitCode(1);
+ }
+
+ public function test_command_runs_with_provided_email()
+ {
+ $requests = $this->mockHttpClient([new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData())]);
+
+ $user = $this->users->viewer();
+ $this->assertFalse($user->avatar()->exists());
+
+ $this->artisan("bookstack:refresh-avatar --email={$user->email} -f")
+ ->expectsQuestion('Are you sure you want to proceed?', true)
+ ->expectsOutput("[ID: {$user->id}] {$user->email} - Updated")
+ ->expectsOutputToContain('This will destroy any existing avatar images these users have, and attempt to fetch new avatar images from avatars.example.com')
+ ->assertExitCode(0);
+
+ $this->assertEquals('https://avatars.example.com?a=b', $requests->latestRequest()->getUri());
+
+ $user->refresh();
+ $this->assertTrue($user->avatar()->exists());
+ }
+
+ public function test_command_runs_with_provided_id()
+ {
+ $requests = $this->mockHttpClient([new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData())]);
+
+ $user = $this->users->viewer();
+ $this->assertFalse($user->avatar()->exists());
+
+ $this->artisan("bookstack:refresh-avatar --id={$user->id} -f")
+ ->expectsQuestion('Are you sure you want to proceed?', true)
+ ->expectsOutput("[ID: {$user->id}] {$user->email} - Updated")
+ ->assertExitCode(0);
+
+ $this->assertEquals('https://avatars.example.com?a=b', $requests->latestRequest()->getUri());
+
+ $user->refresh();
+ $this->assertTrue($user->avatar()->exists());
+ }
+
+ public function test_command_runs_with_provided_id_error_upstream()
+ {
+ $requests = $this->mockHttpClient([new Response(404)]);
+
+ $user = $this->users->viewer();
+ $this->assertFalse($user->avatar()->exists());
+
+ $this->artisan("bookstack:refresh-avatar --id={$user->id} -f")
+ ->expectsQuestion('Are you sure you want to proceed?', true)
+ ->expectsOutput("[ID: {$user->id}] {$user->email} - Not updated")
+ ->assertExitCode(1);
+
+ $this->assertEquals(1, $requests->requestCount());
+ $this->assertFalse($user->avatar()->exists());
+ }
+
+ public function test_saying_no_to_confirmation_does_not_refresh_avatar()
+ {
+ $user = $this->users->viewer();
+
+ $this->assertFalse($user->avatar()->exists());
+ $this->artisan("bookstack:refresh-avatar --id={$user->id} -f")
+ ->expectsQuestion('Are you sure you want to proceed?', false)
+ ->assertExitCode(0);
+ $this->assertFalse($user->avatar()->exists());
+ }
+
+ public function test_giving_non_existing_user_shows_error_message()
+ {
+ ->assertExitCode(1);
+ }
+
+ public function test_command_runs_all_users_without_avatars_dry_run()
+ {
+ $users = User::query()->where('image_id', '=', 0)->get();
+
+ $this->artisan('bookstack:refresh-avatar --users-without-avatars')
+ ->expectsOutput(count($users) . ' user(s) found to update avatars for.')
+ ->expectsOutput("[ID: {$users[0]->id}] {$users[0]->email} - Not updated")
+ ->expectsOutput('Dry run, no avatars were updated.')
+ ->assertExitCode(0);
+ }
+
+ public function test_command_runs_all_users_without_avatars_with_none_to_update()
+ {
+ $requests = $this->mockHttpClient();
+ $image = Image::factory()->create();
+ User::query()->update(['image_id' => $image->id]);
+
+ $this->artisan('bookstack:refresh-avatar --users-without-avatars -f')
+ ->expectsOutput('0 user(s) found to update avatars for.')
+ ->assertExitCode(0);
+
+ $this->assertEquals(0, $requests->requestCount());
+ }
+
+ public function test_command_runs_all_users_without_avatars()
+ {
+ /** @var Collection|User[] $users */
+ $users = User::query()->where('image_id', '=', 0)->get();
+
+ $pendingCommand = $this->artisan('bookstack:refresh-avatar --users-without-avatars -f');
+ $pendingCommand
+ ->expectsOutput($users->count() . ' user(s) found to update avatars for.')
+ ->expectsQuestion('Are you sure you want to proceed?', true);
+
+ $responses = [];
+ foreach ($users as $user) {
+ $pendingCommand->expectsOutput("[ID: {$user->id}] {$user->email} - Updated");
+ $responses[] = new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData());
+ }
+ $requests = $this->mockHttpClient($responses);
+
+ $pendingCommand->assertExitCode(0);
+ $pendingCommand->run();
+
+ $this->assertEquals(0, User::query()->where('image_id', '=', 0)->count());
+ $this->assertEquals($users->count(), $requests->requestCount());
+ }
+
+ public function test_saying_no_to_confirmation_all_users_without_avatars()
+ {
+ $requests = $this->mockHttpClient();
+
+ $this->artisan('bookstack:refresh-avatar --users-without-avatars -f')
+ ->expectsQuestion('Are you sure you want to proceed?', false)
+ ->assertExitCode(0);
+
+ $this->assertEquals(0, $requests->requestCount());
+ }
+
+ public function test_command_runs_all_users_dry_run()
+ {
+ $users = User::query()->where('image_id', '=', 0)->get();
+
+ $this->artisan('bookstack:refresh-avatar --all')
+ ->expectsOutput(count($users) . ' user(s) found to update avatars for.')
+ ->expectsOutput("[ID: {$users[0]->id}] {$users[0]->email} - Not updated")
+ ->expectsOutput('Dry run, no avatars were updated.')
+ ->assertExitCode(0);
+ }
+
+ public function test_command_runs_update_all_users_avatar()
+ {
+ /** @var Collection|User[] $users */
+ $users = User::query()->get();
+
+ $pendingCommand = $this->artisan('bookstack:refresh-avatar --all -f');
+ $pendingCommand
+ ->expectsOutput($users->count() . ' user(s) found to update avatars for.')
+ ->expectsQuestion('Are you sure you want to proceed?', true);
+
+ $responses = [];
+ foreach ($users as $user) {
+ $pendingCommand->expectsOutput("[ID: {$user->id}] {$user->email} - Updated");
+ $responses[] = new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData());
+ }
+ $requests = $this->mockHttpClient($responses);
+
+ $pendingCommand->assertExitCode(0);
+ $pendingCommand->run();
+
+ $this->assertEquals(0, User::query()->where('image_id', '=', 0)->count());
+ $this->assertEquals($users->count(), $requests->requestCount());
+ }
+
+ public function test_command_runs_update_all_users_avatar_errors()
+ {
+ /** @var Collection|User[] $users */
+ $users = array_values(User::query()->get()->all());
+
+ $pendingCommand = $this->artisan('bookstack:refresh-avatar --all -f');
+ $pendingCommand
+ ->expectsOutput(count($users) . ' user(s) found to update avatars for.')
+ ->expectsQuestion('Are you sure you want to proceed?', true);
+
+ $responses = [];
+ foreach ($users as $index => $user) {
+ if ($index === 0) {
+ $pendingCommand->expectsOutput("[ID: {$user->id}] {$user->email} - Not updated");
+ $responses[] = new Response(404);
+ continue;
+ }
+
+ $pendingCommand->expectsOutput("[ID: {$user->id}] {$user->email} - Updated");
+ $responses[] = new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData());
+ }
+
+ $requests = $this->mockHttpClient($responses);
+
+ $pendingCommand->assertExitCode(1);
+ $pendingCommand->run();
+
+ $userWithAvatars = User::query()->where('image_id', '!=', 0)->count();
+ $this->assertEquals(count($users) - 1, $userWithAvatars);
+ $this->assertEquals(count($users), $requests->requestCount());
+ }
+
+ public function test_saying_no_to_confirmation_update_all_users_avatar()
+ {
+ $requests = $this->mockHttpClient([new Response(200, ['Content-Type' => 'image/png'], $this->files->pngImageData())]);
+
+ $this->artisan('bookstack:refresh-avatar --all -f')
+ ->expectsQuestion('Are you sure you want to proceed?', false)
+ ->assertExitCode(0);
+
+ $this->assertEquals(0, $requests->requestCount());
+ }
+}
public function test_command_requires_email_or_id_option()
{
$this->artisan('bookstack:reset-mfa')
- ->expectsOutput('Either a --id=<number> or --email=<email> option must be provided.')
+ ->expectsOutputToContain('Either a --id=<number> or --email=<email> option must be provided.')
->assertExitCode(1);
}
$search = $this->asEditor()->get('/search?term=' . urlencode('\\\\cat\\dog'));
$search->assertSee($page->getUrl(), false);
- $search = $this->asEditor()->get('/search?term=' . urlencode('"\\dog\\"'));
+ $search = $this->asEditor()->get('/search?term=' . urlencode('"\\dog\\\\"'));
$search->assertSee($page->getUrl(), false);
- $search = $this->asEditor()->get('/search?term=' . urlencode('"\\badger\\"'));
+ $search = $this->asEditor()->get('/search?term=' . urlencode('"\\badger\\\\"'));
$search->assertDontSee($page->getUrl(), false);
$search = $this->asEditor()->get('/search?term=' . urlencode('[\\Categorylike%\\fluffy]'));
public function test_book_text_export()
{
- $page = $this->entities->page();
- $book = $page->book;
+ $book = $this->entities->bookHasChaptersAndPages();
+ $directPage = $book->directPages()->first();
+ $chapter = $book->chapters()->first();
+ $chapterPage = $chapter->pages()->first();
+ $this->entities->updatePage($directPage, ['html' => '<p>My awesome page</p>']);
+ $this->entities->updatePage($chapterPage, ['html' => '<p>My little nested page</p>']);
$this->asEditor();
$resp = $this->get($book->getUrl('/export/plaintext'));
$resp->assertStatus(200);
$resp->assertSee($book->name);
- $resp->assertSee($page->name);
+ $resp->assertSee($chapterPage->name);
+ $resp->assertSee($chapter->name);
+ $resp->assertSee($directPage->name);
+ $resp->assertSee('My awesome page');
+ $resp->assertSee('My little nested page');
$resp->assertHeader('Content-Disposition', 'attachment; filename="' . $book->slug . '.txt"');
}
+ public function test_book_text_export_format()
+ {
+ $entities = $this->entities->createChainBelongingToUser($this->users->viewer());
+ $this->entities->updatePage($entities['page'], ['html' => '<p>My great page</p><p>Full of <strong>great</strong> stuff</p>', 'name' => 'My wonderful page!']);
+ $entities['chapter']->name = 'Export chapter';
+ $entities['chapter']->description = "A test chapter to be exported\nIt has loads of info within";
+ $entities['book']->name = 'Export Book';
+ $entities['book']->description = "This is a book with stuff to export";
+ $entities['chapter']->save();
+ $entities['book']->save();
+
+ $resp = $this->asEditor()->get($entities['book']->getUrl('/export/plaintext'));
+
+ $expected = "Export Book\nThis is a book with stuff to export\n\nExport chapter\nA test chapter to be exported\nIt has loads of info within\n\n";
+ $expected .= "My wonderful page!\nMy great page Full of great stuff";
+ $resp->assertSee($expected);
+ }
+
public function test_book_pdf_export()
{
$page = $this->entities->page();
{
$chapter = $this->entities->chapter();
$page = $chapter->pages[0];
+ $this->entities->updatePage($page, ['html' => '<p>This is content within the page!</p>']);
$this->asEditor();
$resp = $this->get($chapter->getUrl('/export/plaintext'));
$resp->assertStatus(200);
$resp->assertSee($chapter->name);
$resp->assertSee($page->name);
+ $resp->assertSee('This is content within the page!');
$resp->assertHeader('Content-Disposition', 'attachment; filename="' . $chapter->slug . '.txt"');
}
+ public function test_chapter_text_export_format()
+ {
+ $entities = $this->entities->createChainBelongingToUser($this->users->viewer());
+ $this->entities->updatePage($entities['page'], ['html' => '<p>My great page</p><p>Full of <strong>great</strong> stuff</p>', 'name' => 'My wonderful page!']);
+ $entities['chapter']->name = 'Export chapter';
+ $entities['chapter']->description = "A test chapter to be exported\nIt has loads of info within";
+ $entities['chapter']->save();
+
+ $resp = $this->asEditor()->get($entities['book']->getUrl('/export/plaintext'));
+
+ $expected = "Export chapter\nA test chapter to be exported\nIt has loads of info within\n\n";
+ $expected .= "My wonderful page!\nMy great page Full of great stuff";
+ $resp->assertSee($expected);
+ }
+
public function test_chapter_pdf_export()
{
$chapter = $this->entities->chapter();
namespace Tests\Entity;
use BookStack\Search\SearchOptions;
+use Illuminate\Http\Request;
use Tests\TestCase;
class SearchOptionsTest extends TestCase
$this->assertEquals(['is_tree' => ''], $options->filters);
}
+ public function test_from_string_properly_parses_escaped_quotes()
+ {
+ $options = SearchOptions::fromString('"\"cat\"" surprise "\"\"" "\"donkey" "\"" "\\\\"');
+
+ $this->assertEquals(['"cat"', '""', '"donkey', '"', '\\'], $options->exacts);
+ }
+
public function test_to_string_includes_all_items_in_the_correct_format()
{
$expected = 'cat "dog" [tag=good] {is_tree}';
}
}
+ public function test_to_string_escapes_as_expected()
+ {
+ $options = new SearchOptions();
+ $options->exacts = ['"cat"', '""', '"donkey', '"', '\\', '\\"'];
+
+ $output = $options->toString();
+ $this->assertEquals('"\"cat\"" "\"\"" "\"donkey" "\"" "\\\\" "\\\\\""', $output);
+ }
+
public function test_correct_filter_values_are_set_from_string()
{
$opts = SearchOptions::fromString('{is_tree} {name:dan} {cat:happy}');
'cat' => 'happy',
], $opts->filters);
}
+ public function test_it_cannot_parse_out_empty_exacts()
+ {
+ $options = SearchOptions::fromString('"" test ""');
+
+ $this->assertEmpty($options->exacts);
+ $this->assertCount(1, $options->searches);
+ }
+
+ public function test_from_request_properly_parses_exacts_from_search_terms()
+ {
+ $request = new Request([
+ 'search' => 'biscuits "cheese" "" "baked beans"'
+ ]);
+
+ $options = SearchOptions::fromRequest($request);
+ $this->assertEquals(["biscuits"], $options->searches);
+ $this->assertEquals(['"cheese"', '""', '"baked', 'beans"'], $options->exacts);
+ }
}
namespace Tests;
+use Illuminate\Foundation\Http\Middleware\ValidatePostSize;
use Illuminate\Support\Facades\Log;
class ErrorTest extends TestCase
$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.']);
+ }
}
*/
public function deleteAtRelativePath(string $path): void
{
- $fullPath = public_path($path);
+ $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.
$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')));
+ }
}
$homeVisit->assertSee('grid-card-content');
$homeVisit->assertSee('grid-card-footer');
$homeVisit->assertSee('featured-image-container');
-
- $this->setSettings(['app-homepage-type' => false]);
- $this->test_default_homepage_visible();
}
public function test_set_bookshelves_homepage()
$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]);
- $this->setSettings(['app-homepage-type' => false]);
- $this->test_default_homepage_visible();
+ $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()
--- /dev/null
+<?php
+
+namespace Tests;
+
+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('/'));
+
+ // crossorigin attribute is required to send cookies with the manifest,
+ // so it can react correctly to user preferences (dark/light mode).
+ $html->assertElementExists('head link[rel="manifest"][href$="manifest.json"][crossorigin="use-credentials"]');
+ $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']);
+ }
+}
});
}
+ 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);
+ });
+ }
+
protected function usingThemeFolder(callable $callback)
{
// Create a folder and configure a theme
$this->files->deleteAtRelativePath($relPath);
}
+ public function test_image_manager_regen_thumbnails()
+ {
+ $this->asEditor();
+ $imageName = 'first-image.png';
+ $relPath = $this->files->expectedImagePath('gallery', $imageName);
+ $this->files->deleteAtRelativePath($relPath);
+
+ $this->files->uploadGalleryImage($this, $imageName, $this->entities->page()->id);
+ $image = Image::first();
+
+ $resp = $this->get("/images/edit/{$image->id}");
+ $this->withHtml($resp)->assertElementExists('button#image-manager-rebuild-thumbs');
+
+ $expectedThumbPath = dirname($relPath) . '/scaled-1680-/' . basename($relPath);
+ $this->files->deleteAtRelativePath($expectedThumbPath);
+ $this->assertFileDoesNotExist($this->files->relativeToFullPath($expectedThumbPath));
+
+ $resp = $this->put("/images/{$image->id}/rebuild-thumbnails");
+ $resp->assertOk();
+
+ $this->assertFileExists($this->files->relativeToFullPath($expectedThumbPath));
+ $this->files->deleteAtRelativePath($relPath);
+ }
+
protected function getTestProfileImage()
{
$imageName = 'profile.png';