Compare commits

..

82 Commits

Author SHA1 Message Date
Zhey
e42fda893c Add CSP controls for image and CSS sources 2026-03-26 12:00:08 +01:00
Dan Brown
25790fd024 Merge branch 'sec_26_03_2' into development 2026-03-23 11:24:07 +00:00
Dan Brown
1763ac550b Meta: Updated translators pre v26.03.2 release 2026-03-23 10:08:38 +00:00
Dan Brown
fd6867e577 Updated translations with latest Crowdin changes (#6064) 2026-03-23 10:05:51 +00:00
Dan Brown
5ebc1fe3b0 Deps: Updated PHP package versions pre v26.03.2 release 2026-03-22 17:22:13 +00:00
Dan Brown
a44756168d WYSIWYG: Aligned double click to set label for details functionality
Aligned the behaviour across the WYSIWYG editors, and also for nested
details blocks (which wasn't working in the TinyMCE implementation).

Closes #6059
2026-03-22 17:20:36 +00:00
Dan Brown
fa1dc162bd Update PHP_CodeSniffer repository link (#6060) 2026-03-21 17:13:43 +00:00
Dan Brown
5763d26b17 Updated registration to use validated input instead of all 2026-03-19 21:29:30 +00:00
Rodrigo Primo
04dd9f8e19 Update PHP_CodeSniffer repository link 2026-03-17 17:21:01 -03:00
Dan Brown
0120b475eb Deps: Updated PHP deps pre v26.03.1 2026-03-17 10:59:11 +00:00
Dan Brown
8a59895ba0 Merge branch 'sec_chapter_export' into development 2026-03-17 10:41:51 +00:00
Dan Brown
a9ffd3e0c7 Responses: Added extra sanitization for download names
From testing, don't think this could exploited directly, as the response
would error instead of allowing control characters, but this adds an
extra layer of sanitization, and switches to encoded disposition
filenames for better UTF8 support.
2026-03-16 18:28:44 +00:00
Dan Brown
4f18fea086 Deps: Updated PHP deps pre v26.03 release 2026-03-15 13:17:48 +00:00
Dan Brown
362859ac23 Updated translator & dependency attribution before release v26.03 2026-03-15 13:14:54 +00:00
Dan Brown
7cbfd72920 Merge pull request #6007 from BookStackApp/l10n_development
Updated translations with latest Crowdin changes
2026-03-15 12:58:05 +00:00
Dan Brown
49df47836e Merge pull request #6057 from BookStackApp/v25-12
V25.12 changes v3
2026-03-15 12:51:02 +00:00
Dan Brown
f4c9d2b049 Exports: Fixed scope of pages in chapter MD export
Added tests to cover children of all MD exports
2026-03-13 13:35:28 +00:00
Dan Brown
60a3b0c0ac API examples: Updated books-read to include shelf info 2026-03-12 17:04:36 +00:00
Dan Brown
5f5fea7c83 Deps: Bumped PHP packages before release 2026-03-12 10:52:12 +00:00
Dan Brown
6e7cc169d1 Preferences: Updated return redirect with better origin checks
As suggested by Alex Dan in their security report.
2026-03-10 18:31:51 +00:00
Dan Brown
6216c89f82 Packages: Updated PHP package versions 2026-03-10 17:48:12 +00:00
Dan Brown
404e67afbc Page Revisions: Added testing coverage to basic diffing 2026-03-10 17:47:07 +00:00
Dan Brown
6d64262a61 Revision Diffs: Added filtering post-diff render 2026-03-10 15:03:43 +00:00
Dan Brown
151823b84e Theme Modules: Added easier way to insert HTML head content 2026-03-08 10:26:00 +00:00
Dan Brown
27240be499 Theme System: Added new page-content focused events
Closes #6049
2026-03-06 12:40:22 +00:00
Dan Brown
d0d1bb9829 Merge pull request #6035 from BookStackApp/v25-12
Merge further v25-12 changes into development
2026-03-06 10:26:41 +00:00
Dan Brown
7d0237c798 NPM Deps: Updated package versions
Fixed SCSS if deprecations
Fixed new eslint detected issues
2026-03-06 10:25:27 +00:00
Dan Brown
f2f76a3c56 Modules: Improved install command based on testing
- Updated output to be clearer
- Added warning and confirmation to local install flow
- Adjusted module folder name creation
2026-03-06 09:28:46 +00:00
Dan Brown
ec3dd856db Mail: Set domain for EHLO based upon the APP_URL
For #5990
2026-02-28 18:46:05 +00:00
Dan Brown
25ed242f61 Deps: Updated PHP package versions 2026-02-27 10:09:41 +00:00
Dan Brown
10c46534e0 Logical Theme: Added OIDC_AUTH_PRE_REDIRECT event
Allows customization of the auth URL before the user is redirected
to that URL.
Related to #6014
2026-02-27 09:34:33 +00:00
Dan Brown
dd42b9b43f Text: Updated per-page display limits description
To be more sensible & direct as per MtheBird's suggestion.
Closes #6005
2026-02-27 08:54:12 +00:00
Dan Brown
9a12e3a8b7 Book API: Added shelves list to show endpoint
For #6006
Added test to cover.
2026-02-24 10:25:17 +00:00
Dan Brown
7aef0a48b3 Content: Updated filters to allow some required attributes
- Allows target attribute on links.
- Allows custom mention attribute on links.

Adds test case to cover these.
For #6034
2026-02-23 08:08:44 +00:00
Dan Brown
6808292c90 Editors: Made drawings appear clickiable via cursor
During review of #5864
2026-02-21 16:00:14 +00:00
Dan Brown
c10b0fd5b9 Merge branch 'patch-1' of github.com:lublak/BookStack into lublak-patch-1 2026-02-21 15:52:25 +00:00
Dan Brown
1077a4efd0 Merge branch 'v25-12' into development 2026-02-21 13:59:29 +00:00
Dan Brown
23f3f35f6b Readme: Updated sponsors 2026-02-21 13:56:50 +00:00
Dan Brown
229a99ba24 Descriptions: Improved empty field handling, reduces whitespace
For #5724
2026-02-20 14:22:54 +00:00
Dan Brown
8e99fc6783 Books: On delete, redirect to shelf if in context
For #6029
Added tests to cover
2026-02-20 11:23:26 +00:00
Dan Brown
80204518a2 Page Content: Better handling for empty content filtering
For #6028
2026-02-19 23:25:00 +00:00
Dan Brown
a8d96fd389 Content filter: Allowed custom diagram attribute in allow-list
For #6026
2026-02-18 19:33:35 +00:00
Dan Brown
9d15c79fee Deps: Updated PHP package versions 2026-02-18 19:24:06 +00:00
Dan Brown
e1de1f0583 git: Added old purifier location to gitignore 2026-02-17 18:34:14 +00:00
Dan Brown
a2017ffa55 Caching: Altered purifier cache folder to be server-created
Moved from a static folder to a dynamically created folder in the
framework/cache directory, to increase the chance that it's created with
server-writable permissions.
This is due to an issue where users had permission issues, since adding
a new folder means it's created by the git user and often
non-web-writable.
2026-02-17 18:22:13 +00:00
Dan Brown
9646339933 Testing: Addressed failing tests and static checks 2026-02-17 11:31:47 +00:00
Dan Brown
e4383765e1 Meta: Updated licenses and config wording 2026-02-17 11:00:37 +00:00
Dan Brown
5d547fcf4c Deps: Updated PHP packages
Also fixed test namespace
2026-02-17 09:44:56 +00:00
Dan Brown
826b36c985 Editors: Added HTML filtering in certain loading conditions
When loaded via ajax for draft revert live in editor, or when loaded
into the editor by a different user.
2026-02-16 15:50:54 +00:00
Dan Brown
3fa1174e7a Content filtering: Updated config and readme attribution 2026-02-16 13:46:45 +00:00
Dan Brown
50e8501027 Content Filter: Added extra object filtering
Was blocked by CSP anyway, but best to have an extra layer.
2026-02-16 13:02:24 +00:00
Dan Brown
8a221f64e4 Content Filtering: Covered new config options and filters with tests 2026-02-16 10:11:48 +00:00
Dan Brown
035be66ebc Content: Updated tests and CSP usage of content script setting
Updates CSP to use new content_filtering option.
Splits out content filtering tests to their own class.
Updated tests where needed to adapt to changes.
2026-02-15 18:44:14 +00:00
Dan Brown
227027fc45 Content: Updated purifier and content caching
- Updated page content cache to use app version in cache key
- Moved purifier cache into framework to better work with existing
  expected folders.
- Added app version check to purifier so that it will reset its own
  cache on app version change.
2026-02-15 16:46:09 +00:00
Dan Brown
0f040fe8b1 Content: Tuned HTML purifier for our use
Tested it with a range of supported, including uncommon, content types
and added support, or changed config, where needed.
Been through docs for all HTMLPurifier options to assess what's
relevant.
2026-02-15 16:17:03 +00:00
Dan Brown
10ebe53bd9 Page Content: Added more complex & configurable content filtering
- Added new option to control parts of the filter.
- Added whitelist filtering pass via HTMLPurifier.
2026-02-13 14:14:28 +00:00
Dan Brown
5e12b678c7 Merge pull request #5998 from BookStackApp/further_theme_development
Further theme system developments
2026-02-09 13:34:15 +00:00
Dan Brown
057d7be0bc Views: Made index/show sidebars a lot more modular
Split out each sidebar block into their own template for easier
customization of those elements, and less code to manage when overriding
the parent show/index views.
2026-02-08 17:03:48 +00:00
Dan Brown
984a73159f Theme modules: Updated view includes to prevent caching conflicts 2026-02-08 13:39:34 +00:00
Dan Brown
a20438b901 Theme System: Fixed theme view before/after issues
- Updated the system to work with modules.
- Updated module docs to consider namespacing.
- Fixed view loading and registration event ordering.
- Fixed checking if views are registered.
2026-02-07 23:01:13 +00:00
Dan Brown
9d3d0a4a07 Theme Modules: Added testing coverage for install command 2026-02-05 21:57:12 +00:00
Dan Brown
5038d124e1 Theme modules: Updated docs to cover ZIP format 2026-02-05 18:01:17 +00:00
Dan Brown
f7890c2dd9 Theme Modules: Fixes and improvements after manual testing
- Added (limited) redirect handling to module downloads.
- Adjusted wording/text for consistency and clarity.
- Fixed scenarios where process was not stopped on error.
- Fixed module folder creation check/logic.
- Added better failed request handling to module downloads.
- Updated download response streaming to monitor/limit download size.
2026-02-05 17:49:35 +00:00
Dan Brown
45ae03ceac Theme Modules: Added install helper command
Not yet tested at all, either manually or via PHPUnit
2026-02-03 20:43:01 +00:00
Dan Brown
aa0a8dda11 Theme Modules: Added dev documentation 2026-02-02 18:29:35 +00:00
Dan Brown
120ee38383 Theme Modules: Added testing coverage 2026-02-01 17:31:21 +00:00
Dan Brown
cd84074cdf Theme System: Split & organised tests, changed module version to string 2026-02-01 16:27:52 +00:00
Dan Brown
4949520194 Theme System: Added initial module implementations 2026-02-01 11:53:46 +00:00
Dan Brown
46dcc30bf7 Updated translator & dependency attribution before release v25.12.3 2026-01-29 15:18:06 +00:00
Dan Brown
9f7d3b55dd Updated translations with latest Crowdin changes (#5997) 2026-01-29 15:11:40 +00:00
Dan Brown
3e5e88dc87 Deps: Updated PHP package versions via composer 2026-01-29 14:57:05 +00:00
Dan Brown
c77a0fdff3 Page Content: Added form elements to filtering
Added and updated tests to cover.

Also updated API auth to a narrower focus of existing session instead of also existing user auth.
This is mainly for tests, to ensure they're following the session
process we'd see for activity in the UI.
2026-01-29 14:54:08 +00:00
Dan Brown
6a63b38bb3 API: Prevented non-GET requests when using cookie-based auth
Added test to cover.
2026-01-29 03:37:16 +00:00
Dan Brown
1b17bb3929 Theme: Changed how before/after views are registered
Changed the system out to be a theme event instead of method, to align
with other registration events, and so that the theme view work can
better be contained in its own class.
2026-01-27 16:50:50 +00:00
Dan Brown
9fcfc762ec Theme: Added testing of registerViewToRender* functions
Updated function name also.
2026-01-27 00:36:35 +00:00
Dan Brown
c32b1686a9 Theme: Added the ability to add views before/after existing ones
Adds a registration system via the logical theme system, to tell
BookStack about views to render before or after a specific template
is included in the system.
2026-01-26 17:16:14 +00:00
Dan Brown
36649a6188 Theme: Updated view registration to be dynamic
Within the responsibility of the theme service instead
of being part of the app configuration.
2026-01-26 11:55:39 +00:00
Dan Brown
ff59bbdc07 Updated translator & dependency attribution before release v25.12.2 2026-01-24 13:53:55 +00:00
Dan Brown
4dc443b7df Updated translations with latest Crowdin changes (#5970) 2026-01-22 17:53:58 +00:00
Dan Brown
19f02d927e Deps: Updated PHP package versions 2026-01-22 17:39:26 +00:00
Dan Brown
da7bedd2e4 Sponsors: Added Onyx 2026-01-13 13:23:54 +00:00
lublak
570ded10fa Set cursor to pointer for drawio diagrams
Add cursor style for drawio diagrams in TinyMCE.
2025-10-31 12:51:04 +01:00
320 changed files with 6692 additions and 4552 deletions

View File

@@ -351,10 +351,25 @@ EXPORT_PDF_COMMAND_TIMEOUT=15
# Only used if 'ALLOW_UNTRUSTED_SERVER_FETCHING=true' which disables security protections.
WKHTMLTOPDF=false
# Allow <script> tags in page content
# Allow JavaScript, and other potentiall dangerous content in page content.
# This also removes CSP-level JavaScript control.
# Note, if set to 'true' the page editor may still escape scripts.
# DEPRECATED: Use 'APP_CONTENT_FILTERING' instead as detailed below. Activiting this option
# effectively sets APP_CONTENT_FILTERING='' (No filtering)
ALLOW_CONTENT_SCRIPTS=false
# Control the behaviour of content filtering, primarily used for page content.
# This setting is a string of characters which represent different available filters:
# - j - Filter out JavaScript and unknown binary data based content
# - h - Filter out unexpected, and potentially dangerous, HTML elements
# - f - Filter out unexpected form elements
# - a - Run content through a more complex allowlist filter
# This defaults to using all filters, unless ALLOW_CONTENT_SCRIPTS is set to true in which case no filters are used.
# Note: These filters are a best-attempt and may not be 100% effective. They are typically a layer used in addition to other security measures.
# Note: The default value will always be the most-strict, so it's advised to leave this unset in your own configuration
# to ensure you are always using the full range of filters.
APP_CONTENT_FILTERING="jfha"
# Indicate if robots/crawlers should crawl your instance.
# Can be 'true', 'false' or 'null'.
# The behaviour of the default 'null' option will depend on the 'app-public' admin setting.
@@ -380,6 +395,18 @@ ALLOWED_IFRAME_HOSTS=null
# Current host and source for the "DRAWIO" setting will be auto-appended to the sources configured.
ALLOWED_IFRAME_SOURCES="https://*.draw.io https://*.youtube.com https://*.youtube-nocookie.com https://*.vimeo.com"
# A list of sources/hostnames that can be loaded as CSS styles within BookStack.
# Space separated if multiple. BookStack host domain is auto-inferred.
# Defaults to a permissive set if not provided.
# Example: ALLOWED_CSS_SOURCES="https://fonts.googleapis.com"
ALLOWED_CSS_SOURCES=null
# A list of sources/hostnames that can be loaded as image content within BookStack.
# Space separated if multiple. BookStack host domain is auto-inferred.
# Defaults to a permissive set if not provided.
# Example: ALLOWED_IMAGE_SOURCES="https://images.example.com data:"
ALLOWED_IMAGE_SOURCES=null
# A list of the sources/hostnames that can be reached by application SSR calls.
# This is used wherever users can provide URLs/hosts in-platform, like for webhooks.
# Host-specific functionality (usually controlled via other options) like auth

View File

@@ -521,3 +521,16 @@ setiawan setiawan (culture.setiawan) :: Indonesian
Donald Mac Kenzie (kiuman) :: Norwegian Bokmal
Gabriel Silver (GabrielBSilver) :: Hebrew
Tomas Darius Davainis (Tomasdd) :: Lithuanian
CriedHero :: Chinese Simplified
Henrik (henrik2105) :: Norwegian Bokmal
FoW (fofwisdom) :: Korean
serinf-lauza :: French
Diyan Nikolaev (nikolaev.diyan) :: Bulgarian
Shadluk Avan (quldosh) :: Uzbek
Marci (MartonPoto) :: Hungarian
Michał Sadurski (wheeskeey) :: Polish
JanDziaslo :: Polish
Charllys Fernandes (CharllysFernandes) :: Portuguese, Brazilian
Ilgiz Zigangirov (inov8) :: Russian
Max Israelsson (Blezie) :: Swedish
Skiddybison5924 (chris-devel0per) :: German

View File

@@ -48,8 +48,7 @@ class RegisterController extends Controller
public function postRegister(Request $request)
{
$this->registrationService->ensureRegistrationAllowed();
$this->validator($request->all())->validate();
$userData = $request->all();
$userData = $this->validator($request->all())->validate();
try {
$user = $this->registrationService->registerUser($userData);

View File

@@ -49,6 +49,11 @@ class OidcService
$url = $provider->getAuthorizationUrl();
session()->put('oidc_pkce_code', $provider->getPkceCode() ?? '');
$returnUrl = Theme::dispatch(ThemeEvents::OIDC_AUTH_PRE_REDIRECT, $url);
if (is_string($returnUrl)) {
$url = $returnUrl;
}
return [
'url' => $url,
'state' => $provider->getState(),

View File

@@ -83,7 +83,7 @@ class RegistrationService
// Email restriction
$this->ensureEmailDomainAllowed($userEmail);
// Ensure user does not already exist
// Ensure the user does not already exist
$alreadyUser = !is_null($this->userRepo->getByEmail($userEmail));
if ($alreadyUser) {
throw new UserRegistrationException(trans('errors.error_user_exists_different_creds', ['email' => $userEmail]), '/login');
@@ -99,7 +99,7 @@ class RegistrationService
$newUser = $this->userRepo->createWithoutActivity($userData, $emailConfirmed);
$newUser->attachDefaultRole();
// Assign social account if given
// Assign a social account if given
if ($socialAccount) {
$newUser->socialAccounts()->save($socialAccount);
}
@@ -107,7 +107,7 @@ class RegistrationService
Activity::add(ActivityType::AUTH_REGISTER, $socialAccount ?? $newUser);
Theme::dispatch(ThemeEvents::AUTH_REGISTER, $authSystem, $newUser);
// Start email confirmation flow if required
// Start the email confirmation flow if required
if ($this->emailConfirmationService->confirmationRequired() && !$emailConfirmed) {
$newUser->save();

View File

@@ -8,6 +8,7 @@ use BookStack\Permissions\PermissionApplicator;
use BookStack\Users\Models\HasCreatorAndUpdater;
use BookStack\Users\Models\OwnableInterface;
use BookStack\Util\HtmlContentFilter;
use BookStack\Util\HtmlContentFilterConfig;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -82,7 +83,8 @@ class Comment extends Model implements Loggable, OwnableInterface
public function safeHtml(): string
{
return HtmlContentFilter::removeScriptsFromHtmlString($this->html ?? '');
$filter = new HtmlContentFilter(new HtmlContentFilterConfig());
return $filter->filterString($this->html ?? '');
}
public function jointPermissions(): HasMany

View File

@@ -65,6 +65,13 @@ class AppServiceProvider extends ServiceProvider
URL::forceScheme($isHttps ? 'https' : 'http');
}
// Set SMTP mail driver to use a local domain matching the app domain,
// which helps avoid defaulting to a 127.0.0.1 domain
if ($appUrl) {
$hostName = parse_url($appUrl, PHP_URL_HOST) ?: null;
config()->set('mail.mailers.smtp.local_domain', $hostName);
}
// Allow longer string lengths after upgrade to utf8mb4
Schema::defaultStringLength(191);

View File

@@ -4,6 +4,8 @@ namespace BookStack\App\Providers;
use BookStack\Theming\ThemeEvents;
use BookStack\Theming\ThemeService;
use BookStack\Theming\ThemeViews;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class ThemeServiceProvider extends ServiceProvider
@@ -24,7 +26,26 @@ class ThemeServiceProvider extends ServiceProvider
{
// Boot up the theme system
$themeService = $this->app->make(ThemeService::class);
$viewFactory = $this->app->make('view');
$themeViews = new ThemeViews($viewFactory->getFinder());
// Use a custom include so that we can insert theme views before/after includes.
// This is done, even if no theme is active, so that view caching does not create problems
// when switching between themes or when switching a theme on/off.
$viewFactory->share('__themeViews', $themeViews);
Blade::directive('include', function ($expression) {
return "<?php echo \$__themeViews->handleViewInclude({$expression}, array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1])); ?>";
});
if (!$themeService->getTheme()) {
return;
}
$themeService->loadModules();
$themeService->readThemeActions();
$themeService->dispatch(ThemeEvents::APP_BOOT, $this->app);
$themeViews->registerViewPathsForTheme($themeService->getModules());
$themeService->dispatch(ThemeEvents::THEME_REGISTER_VIEWS, $themeViews);
}
}

View File

@@ -81,8 +81,7 @@ function setting(?string $key = null, mixed $default = null): mixed
/**
* Get a path to a theme resource.
* Returns null if a theme is not configured and
* therefore a full path is not available for use.
* Returns null if a theme is not configured, and therefore a full path is not available for use.
*/
function theme_path(string $path = ''): ?string
{

View File

@@ -37,10 +37,15 @@ return [
// The limit for all uploaded files, including images and attachments in MB.
'upload_limit' => env('FILE_UPLOAD_SIZE_LIMIT', 50),
// Allow <script> tags to entered within page content.
// <script> tags are escaped by default.
// Even when overridden the WYSIWYG editor may still escape script content.
'allow_content_scripts' => env('ALLOW_CONTENT_SCRIPTS', false),
// Control the behaviour of content filtering, primarily used for page content.
// This setting is a string of characters which represent different available filters:
// - j - Filter out JavaScript and unknown binary data based content
// - h - Filter out unexpected, and potentially dangerous, HTML elements
// - f - Filter out unexpected form elements
// - a - Run content through a more complex allowlist filter
// This defaults to using all filters, unless ALLOW_CONTENT_SCRIPTS is set to true in which case no filters are used.
// Note: These filters are a best-attempt and may not be 100% effective. They are typically a layer used in addition to other security measures.
'content_filtering' => env('APP_CONTENT_FILTERING', env('ALLOW_CONTENT_SCRIPTS', false) === true ? '' : 'jhfa'),
// Allow server-side fetches to be performed to potentially unknown
// and user-provided locations. Primarily used in exports when loading
@@ -48,8 +53,8 @@ return [
'allow_untrusted_server_fetching' => env('ALLOW_UNTRUSTED_SERVER_FETCHING', false),
// Override the default behaviour for allowing crawlers to crawl the instance.
// May be ignored if view has be overridden or modified.
// Defaults to null since, if not set, 'app-public' status used instead.
// May be ignored if the underlying view has been overridden or modified.
// Defaults to null in which case the 'app-public' status is used instead.
'allow_robots' => env('ALLOW_ROBOTS', null),
// Application Base URL, Used by laravel in development commands
@@ -67,6 +72,16 @@ return [
// Current host and source for the "DRAWIO" setting will be auto-appended to the sources configured.
'iframe_sources' => env('ALLOWED_IFRAME_SOURCES', 'https://*.draw.io https://*.youtube.com https://*.youtube-nocookie.com https://*.vimeo.com'),
// A list of sources/hostnames that can be loaded as CSS styles within BookStack.
// Space separated if multiple. BookStack host domain is auto-inferred.
// If not set, a permissive default set is used to reduce potential breakage.
'css_sources' => env('ALLOWED_CSS_SOURCES', null),
// A list of sources/hostnames that can be loaded as image content within BookStack.
// Space separated if multiple. BookStack host domain is auto-inferred.
// If not set, a permissive default set is used to reduce potential breakage.
'image_sources' => env('ALLOWED_IMAGE_SOURCES', null),
// A list of the sources/hostnames that can be reached by application SSR calls.
// This is used wherever users can provide URLs/hosts in-platform, like for webhooks.
// Host-specific functionality (usually controlled via other options) like auth

View File

@@ -22,18 +22,6 @@ return [
// Callback URL for social authentication methods
'callback_url' => env('APP_URL', false),
// LLM Service
// Options: openai
'llm' => env('LLM_SERVICE', ''),
// OpenAI API-compatible service details
'openai' => [
'endpoint' => env('OPENAI_ENDPOINT', 'https://api.openai.com'),
'key' => env('OPENAI_KEY', ''),
'embedding_model' => env('OPENAI_EMBEDDING_MODEL', 'text-embedding-3-small'),
'query_model' => env('OPENAI_QUERY_MODEL', 'gpt-4o'),
],
'github' => [
'client_id' => env('GITHUB_APP_ID', false),
'client_secret' => env('GITHUB_APP_SECRET', false),

View File

@@ -8,12 +8,6 @@
* Do not edit this file unless you're happy to maintain any changes yourself.
*/
// Join up possible view locations
$viewPaths = [realpath(base_path('resources/views'))];
if ($theme = env('APP_THEME', false)) {
array_unshift($viewPaths, base_path('themes/' . $theme));
}
return [
// App theme
@@ -26,7 +20,7 @@ return [
// Most templating systems load templates from disk. Here you may specify
// an array of paths that should be checked for your views. Of course
// the usual Laravel view path has already been registered for you.
'paths' => $viewPaths,
'paths' => [realpath(base_path('resources/views'))],
// Compiled View Path
// This option determines where all the compiled Blade templates will be

View File

@@ -0,0 +1,312 @@
<?php
namespace BookStack\Console\Commands;
use BookStack\Http\HttpRequestService;
use BookStack\Theming\ThemeModule;
use BookStack\Theming\ThemeModuleException;
use BookStack\Theming\ThemeModuleManager;
use BookStack\Theming\ThemeModuleZip;
use GuzzleHttp\Psr7\Request;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
class InstallModuleCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'bookstack:install-module
{location : The URL or path of the module file}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Install a module to the currently configured theme';
protected array $cleanupActions = [];
/**
* Execute the console command.
*/
public function handle(): int
{
$location = $this->argument('location');
// Get the ZIP file containing the module files
$zipPath = $this->getPathToZip($location);
if (!$zipPath) {
$this->cleanup();
return 1;
}
// Validate module zip file (metadata, size, etc...) and get module instance
$zip = new ThemeModuleZip($zipPath);
$themeModule = $this->validateAndGetModuleInfoFromZip($zip);
if (!$themeModule) {
$this->cleanup();
return 1;
}
// Get the theme folder in use, attempting to create one if no active theme in use
$themeFolder = $this->getThemeFolder();
if (!$themeFolder) {
$this->cleanup();
return 1;
}
// Get the modules folder of the theme, attempting to create it if not existing,
// and create a new module manager instance.
$moduleFolder = $this->getModuleFolder($themeFolder);
if (!$moduleFolder) {
$this->cleanup();
return 1;
}
$manager = new ThemeModuleManager($moduleFolder);
// Handle existing modules with the same name
$exitingModulesWithName = $manager->getByName($themeModule->name);
$shouldContinue = $this->handleExistingModulesWithSameName($exitingModulesWithName, $manager);
if (!$shouldContinue) {
$this->cleanup();
return 1;
}
// Extract module ZIP into the theme modules folder
try {
$newModule = $manager->addFromZip($themeModule->name, $zip);
} catch (ThemeModuleException $exception) {
$this->error("ERROR: Failed to install module with error: {$exception->getMessage()}");
$this->cleanup();
return 1;
}
$this->info("Module \"{$newModule->name}\" ({$newModule->getVersion()}) successfully installed!");
$this->info("Install location: {$moduleFolder}/{$newModule->folderName}");
$this->cleanup();
return 0;
}
/**
* @param ThemeModule[] $existingModules
*/
protected function handleExistingModulesWithSameName(array $existingModules, ThemeModuleManager $manager): bool
{
if (count($existingModules) === 0) {
return true;
}
$this->warn("The following modules already exist with the same name:");
foreach ($existingModules as $folder => $module) {
$this->line("{$module->name} ({$folder}:{$module->getVersion()}) - {$module->description}");
}
$this->line('');
$choices = ['Cancel module install', 'Add alongside existing module'];
if (count($existingModules) === 1) {
$choices[] = 'Replace existing module';
}
$choice = $this->choice("What would you like to do?", $choices, 0, null, false);
if ($choice === 'Cancel module install') {
return false;
}
if ($choice === 'Replace existing module') {
$existingModuleFolder = array_key_first($existingModules);
$this->info("Replacing existing module in {$existingModuleFolder} folder");
$manager->deleteModuleFolder($existingModuleFolder);
}
return true;
}
protected function getModuleFolder(string $themeFolder): string|null
{
$path = $themeFolder . DIRECTORY_SEPARATOR . 'modules';
if (file_exists($path) && !is_dir($path)) {
$this->error("ERROR: Cannot create a modules folder, file already exists at {$path}");
return null;
}
if (!file_exists($path)) {
$created = mkdir($path, 0755, true);
if (!$created) {
$this->error("ERROR: Failed to create a modules folder at {$path}");
return null;
}
}
return $path;
}
protected function getThemeFolder(): string|null
{
$path = theme_path('');
if (!$path || !is_dir($path)) {
$shouldCreate = $this->confirm('No active theme folder found, would you like to create one?');
if (!$shouldCreate) {
return null;
}
$folder = 'custom';
while (file_exists(base_path("themes" . DIRECTORY_SEPARATOR . $folder))) {
$folder = 'custom-' . Str::random(4);
}
$path = base_path("themes/{$folder}");
$created = mkdir($path, 0755, true);
if (!$created) {
$this->error('Failed to create a theme folder to use. This may be a permissions issue. Try manually configuring an active theme');
return null;
}
$this->info("Created theme folder at {$path}");
$this->warn("You will need to set APP_THEME={$folder} in your BookStack env configuration to enable this theme!");
}
return $path;
}
protected function validateAndGetModuleInfoFromZip(ThemeModuleZip $zip): ThemeModule|null
{
if (!$zip->exists()) {
$this->error("ERROR: Cannot open ZIP file at {$zip->getPath()}");
return null;
}
if ($zip->getContentsSize() > (50 * 1024 * 1024)) {
$this->error("ERROR: Module ZIP file contents are too large. Maximum size is 50MB");
return null;
}
try {
$themeModule = $zip->getModuleInstance();
} catch (ThemeModuleException $exception) {
$this->error("ERROR: Failed to read module metadata with error: {$exception->getMessage()}");
return null;
}
return $themeModule;
}
protected function downloadModuleFile(string $location): string|null
{
$httpRequests = app()->make(HttpRequestService::class);
$client = $httpRequests->buildClient(30, ['stream' => true]);
$originalUrl = parse_url($location);
$currentLocation = $location;
$maxRedirects = 3;
$redirectCount = 0;
// Follow redirects up to 3 times for the same hostname
do {
$resp = $client->sendRequest(new Request('GET', $currentLocation));
$statusCode = $resp->getStatusCode();
if ($statusCode >= 300 && $statusCode < 400 && $redirectCount < $maxRedirects) {
$redirectLocation = $resp->getHeaderLine('Location');
if ($redirectLocation) {
$redirectUrl = parse_url($redirectLocation);
if (
($originalUrl['host'] ?? '') === ($redirectUrl['host'] ?? '')
&& ($originalUrl['scheme'] ?? '') === ($redirectUrl['scheme'] ?? '')
&& ($originalUrl['port'] ?? '') === ($redirectUrl['port'] ?? '')
) {
$currentLocation = $redirectLocation;
$redirectCount++;
continue;
}
}
}
break;
} while (true);
if ($resp->getStatusCode() >= 300) {
$this->error("ERROR: Failed to download module from {$location}");
$this->error("Download failed with status code {$resp->getStatusCode()}");
return null;
}
$tempFile = tempnam(sys_get_temp_dir(), 'bookstack_module_');
$fileHandle = fopen($tempFile, 'w');
$respBody = $resp->getBody();
$size = 0;
$maxSize = 50 * 1024 * 1024;
while (!$respBody->eof()) {
fwrite($fileHandle, $respBody->read(1024));
$size += 1024;
if ($size > $maxSize) {
fclose($fileHandle);
unlink($tempFile);
$this->error("ERROR: Module ZIP file is too large. Maximum size is 50MB");
return '';
}
}
fclose($fileHandle);
$this->cleanupActions[] = function () use ($tempFile) {
unlink($tempFile);
};
return $tempFile;
}
protected function getPathToZip(string $location): string|null
{
$lowerLocation = strtolower($location);
$isRemote = str_starts_with($lowerLocation, 'http://') || str_starts_with($lowerLocation, 'https://');
if ($isRemote) {
// Warning about fetching from source
$host = parse_url($location, PHP_URL_HOST);
$this->warn("\nThis will download a module from: {$host}\n\nModules can contain code which would have the ability to do anything on the BookStack host server.\nYou should only install modules from trusted sources.");
$trustHost = $this->confirm('Are you sure you trust this source?');
if (!$trustHost) {
return null;
}
// Check if the connection is http. If so, warn the user.
if (str_starts_with($lowerLocation, 'http://')) {
$this->warn("You are downloading a module from an insecure HTTP source.\nWe recommend only using HTTPS sources to avoid various security risks.");
if (!$this->confirm('Are you sure you want to continue without HTTPS?')) {
return null;
}
}
// Download ZIP and get its location
return $this->downloadModuleFile($location);
}
// Validate the file and get the full location
$zipPath = realpath($location);
if (!$zipPath || !is_file($zipPath)) {
$this->error("ERROR: Module file not found at {$location}");
return null;
}
$this->warn("\nThis will install a module from: {$zipPath}\n\nModules can contain code which would have the ability to do anything on the BookStack host server.\nYou should only install modules from trusted sources.");
$trustHost = $this->confirm('Are you sure you want to install this module?');
if (!$trustHost) {
return null;
}
return $zipPath;
}
protected function cleanup(): void
{
foreach ($this->cleanupActions as $action) {
$action();
}
}
}

View File

@@ -1,46 +0,0 @@
<?php
namespace BookStack\Console\Commands;
use BookStack\Entities\EntityProvider;
use BookStack\Entities\Models\Entity;
use BookStack\Search\Queries\SearchVector;
use BookStack\Search\Queries\StoreEntityVectorsJob;
use Illuminate\Console\Command;
class RegenerateVectorsCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'bookstack:regenerate-vectors';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Re-index vectors for all content in the system';
/**
* Execute the console command.
*/
public function handle(EntityProvider $entityProvider)
{
// TODO - Add confirmation before run regarding deletion/time/effort/api-cost etc...
SearchVector::query()->delete();
$types = $entityProvider->all();
foreach ($types as $type => $typeInstance) {
$this->info("Creating jobs to store vectors for {$type} data...");
/** @var Entity[] $entities */
$typeInstance->newQuery()->chunkById(100, function ($entities) {
foreach ($entities as $entity) {
dispatch(new StoreEntityVectorsJob($entity));
}
});
}
}
}

View File

@@ -7,11 +7,14 @@ use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Queries\BookQueries;
use BookStack\Entities\Queries\BookshelfQueries;
use BookStack\Entities\Queries\PageQueries;
use BookStack\Entities\Repos\BookRepo;
use BookStack\Entities\Tools\BookContents;
use BookStack\Http\ApiController;
use BookStack\Permissions\Permission;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
@@ -21,6 +24,7 @@ class BookApiController extends ApiController
protected BookRepo $bookRepo,
protected BookQueries $queries,
protected PageQueries $pageQueries,
protected BookshelfQueries $shelfQueries,
) {
}
@@ -60,13 +64,20 @@ class BookApiController extends ApiController
* View the details of a single book.
* The response data will contain a 'content' property listing the chapter and pages directly within, in
* the same structure as you'd see within the BookStack interface when viewing a book. Top-level
* contents will have a 'type' property to distinguish between pages & chapters.
* contents will have a 'type' property to distinguish between pages and chapters.
*/
public function read(string $id)
{
$book = $this->queries->findVisibleByIdOrFail(intval($id));
$book = $this->forJsonDisplay($book);
$book->load(['createdBy', 'updatedBy', 'ownedBy']);
$book->load([
'createdBy',
'updatedBy',
'ownedBy',
'shelves' => function (BelongsToMany $query) {
$query->select(['id', 'name', 'slug'])->scopes('visible');
}
]);
$contents = (new BookContents($book))->getTree(true, false)->all();
$contentsApiData = (new ApiEntityListFormatter($contents))

View File

@@ -224,9 +224,14 @@ class BookController extends Controller
{
$book = $this->queries->findVisibleBySlugOrFail($bookSlug);
$this->checkOwnablePermission(Permission::BookDelete, $book);
$contextShelf = $this->shelfContext->getContextualShelfForBook($book);
$this->bookRepo->destroy($book);
if ($contextShelf) {
return redirect($contextShelf->getUrl());
}
return redirect('/books');
}

View File

@@ -21,6 +21,8 @@ use BookStack\Exceptions\PermissionsException;
use BookStack\Http\Controller;
use BookStack\Permissions\Permission;
use BookStack\References\ReferenceFetcher;
use BookStack\Util\HtmlContentFilter;
use BookStack\Util\HtmlContentFilterConfig;
use Exception;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Http\Request;
@@ -173,7 +175,7 @@ class PageController extends Controller
}
/**
* Get page from an ajax request.
* Get a page from an ajax request.
*
* @throws NotFoundException
*/
@@ -183,6 +185,10 @@ class PageController extends Controller
$page->setHidden(array_diff($page->getHidden(), ['html', 'markdown']));
$page->makeHidden(['book']);
$filterConfig = HtmlContentFilterConfig::fromConfigString(config('app.content_filtering'));
$filter = new HtmlContentFilter($filterConfig);
$page->html = $filter->filterString($page->html);
return response()->json($page);
}

View File

@@ -12,6 +12,8 @@ use BookStack\Exceptions\NotFoundException;
use BookStack\Facades\Activity;
use BookStack\Http\Controller;
use BookStack\Permissions\Permission;
use BookStack\Util\HtmlContentFilter;
use BookStack\Util\HtmlContentFilterConfig;
use BookStack\Util\SimpleListOptions;
use Illuminate\Http\Request;
use Ssddanbrown\HtmlDiff\Diff;
@@ -101,12 +103,15 @@ class PageRevisionController extends Controller
$prev = $revision->getPreviousRevision();
$prevContent = $prev->html ?? '';
$diff = Diff::excecute($prevContent, $revision->html);
// TODO - Refactor PageContent so we can de-dupe these steps
$rawDiff = Diff::excecute($prevContent, $revision->html);
$filterConfig = HtmlContentFilterConfig::fromConfigString(config('app.content_filtering'));
$filter = new HtmlContentFilter($filterConfig);
$diff = $filter->filterString($rawDiff);
$page->fill($revision->toArray());
// TODO - Refactor PageContent so we don't need to juggle this
$page->html = $revision->html;
$page->html = (new PageContent($page))->render();
$page->html = '';
$this->setPageTitle(trans('entities.pages_revision_named', ['pageName' => $page->getShortName()]));
return view('pages.revision', [

View File

@@ -19,7 +19,7 @@ class Bookshelf extends Entity implements HasDescriptionInterface, HasCoverInter
public float $searchFactor = 1.2;
protected $hidden = ['image_id', 'deleted_at', 'description_html', 'priority', 'default_template_id', 'sort_rule_id', 'entity_id', 'entity_type', 'chapter_id', 'book_id'];
protected $hidden = ['pivot', 'image_id', 'deleted_at', 'description_html', 'priority', 'default_template_id', 'sort_rule_id', 'entity_id', 'entity_type', 'chapter_id', 'book_id'];
protected $fillable = ['name'];
/**

View File

@@ -6,6 +6,7 @@ use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Bookshelf;
use BookStack\Entities\Models\Chapter;
use BookStack\Util\HtmlContentFilter;
use BookStack\Util\HtmlContentFilterConfig;
class EntityHtmlDescription
{
@@ -50,7 +51,13 @@ class EntityHtmlDescription
return $html;
}
return HtmlContentFilter::removeScriptsFromHtmlString($html);
$isEmpty = empty(trim(strip_tags($html)));
if ($isEmpty) {
return '<p></p>';
}
$filter = new HtmlContentFilter(new HtmlContentFilterConfig());
return $filter->filterString($html);
}
public function getPlain(): string

View File

@@ -2,6 +2,7 @@
namespace BookStack\Entities\Tools;
use BookStack\App\AppVersion;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Queries\PageQueries;
use BookStack\Entities\Tools\Markdown\MarkdownToHtml;
@@ -13,6 +14,7 @@ use BookStack\Uploads\ImageRepo;
use BookStack\Uploads\ImageService;
use BookStack\Users\Models\User;
use BookStack\Util\HtmlContentFilter;
use BookStack\Util\HtmlContentFilterConfig;
use BookStack\Util\HtmlDocument;
use BookStack\Util\WebSafeMimeSniffer;
use Closure;
@@ -37,7 +39,14 @@ class PageContent
public function setNewHTML(string $html, User $updater): void
{
$html = $this->extractBase64ImagesFromHtml($html, $updater);
$this->page->html = $this->formatHtml($html);
$html = $this->formatHtml($html);
$themeResult = Theme::dispatch(ThemeEvents::PAGE_CONTENT_PRE_STORE, $html, $this->page);
if (is_string($themeResult)) {
$html = $themeResult;
}
$this->page->html = $html;
$this->page->text = $this->toPlainText();
$this->page->markdown = '';
}
@@ -50,7 +59,14 @@ class PageContent
$markdown = $this->extractBase64ImagesFromMarkdown($markdown, $updater);
$this->page->markdown = $markdown;
$html = (new MarkdownToHtml($markdown))->convert();
$this->page->html = $this->formatHtml($html);
$html = $this->formatHtml($html);
$themeResult = Theme::dispatch(ThemeEvents::PAGE_CONTENT_PRE_STORE, $html, $this->page);
if (is_string($themeResult)) {
$html = $themeResult;
}
$this->page->html = $html;
$this->page->text = $this->toPlainText();
}
@@ -79,7 +95,7 @@ class PageContent
/**
* Convert all inline base64 content to uploaded image files.
* Regex is used to locate the start of data-uri definitions then
* Regex is used to locate the start of data-uri definitions, then
* manual looping over content is done to parse the whole data uri.
* Attempting to capture the whole data uri using regex can cause PHP
* PCRE limits to be hit with larger, multi-MB, files.
@@ -299,7 +315,7 @@ class PageContent
$html = $this->page->html ?? '';
if (empty($html)) {
return $html;
return $this->handlePostRender('');
}
$doc = new HtmlDocument($html);
@@ -317,11 +333,36 @@ class PageContent
$this->updateIdsRecursively($doc->getBody(), 0, $idMap, $changeMap);
}
if (!config('app.allow_content_scripts')) {
HtmlContentFilter::removeScriptsFromDocument($doc);
$cacheKey = $this->getContentCacheKey($doc->getBodyInnerHtml());
$cached = cache()->get($cacheKey, null);
if ($cached !== null) {
return $this->handlePostRender($cached);
}
return $doc->getBodyInnerHtml();
$filterConfig = HtmlContentFilterConfig::fromConfigString(config('app.content_filtering'));
$filter = new HtmlContentFilter($filterConfig);
$filtered = $filter->filterDocument($doc);
$cacheTime = 86400 * 7; // 1 week
cache()->put($cacheKey, $filtered, $cacheTime);
return $this->handlePostRender($filtered);
}
protected function handlePostRender(string $html): string
{
$themeResult = Theme::dispatch(ThemeEvents::PAGE_CONTENT_POST_RENDER, $html, $this->page);
return is_string($themeResult) ? $themeResult : $html;
}
protected function getContentCacheKey(string $html): string
{
$contentHash = md5($html);
$contentId = $this->page->id;
$contentTime = $this->page->updated_at?->timestamp ?? time();
$appVersion = AppVersion::get();
$filterConfig = config('app.content_filtering') ?? '';
return "page-content-cache::{$filterConfig}::{$appVersion}::{$contentId}::{$contentTime}::{$contentHash}";
}
/**

View File

@@ -8,6 +8,8 @@ use BookStack\Entities\Queries\EntityQueries;
use BookStack\Entities\Tools\Markdown\HtmlToMarkdown;
use BookStack\Entities\Tools\Markdown\MarkdownToHtml;
use BookStack\Permissions\Permission;
use BookStack\Util\HtmlContentFilter;
use BookStack\Util\HtmlContentFilterConfig;
class PageEditorData
{
@@ -47,6 +49,7 @@ class PageEditorData
$isDraftRevision = false;
$this->warnings = [];
$editActivity = new PageEditActivity($page);
$lastEditorId = $page->updated_by ?? user()->id;
if ($editActivity->hasActiveEditing()) {
$this->warnings[] = $editActivity->activeEditingMessage();
@@ -58,11 +61,20 @@ class PageEditorData
$page->forceFill($userDraft->only(['name', 'html', 'markdown']));
$isDraftRevision = true;
$this->warnings[] = $editActivity->getEditingActiveDraftMessage($userDraft);
$lastEditorId = $userDraft->created_by;
}
// Get editor type and handle changes
$editorType = $this->getEditorType($page);
$this->updateContentForEditor($page, $editorType);
// Filter HTML content if required
if ($editorType->isHtmlBased() && !old('html') && $lastEditorId !== user()->id) {
$filterConfig = HtmlContentFilterConfig::fromConfigString(config('app.content_filtering'));
$filter = new HtmlContentFilter($filterConfig);
$page->html = $filter->filterString($page->html);
}
return [
'page' => $page,
'book' => $page->book,

View File

@@ -323,7 +323,7 @@ class ExportFormatter
$text .= $description . "\n\n";
}
foreach ($chapter->pages as $page) {
foreach ($chapter->getVisiblePages() as $page) {
$text .= $this->pageToMarkdown($page) . "\n\n";
}

View File

@@ -167,14 +167,26 @@ abstract class Controller extends BaseController
/**
* Redirect to the URL provided in the request as a '_return' parameter.
* Will check that the parameter leads to a URL under the root path of the system.
* Will check that the parameter leads to a URL under the same origin as the application.
*/
protected function redirectToRequest(Request $request): RedirectResponse
{
$basePath = url('/');
$returnUrl = $request->input('_return') ?? $basePath;
if (!str_starts_with($returnUrl, $basePath)) {
// Only allow use of _return on requests where we expect CSRF to be active
// to prevent it potentially being used as an open redirect
$allowedMethods = ['POST', 'PUT', 'PATCH', 'DELETE'];
if (!in_array($request->getMethod(), $allowedMethods)) {
return redirect($basePath);
}
$intendedUrl = parse_url($returnUrl);
$baseUrl = parse_url($basePath);
$isSameOrigin = ($intendedUrl['host'] ?? '') === ($baseUrl['host'] ?? '')
&& ($intendedUrl['scheme'] ?? '') === ($baseUrl['scheme'] ?? '')
&& ($intendedUrl['port'] ?? 0) === ($baseUrl['port'] ?? 0);
if (!$isSameOrigin) {
return redirect($basePath);
}

View File

@@ -102,12 +102,15 @@ class DownloadResponseFactory
protected function getHeaders(string $fileName, int $fileSize, string $mime = 'application/octet-stream'): array
{
$disposition = ($mime === 'application/octet-stream') ? 'attachment' : 'inline';
$downloadName = str_replace('"', '', $fileName);
$downloadName = str_replace(['"', '/', '\\', '$'], '', $fileName);
$downloadName = preg_replace('/[\x00-\x1F\x7F]/', '', $downloadName);
$encodedDownloadName = rawurlencode($downloadName);
return [
'Content-Type' => $mime,
'Content-Length' => $fileSize,
'Content-Disposition' => "{$disposition}; filename=\"{$downloadName}\"",
'Content-Disposition' => "{$disposition}; filename*=UTF-8''{$encodedDownloadName}",
'X-Content-Type-Options' => 'nosniff',
];
}

View File

@@ -17,7 +17,7 @@ class ApiAuthenticate
public function handle(Request $request, Closure $next)
{
// Validate the token and it's users API access
$this->ensureAuthorizedBySessionOrToken();
$this->ensureAuthorizedBySessionOrToken($request);
return $next($request);
}
@@ -28,22 +28,28 @@ class ApiAuthenticate
*
* @throws ApiAuthException
*/
protected function ensureAuthorizedBySessionOrToken(): void
protected function ensureAuthorizedBySessionOrToken(Request $request): void
{
// Return if the user is already found to be signed in via session-based auth.
// This is to make it easy to browser the API via browser after just logging into the system.
if (!user()->isGuest() || session()->isStarted()) {
// Use the active user session already exists.
// This is to make it easy to explore API endpoints via the UI.
if (session()->isStarted()) {
// Ensure the user has API access permission
if (!$this->sessionUserHasApiAccess()) {
throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403);
}
// Only allow GET requests for cookie-based API usage
if ($request->method() !== 'GET') {
throw new ApiAuthException(trans('errors.api_cookie_auth_only_get'), 403);
}
return;
}
// Set our api guard to be the default for this request lifecycle.
auth()->shouldUse('api');
// Validate the token and it's users API access
// Validate the token and its users API access
auth()->authenticate();
}

View File

@@ -1,89 +0,0 @@
<?php
declare(strict_types=1);
namespace BookStack\Search\Queries;
use BookStack\Activity\Models\Tag;
use BookStack\Entities\Models\Entity;
use BookStack\Search\Queries\Services\VectorQueryService;
use Illuminate\Support\Facades\DB;
class EntityVectorGenerator
{
public function __construct(
protected VectorQueryServiceProvider $vectorQueryServiceProvider
) {
}
public function generateAndStore(Entity $entity): void
{
$vectorService = $this->vectorQueryServiceProvider->get();
$text = $this->entityToPlainText($entity);
$chunks = $this->chunkText($text);
$embeddings = $this->chunksToEmbeddings($chunks, $vectorService);
$this->deleteExistingEmbeddingsForEntity($entity);
$this->storeEmbeddings($embeddings, $chunks, $entity);
}
protected function deleteExistingEmbeddingsForEntity(Entity $entity): void
{
SearchVector::query()
->where('entity_type', '=', $entity->getMorphClass())
->where('entity_id', '=', $entity->id)
->delete();
}
protected function storeEmbeddings(array $embeddings, array $textChunks, Entity $entity): void
{
$toInsert = [];
foreach ($embeddings as $index => $embedding) {
$text = $textChunks[$index];
$toInsert[] = [
'entity_id' => $entity->id,
'entity_type' => $entity->getMorphClass(),
'embedding' => DB::raw('VEC_FROMTEXT("[' . implode(',', $embedding) . ']")'),
'text' => $text,
];
}
$chunks = array_chunk($toInsert, 500);
foreach ($chunks as $chunk) {
SearchVector::query()->insert($chunk);
}
}
/**
* @param string[] $chunks
* @return float[] array
*/
protected function chunksToEmbeddings(array $chunks, VectorQueryService $vectorQueryService): array
{
$embeddings = [];
foreach ($chunks as $index => $chunk) {
$embeddings[$index] = $vectorQueryService->generateEmbeddings($chunk);
}
return $embeddings;
}
/**
* @return string[]
*/
protected function chunkText(string $text): array
{
return (new TextChunker(500, ["\n", '.', ' ', '']))->chunk($text);
}
protected function entityToPlainText(Entity $entity): string
{
$tags = $entity->tags()->get();
$tagText = $tags->map(function (Tag $tag) {
return $tag->name . ': ' . $tag->value;
})->join('\n');
return $entity->name . "\n{$tagText}\n" . $entity->{$entity->textField};
}
}

View File

@@ -1,26 +0,0 @@
<?php
namespace BookStack\Search\Queries;
use Exception;
class LlmQueryRunner
{
public function __construct(
protected VectorQueryServiceProvider $vectorQueryServiceProvider,
) {
}
/**
* Run a query against the configured LLM to produce a text response.
* @param VectorSearchResult[] $vectorResults
* @throws Exception
*/
public function run(string $query, array $vectorResults): string
{
$queryService = $this->vectorQueryServiceProvider->get();
$matchesText = array_values(array_map(fn (VectorSearchResult $result) => $result->matchText, $vectorResults));
return $queryService->query($query, $matchesText);
}
}

View File

@@ -1,61 +0,0 @@
<?php
namespace BookStack\Search\Queries;
use BookStack\Http\Controller;
use BookStack\Search\SearchRunner;
use Illuminate\Http\Request;
class QueryController extends Controller
{
public function __construct(
protected SearchRunner $searchRunner,
) {
// TODO - Check via testing
$this->middleware(function ($request, $next) {
if (!VectorQueryServiceProvider::isEnabled()) {
$this->showPermissionError('/');
}
return $next($request);
});
}
/**
* Show the view to start a vector/LLM-based query search.
*/
public function show(Request $request)
{
$query = $request->get('ask', '');
// TODO - Set page title
return view('search.query', [
'query' => $query,
]);
}
/**
* Perform a vector/LLM-based query search.
*/
public function run(Request $request, VectorSearchRunner $searchRunner, LlmQueryRunner $llmRunner)
{
// TODO - Rate limiting
$query = $request->get('query', '');
return response()->eventStream(function () use ($query, $searchRunner, $llmRunner) {
$results = $query ? $searchRunner->run($query) : [];
$entities = [];
foreach ($results as $result) {
$entityKey = $result->entity->getMorphClass() . ':' . $result->entity->id;
if (!isset($entities[$entityKey])) {
$entities[$entityKey] = $result->entity;
}
}
yield ['view' => view('entities.list', ['entities' => $entities])->render()];
yield ['result' => $llmRunner->run($query, $results)];
});
}
}

View File

@@ -1,26 +0,0 @@
<?php
declare(strict_types=1);
namespace BookStack\Search\Queries;
use BookStack\Permissions\Models\JointPermission;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* @property string $entity_type
* @property int $entity_id
* @property string $text
* @property string $embedding
*/
class SearchVector extends Model
{
public $timestamps = false;
public function jointPermissions(): HasMany
{
return $this->hasMany(JointPermission::class, 'entity_id', 'entity_id')
->whereColumn('search_vectors.entity_type', '=', 'joint_permissions.entity_type');
}
}

View File

@@ -1,66 +0,0 @@
<?php
namespace BookStack\Search\Queries\Services;
use BookStack\Http\HttpRequestService;
class OpenAiVectorQueryService implements VectorQueryService
{
protected string $key;
protected string $endpoint;
protected string $embeddingModel;
protected string $queryModel;
public function __construct(
protected array $options,
protected HttpRequestService $http,
) {
// TODO - Some kind of validation of options
$this->key = $this->options['key'] ?? '';
$this->endpoint = $this->options['endpoint'] ?? '';
$this->embeddingModel = $this->options['embedding_model'] ?? '';
$this->queryModel = $this->options['query_model'] ?? '';
}
protected function jsonRequest(string $method, string $uri, array $data): array
{
$fullUrl = rtrim($this->endpoint, '/') . '/' . ltrim($uri, '/');
$client = $this->http->buildClient(30);
$request = $this->http->jsonRequest($method, $fullUrl, $data)
->withHeader('Authorization', 'Bearer ' . $this->key);
$response = $client->sendRequest($request);
return json_decode($response->getBody()->getContents(), true);
}
public function generateEmbeddings(string $text): array
{
$response = $this->jsonRequest('POST', 'v1/embeddings', [
'input' => $text,
'model' => $this->embeddingModel,
]);
return $response['data'][0]['embedding'];
}
public function query(string $input, array $context): string
{
$formattedContext = implode("\n", $context);
$response = $this->jsonRequest('POST', 'v1/chat/completions', [
'model' => $this->queryModel,
'messages' => [
[
'role' => 'developer',
'content' => 'You are a helpful assistant providing search query responses. Be specific, factual and to-the-point in response. Don\'t try to converse or continue the conversation.'
],
[
'role' => 'user',
'content' => "Provide a response to the below given QUERY using the below given CONTEXT. The CONTEXT is split into parts via lines. Ignore any nonsensical lines of CONTEXT.\nQUERY: {$input}\n\nCONTEXT: {$formattedContext}",
]
],
]);
return $response['choices'][0]['message']['content'] ?? '';
}
}

View File

@@ -1,21 +0,0 @@
<?php
namespace BookStack\Search\Queries\Services;
interface VectorQueryService
{
/**
* Generate embedding vectors from the given chunk of text.
* @return float[]
*/
public function generateEmbeddings(string $text): array;
/**
* Query the LLM service using the given user input, and
* relevant context text retrieved locally via a vector search.
* Returns the response output text from the LLM.
*
* @param string[] $context
*/
public function query(string $input, array $context): string;
}

View File

@@ -1,30 +0,0 @@
<?php
declare(strict_types=1);
namespace BookStack\Search\Queries;
use BookStack\Entities\Models\Entity;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class StoreEntityVectorsJob implements ShouldQueue
{
use Queueable;
/**
* Create a new job instance.
*/
public function __construct(
protected Entity $entity
) {
}
/**
* Execute the job.
*/
public function handle(EntityVectorGenerator $generator): void
{
$generator->generateAndStore($this->entity);
}
}

View File

@@ -1,79 +0,0 @@
<?php
declare(strict_types=1);
namespace BookStack\Search\Queries;
use InvalidArgumentException;
/**
* Splits a given string into smaller chunks based on specified delimiters
* and a predefined maximum chunk size. This will work through the given delimiters
* to break down text further and further to fit into the chunk size.
*
* The last delimiter is always an empty string to ensure text can always be broken down.
*/
class TextChunker
{
public function __construct(
protected int $chunkSize,
protected array $delimiterOrder,
) {
if (count($this->delimiterOrder) === 0 || $this->delimiterOrder[count($this->delimiterOrder) - 1] !== '') {
$this->delimiterOrder[] = '';
}
if ($this->chunkSize < 1) {
throw new InvalidArgumentException('Chunk size must be greater than 0');
}
}
public function chunk(string $text): array
{
$delimiter = $this->delimiterOrder[0];
$delimiterLength = strlen($delimiter);
$lines = ($delimiter === '') ? str_split($text, $this->chunkSize) : explode($delimiter, $text);
$cChunk = ''; // Current chunk
$cLength = 0; // Current chunk length
$chunks = []; // Chunks to return
$lDelim = ''; // Last delimiter
foreach ($lines as $index => $line) {
$lineLength = strlen($line);
if ($cLength + $lineLength + $delimiterLength <= $this->chunkSize) {
$cChunk .= $line . $delimiter;
$cLength += $lineLength + $delimiterLength;
$lDelim = $delimiter;
} else if ($lineLength <= $this->chunkSize) {
$chunks[] = trim($cChunk, $delimiter);
$cChunk = $line . $delimiter;
$cLength = $lineLength + $delimiterLength;
$lDelim = $delimiter;
} else {
$subChunks = new static($this->chunkSize, array_slice($this->delimiterOrder, 1));
$subDelimiter = $this->delimiterOrder[1] ?? '';
$subDelimiterLength = strlen($subDelimiter);
foreach ($subChunks->chunk($line) as $subChunk) {
$chunkLength = strlen($subChunk);
if ($cLength + $chunkLength + $subDelimiterLength <= $this->chunkSize) {
$cChunk .= $subChunk . $subDelimiter;
$cLength += $chunkLength + $subDelimiterLength;
$lDelim = $subDelimiter;
} else {
$chunks[] = trim($cChunk, $lDelim);
$cChunk = $subChunk . $subDelimiter;
$cLength = $chunkLength + $subDelimiterLength;
$lDelim = $subDelimiter;
}
}
}
}
if ($cChunk !== '') {
$chunks[] = trim($cChunk, $lDelim);
}
return $chunks;
}
}

View File

@@ -1,38 +0,0 @@
<?php
declare(strict_types=1);
namespace BookStack\Search\Queries;
use BookStack\Http\HttpRequestService;
use BookStack\Search\Queries\Services\OpenAiVectorQueryService;
use BookStack\Search\Queries\Services\VectorQueryService;
class VectorQueryServiceProvider
{
public function __construct(
protected HttpRequestService $http,
) {
}
public function get(): VectorQueryService
{
$service = $this->getServiceName();
if ($service === 'openai') {
return new OpenAiVectorQueryService(config('services.openai'), $this->http);
}
throw new \Exception("No '{$service}' LLM service found");
}
protected static function getServiceName(): string
{
return strtolower(config('services.llm'));
}
public static function isEnabled(): bool
{
return !empty(static::getServiceName());
}
}

View File

@@ -1,17 +0,0 @@
<?php
declare(strict_types=1);
namespace BookStack\Search\Queries;
use BookStack\Entities\Models\Entity;
readonly class VectorSearchResult
{
public function __construct(
public Entity $entity,
public float $distance,
public string $matchText
) {
}
}

View File

@@ -1,54 +0,0 @@
<?php
namespace BookStack\Search\Queries;
use BookStack\Entities\Tools\MixedEntityListLoader;
use BookStack\Permissions\PermissionApplicator;
use Exception;
class VectorSearchRunner
{
public function __construct(
protected VectorQueryServiceProvider $vectorQueryServiceProvider,
protected PermissionApplicator $permissions,
protected MixedEntityListLoader $entityLoader,
) {
}
/**
* Run a vector search query to find results across entities.
* @return VectorSearchResult[]
* @throws Exception
*/
public function run(string $query): array
{
$queryService = $this->vectorQueryServiceProvider->get();
$queryVector = $queryService->generateEmbeddings($query);
// TODO - Test permissions applied
$topMatchesQuery = SearchVector::query()->select('text', 'entity_type', 'entity_id')
->selectRaw('VEC_DISTANCE_COSINE(VEC_FROMTEXT("[' . implode(',', $queryVector) . ']"), embedding) as distance')
->orderBy('distance', 'asc')
->having('distance', '<', 0.6)
->limit(10);
$query = $this->permissions->restrictEntityRelationQuery($topMatchesQuery, 'search_vectors', 'entity_id', 'entity_type');
$topMatches = $query->get();
$this->entityLoader->loadIntoRelations($topMatches->all(), 'entity', true);
$results = [];
foreach ($topMatches as $match) {
if ($match->relationLoaded('entity')) {
$results[] = new VectorSearchResult(
$match->getRelation('entity'),
$match->getAttribute('distance'),
$match->getAttribute('text'),
);
}
}
return $results;
}
}

View File

@@ -6,7 +6,6 @@ use BookStack\Entities\Queries\PageQueries;
use BookStack\Entities\Queries\QueryPopular;
use BookStack\Entities\Tools\SiblingFetcher;
use BookStack\Http\Controller;
use BookStack\Search\Queries\VectorSearchRunner;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;

View File

@@ -6,8 +6,6 @@ use BookStack\Activity\Models\Tag;
use BookStack\Entities\EntityProvider;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Models\Page;
use BookStack\Search\Queries\StoreEntityVectorsJob;
use BookStack\Search\Queries\VectorQueryServiceProvider;
use BookStack\Util\HtmlDocument;
use DOMNode;
use Illuminate\Database\Eloquent\Builder;
@@ -27,7 +25,7 @@ class SearchIndex
public static string $softDelimiters = ".-";
public function __construct(
protected EntityProvider $entityProvider,
protected EntityProvider $entityProvider
) {
}
@@ -39,10 +37,6 @@ class SearchIndex
$this->deleteEntityTerms($entity);
$terms = $this->entityToTermDataArray($entity);
$this->insertTerms($terms);
if (VectorQueryServiceProvider::isEnabled()) {
dispatch(new StoreEntityVectorsJob($entity));
}
}
/**
@@ -53,15 +47,9 @@ class SearchIndex
public function indexEntities(array $entities): void
{
$terms = [];
$vectorQueryEnabled = VectorQueryServiceProvider::isEnabled();
foreach ($entities as $entity) {
$entityTerms = $this->entityToTermDataArray($entity);
array_push($terms, ...$entityTerms);
if ($vectorQueryEnabled) {
dispatch(new StoreEntityVectorsJob($entity));
}
}
$this->insertTerms($terms);

View File

@@ -4,25 +4,17 @@ namespace BookStack\Theming;
use BookStack\Util\CspService;
use BookStack\Util\HtmlContentFilter;
use BookStack\Util\HtmlContentFilterConfig;
use BookStack\Util\HtmlNonceApplicator;
use Illuminate\Contracts\Cache\Repository as Cache;
class CustomHtmlHeadContentProvider
{
/**
* @var CspService
*/
protected $cspService;
/**
* @var Cache
*/
protected $cache;
public function __construct(CspService $cspService, Cache $cache)
{
$this->cspService = $cspService;
$this->cache = $cache;
public function __construct(
protected CspService $cspService,
protected Cache $cache,
protected ThemeService $themeService,
) {
}
/**
@@ -32,8 +24,9 @@ class CustomHtmlHeadContentProvider
public function forWeb(): string
{
$content = $this->getSourceContent();
$hash = md5($content);
$hash = md5($content) . ':' . $this->themeService->getModulesHash();
$html = $this->cache->remember('custom-head-web:' . $hash, 86400, function () use ($content) {
$content .= "\n" . $this->getModuleHeadContent();
return HtmlNonceApplicator::prepare($content);
});
@@ -50,7 +43,8 @@ class CustomHtmlHeadContentProvider
$hash = md5($content);
return $this->cache->remember('custom-head-export:' . $hash, 86400, function () use ($content) {
return HtmlContentFilter::removeScriptsFromHtmlString($content);
$config = new HtmlContentFilterConfig(filterOutNonContentElements: false, useAllowListFilter: false);
return (new HtmlContentFilter($config))->filterString($content);
});
}
@@ -61,4 +55,23 @@ class CustomHtmlHeadContentProvider
{
return setting('app-custom-head', '');
}
/**
* Get any custom head content from installed modules.
*/
protected function getModuleHeadContent(): string
{
$content = '';
foreach ($this->themeService->getModules() as $module) {
$headContentPath = $module->path('head');
if (file_exists($headContentPath) && is_dir($headContentPath)) {
$htmlFiles = glob($headContentPath . '/*.html');
foreach ($htmlFiles as $file) {
$content .= file_get_contents($file);
}
}
}
return $content;
}
}

View File

@@ -5,21 +5,22 @@ namespace BookStack\Theming;
use BookStack\Facades\Theme;
use BookStack\Http\Controller;
use BookStack\Util\FilePathNormalizer;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ThemeController extends Controller
{
/**
* Serve a public file from the configured theme.
*/
public function publicFile(string $theme, string $path)
public function publicFile(string $theme, string $path): StreamedResponse
{
$cleanPath = FilePathNormalizer::normalize($path);
if ($theme !== Theme::getTheme() || !$cleanPath) {
abort(404);
}
$filePath = theme_path("public/{$cleanPath}");
if (!file_exists($filePath)) {
$filePath = Theme::findFirstFile("public/{$cleanPath}");
if (!$filePath) {
abort(404);
}

View File

@@ -87,6 +87,17 @@ class ThemeEvents
*/
const COMMONMARK_ENVIRONMENT_CONFIGURE = 'commonmark_environment_configure';
/**
* OIDC auth pre-redirect event.
* Runs just before BookStack redirects the user to the identity provider for authentication.
* Provides the redirect URL that will be used.
* If the listener returns a string value, that will be used as the redirect URL instead.
*
* @param string $redirectUrl
* @return string|null
*/
const OIDC_AUTH_PRE_REDIRECT = 'oidc_auth_pre_redirect';
/**
* OIDC ID token pre-validate event.
* Runs just before BookStack validates the user ID token data upon login.
@@ -100,6 +111,31 @@ class ThemeEvents
*/
const OIDC_ID_TOKEN_PRE_VALIDATE = 'oidc_id_token_pre_validate';
/**
* Page content post-render event.
* Runs after any display rendering of page content, typically when page content is being processed for viewing.
* Rendering typically includes parsing of page includes, and content filtering.
* Provides the HTML content about to be shown, along with the related page instance.
* If the listener returns a string value, that will be used as the HTML content instead.
*
* @param string $html
* @param \BookStack\Entities\Models\Page $page
* @return string|null
*/
const PAGE_CONTENT_POST_RENDER = 'page_content_post_render';
/**
* Page content pre-store event.
* Runs just before page HTML is stored in the database, after BookStack's own processing.
* Provides the HTML content about to be stored, along with the related page instance.
* If the listener returns a string value, that will be used as the HTML content instead.
*
* @param string $html
* @param \BookStack\Entities\Models\Page $page
* @return string|null
*/
const PAGE_CONTENT_PRE_STORE = 'page_content_pre_store';
/**
* Page include parse event.
* Runs when a page include tag is being parsed, typically when page content is being processed for viewing.
@@ -134,6 +170,16 @@ class ThemeEvents
*/
const ROUTES_REGISTER_WEB_AUTH = 'routes_register_web_auth';
/**
* Theme register views event.
* Called by the theme system when a theme is active, so that custom view templates can be registered
* to be rendered in addition to existing app views.
*
* @param \BookStack\Theming\ThemeViews $themeViews
*/
const THEME_REGISTER_VIEWS = 'theme_register_views';
/**
* Web before middleware action.
* Runs before the request is handled but after all other middleware apart from those

View File

@@ -0,0 +1,59 @@
<?php
namespace BookStack\Theming;
readonly class ThemeModule
{
public function __construct(
public string $name,
public string $description,
public string $version,
public string $folderName,
) {
}
/**
* Create a ThemeModule instance from JSON data.
*
* @throws ThemeModuleException
*/
public static function fromJson(array $data, string $folderName): self
{
if (empty($data['name']) || !is_string($data['name'])) {
throw new ThemeModuleException("Module in folder \"{$folderName}\" is missing a valid 'name' property");
}
if (!isset($data['description']) || !is_string($data['description'])) {
throw new ThemeModuleException("Module in folder \"{$folderName}\" is missing a valid 'description' property");
}
if (!isset($data['version']) || !is_string($data['version'])) {
throw new ThemeModuleException("Module in folder \"{$folderName}\" is missing a valid 'version' property");
}
if (!preg_match('/^v?\d+\.\d+\.\d+(-.*)?$/', $data['version'])) {
throw new ThemeModuleException("Module in folder \"{$folderName}\" has an invalid 'version' format. Expected semantic version format like '1.0.0' or 'v1.0.0'");
}
return new self(
name: $data['name'],
description: $data['description'],
version: $data['version'],
folderName: $folderName,
);
}
/**
* Get a path for a file within this module.
*/
public function path($path = ''): string
{
$component = trim($path, '/');
return theme_path("modules/{$this->folderName}/{$component}");
}
public function getVersion(): string
{
return str_starts_with($this->version, 'v') ? $this->version : 'v' . $this->version;
}
}

View File

@@ -0,0 +1,7 @@
<?php
namespace BookStack\Theming;
class ThemeModuleException extends \Exception
{
}

View File

@@ -0,0 +1,133 @@
<?php
namespace BookStack\Theming;
use Illuminate\Support\Str;
class ThemeModuleManager
{
/** @var array<string, ThemeModule>|null */
protected array|null $loadedModules = null;
public function __construct(
protected string $modulesFolderPath
) {
}
/**
* @return array<string, ThemeModule>
*/
public function getByName(string $name): array
{
return array_filter($this->load(), fn(ThemeModule $module) => $module->name === $name);
}
public function deleteModuleFolder(string $moduleFolderName): void
{
$modules = $this->load();
$module = $modules[$moduleFolderName] ?? null;
if (!$module) {
return;
}
$moduleFolderPath = $module->path('');
if (!file_exists($moduleFolderPath)) {
return;
}
$this->deleteDirectoryRecursively($moduleFolderPath);
unset($this->loadedModules[$moduleFolderName]);
}
/**
* @throws ThemeModuleException
*/
public function addFromZip(string $name, ThemeModuleZip $zip): ThemeModule
{
$baseFolderName = Str::limit(Str::slug($name), 40, '');
$folderName = $baseFolderName;
while (!$baseFolderName || file_exists($this->modulesFolderPath . DIRECTORY_SEPARATOR . $folderName)) {
$folderName = ($baseFolderName ?: 'mod') . '-' . Str::random(4);
}
$folderPath = $this->modulesFolderPath . DIRECTORY_SEPARATOR . $folderName;
$zip->extractTo($folderPath);
$module = $this->loadFromFolder($folderName);
if (!$module) {
throw new ThemeModuleException("Failed to load module from zip file after extraction");
}
return $module;
}
protected function deleteDirectoryRecursively(string $path): void
{
$items = array_diff(scandir($path), ['.', '..']);
foreach ($items as $item) {
$itemPath = $path . DIRECTORY_SEPARATOR . $item;
if (is_dir($itemPath)) {
$this->deleteDirectoryRecursively($itemPath);
} else {
$deleted = unlink($itemPath);
if (!$deleted) {
throw new ThemeModuleException("Failed to delete file at \"{$itemPath}\"");
}
}
}
rmdir($path);
}
public function load(): array
{
if ($this->loadedModules !== null) {
return $this->loadedModules;
}
if (!is_dir($this->modulesFolderPath)) {
return [];
}
$subFolders = array_filter(scandir($this->modulesFolderPath), function ($item) {
return $item !== '.' && $item !== '..' && is_dir($this->modulesFolderPath . DIRECTORY_SEPARATOR . $item);
});
$modules = [];
foreach ($subFolders as $folderName) {
$module = $this->loadFromFolder($folderName);
if ($module) {
$modules[$folderName] = $module;
}
}
$this->loadedModules = $modules;
return $modules;
}
protected function loadFromFolder(string $folderName): ThemeModule|null
{
$moduleJsonFile = $this->modulesFolderPath . DIRECTORY_SEPARATOR . $folderName . DIRECTORY_SEPARATOR . 'bookstack-module.json';
if (!file_exists($moduleJsonFile)) {
return null;
}
try {
$jsonContent = file_get_contents($moduleJsonFile);
$jsonData = json_decode($jsonContent, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new ThemeModuleException("Invalid JSON in module file at \"{$moduleJsonFile}\": " . json_last_error_msg());
}
$module = ThemeModule::fromJson($jsonData, $folderName);
} catch (ThemeModuleException $exception) {
throw $exception;
} catch (\Exception $exception) {
throw new ThemeModuleException("Failed loading module from \"{$moduleJsonFile}\" with error: {$exception->getMessage()}");
}
return $module;
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace BookStack\Theming;
use ZipArchive;
readonly class ThemeModuleZip
{
public function __construct(
protected string $path
) {
}
public function extractTo(string $destinationPath): void
{
$zip = new ZipArchive();
$zip->open($this->path);
$zip->extractTo($destinationPath);
$zip->close();
}
/**
* Read the module's JSON metadata to read it into a ThemeModule instance.
* @throws ThemeModuleException
*/
public function getModuleInstance(): ThemeModule
{
$zip = new ZipArchive();
$open = $zip->open($this->path);
if ($open !== true) {
throw new ThemeModuleException("Unable to open zip file at {$this->path}");
}
$moduleJsonText = $zip->getFromName('bookstack-module.json');
$zip->close();
if ($moduleJsonText === false) {
throw new ThemeModuleException("bookstack-module.json not found within module ZIP at {$this->path}");
}
$moduleJson = json_decode($moduleJsonText, true);
if ($moduleJson === null) {
throw new ThemeModuleException("Could not read JSON from bookstack-module.json within module ZIP at {$this->path}");
}
return ThemeModule::fromJson($moduleJson, '_temp');
}
/**
* Get the path to the zip file.
*/
public function getPath(): string
{
return $this->path;
}
/**
* Check if the zip file exists and that it appears to be a valid zip file.
*/
public function exists(): bool
{
if (!file_exists($this->path)) {
return false;
}
$zip = new ZipArchive();
$open = $zip->open($this->path, ZipArchive::RDONLY);
if ($open === true) {
$zip->close();
return true;
}
return false;
}
/**
* Get the total size of the zip file contents when uncompressed.
*/
public function getContentsSize(): int
{
$zip = new ZipArchive();
if ($zip->open($this->path) !== true) {
return 0;
}
$totalSize = 0;
for ($i = 0; $i < $zip->numFiles; $i++) {
$stat = $zip->statIndex($i);
if ($stat !== false) {
$totalSize += $stat['size'];
}
}
$zip->close();
return $totalSize;
}
}

View File

@@ -6,6 +6,7 @@ use BookStack\Access\SocialDriverManager;
use BookStack\Exceptions\ThemeException;
use Illuminate\Console\Application;
use Illuminate\Console\Application as Artisan;
use Illuminate\View\FileViewFinder;
use Symfony\Component\Console\Command\Command;
class ThemeService
@@ -15,6 +16,11 @@ class ThemeService
*/
protected array $listeners = [];
/**
* @var array<string, ThemeModule>
*/
protected array $modules = [];
/**
* Get the currently configured theme.
* Returns an empty string if not configured.
@@ -76,20 +82,85 @@ class ThemeService
}
/**
* Read any actions from the set theme path if the 'functions.php' file exists.
* Read any actions from the 'functions.php' file of the active theme or its modules.
*/
public function readThemeActions(): void
{
$themeActionsFile = theme_path('functions.php');
if ($themeActionsFile && file_exists($themeActionsFile)) {
$moduleFunctionFiles = array_map(function (ThemeModule $module): string {
return $module->path('functions.php');
}, $this->modules);
$allFunctionFiles = array_merge(array_values($moduleFunctionFiles), [theme_path('functions.php')]);
$filteredFunctionFiles = array_filter($allFunctionFiles, function (string $file): bool {
return $file && file_exists($file);
});
foreach ($filteredFunctionFiles as $functionFile) {
try {
require $themeActionsFile;
require $functionFile;
} catch (\Error $exception) {
throw new ThemeException("Failed loading theme functions file at \"{$themeActionsFile}\" with error: {$exception->getMessage()}");
throw new ThemeException("Failed loading theme functions file at \"{$functionFile}\" with error: {$exception->getMessage()}");
}
}
}
/**
* Read the modules folder and load in any valid theme modules.
* @throws ThemeModuleException
*/
public function loadModules(): void
{
$modulesFolder = theme_path('modules');
if (!$modulesFolder) {
return;
}
$this->modules = (new ThemeModuleManager($modulesFolder))->load();
}
/**
* Get all loaded theme modules.
* @return array<string, ThemeModule>
*/
public function getModules(): array
{
return $this->modules;
}
/**
* Get a hash to represent the currently loaded modules.
*/
public function getModulesHash(): string
{
$key = "";
foreach ($this->modules as $module) {
$key .= $module->name . ':' . $module->version . ';';
}
return md5($key);
}
/**
* Look for a specific file within the theme or its modules.
* Returns the first file found or null if not found.
*/
public function findFirstFile(string $path): ?string
{
$themePath = theme_path($path);
if (file_exists($themePath)) {
return $themePath;
}
foreach ($this->modules as $module) {
$customizedFile = $module->path($path);
if (file_exists($customizedFile)) {
return $customizedFile;
}
}
return null;
}
/**
* @see SocialDriverManager::addSocialDriver
*/

115
app/Theming/ThemeViews.php Normal file
View File

@@ -0,0 +1,115 @@
<?php
namespace BookStack\Theming;
use BookStack\Exceptions\ThemeException;
use Illuminate\View\FileViewFinder;
class ThemeViews
{
/**
* @var array<string, array<string, int>>
*/
protected array $beforeViews = [];
/**
* @var array<string, array<string, int>>
*/
protected array $afterViews = [];
public function __construct(
protected FileViewFinder $finder
) {
}
/**
* Register any extra paths for where we may expect views to be located
* with the FileViewFinder, to make custom views available for use.
* @param ThemeModule[] $modules
*/
public function registerViewPathsForTheme(array $modules): void
{
foreach ($modules as $module) {
$moduleViewsPath = $module->path('views');
if (file_exists($moduleViewsPath) && is_dir($moduleViewsPath)) {
$this->finder->prependLocation($moduleViewsPath);
}
}
$this->finder->prependLocation(theme_path());
}
/**
* Provide the response for a blade template view include.
*/
public function handleViewInclude(string $viewPath, array $data = [], array $mergeData = []): string
{
if (!$this->hasRegisteredViews()) {
return view()->make($viewPath, $data, $mergeData)->render();
}
if (str_contains('book-tree', $viewPath)) {
dd($viewPath, $data);
}
$viewsContent = [
...$this->renderViewSets($this->beforeViews[$viewPath] ?? [], $data, $mergeData),
view()->make($viewPath, $data, $mergeData)->render(),
...$this->renderViewSets($this->afterViews[$viewPath] ?? [], $data, $mergeData),
];
return implode("\n", $viewsContent);
}
/**
* Register a custom view to be rendered before the given target view is included in the template system.
*/
public function renderBefore(string $targetView, string $localView, int $priority = 50): void
{
$this->registerAdjacentView($this->beforeViews, $targetView, $localView, $priority);
}
/**
* Register a custom view to be rendered after the given target view is included in the template system.
*/
public function renderAfter(string $targetView, string $localView, int $priority = 50): void
{
$this->registerAdjacentView($this->afterViews, $targetView, $localView, $priority);
}
public function hasRegisteredViews(): bool
{
return !empty($this->beforeViews) || !empty($this->afterViews);
}
protected function registerAdjacentView(array &$location, string $targetView, string $localView, int $priority = 50): void
{
try {
$viewPath = $this->finder->find($localView);
} catch (\InvalidArgumentException $exception) {
throw new ThemeException("Expected registered view file with name \"{$localView}\" could not be found.");
}
if (!isset($location[$targetView])) {
$location[$targetView] = [];
}
$location[$targetView][$viewPath] = $priority;
}
/**
* @param array<string, int> $viewSet
* @return string[]
*/
protected function renderViewSets(array $viewSet, array $data, array $mergeData): array
{
$paths = array_keys($viewSet);
usort($paths, function (string $a, string $b) use ($viewSet) {
return $viewSet[$a] <=> $viewSet[$b];
});
return array_map(function (string $viewPath) use ($data, $mergeData) {
return view()->file($viewPath, $data, $mergeData)->render();
}, $paths);
}
}

View File

@@ -2,6 +2,7 @@
namespace BookStack\Translation;
use BookStack\Facades\Theme;
use Illuminate\Translation\FileLoader as BaseLoader;
class FileLoader extends BaseLoader
@@ -12,11 +13,6 @@ class FileLoader extends BaseLoader
* Extends Laravel's translation FileLoader to look in multiple directories
* so that we can load in translation overrides from the theme file if wanted.
*
* Note: As of using Laravel 10, this may now be redundant since Laravel's
* file loader supports multiple paths. This needs further testing though
* to confirm if Laravel works how we expect, since we specifically need
* the theme folder to be able to partially override core lang files.
*
* @param string $locale
* @param string $group
* @param string|null $namespace
@@ -32,9 +28,18 @@ class FileLoader extends BaseLoader
if (is_null($namespace) || $namespace === '*') {
$themePath = theme_path('lang');
$themeTranslations = $themePath ? $this->loadPaths([$themePath], $locale, $group) : [];
$originalTranslations = $this->loadPaths($this->paths, $locale, $group);
return array_merge($originalTranslations, $themeTranslations);
$modules = Theme::getModules();
$moduleTranslations = [];
foreach ($modules as $module) {
$modulePath = $module->path('lang');
if (file_exists($modulePath)) {
$moduleTranslations = array_merge($moduleTranslations, $this->loadPaths([$modulePath], $locale, $group));
}
}
$originalTranslations = $this->loadPaths($this->paths, $locale, $group);
return array_merge($originalTranslations, $moduleTranslations, $themeTranslations);
}
return $this->loadNamespaced($locale, $group, $namespace);

View File

@@ -0,0 +1,158 @@
<?php
namespace BookStack\Util;
use BookStack\App\AppVersion;
use HTMLPurifier;
use HTMLPurifier_Config;
use HTMLPurifier_DefinitionCache_Serializer;
use HTMLPurifier_HTML5Config;
use HTMLPurifier_HTMLDefinition;
/**
* Provides a configured HTML Purifier instance.
* https://github.com/ezyang/htmlpurifier
* Also uses this to extend support to HTML5 elements:
* https://github.com/xemlock/htmlpurifier-html5
*/
class ConfiguredHtmlPurifier
{
protected HTMLPurifier $purifier;
protected static bool $cachedChecked = false;
public function __construct()
{
// This is done by the web-server at run-time, with the existing
// storage/framework/cache folder to ensure we're using a server-writable folder.
$cachePath = storage_path('framework/cache/purifier');
$this->createCacheFolderIfNeeded($cachePath);
$config = HTMLPurifier_HTML5Config::createDefault();
$this->setConfig($config, $cachePath);
$this->resetCacheIfNeeded($config);
$htmlDef = $config->getDefinition('HTML', true, true);
if ($htmlDef instanceof HTMLPurifier_HTMLDefinition) {
$this->configureDefinition($htmlDef);
}
$this->purifier = new HTMLPurifier($config);
}
protected function createCacheFolderIfNeeded(string $cachePath): void
{
if (!file_exists($cachePath)) {
mkdir($cachePath, 0777, true);
}
}
protected function resetCacheIfNeeded(HTMLPurifier_Config $config): void
{
if (self::$cachedChecked) {
return;
}
$cachedForVersion = cache('htmlpurifier::cache-version');
$appVersion = AppVersion::get();
if ($cachedForVersion !== $appVersion) {
foreach (['HTML', 'CSS', 'URI'] as $name) {
$cache = new HTMLPurifier_DefinitionCache_Serializer($name);
$cache->flush($config);
}
cache()->set('htmlpurifier::cache-version', $appVersion);
}
self::$cachedChecked = true;
}
protected function setConfig(HTMLPurifier_Config $config, string $cachePath): void
{
$config->set('Cache.SerializerPath', $cachePath);
$config->set('Core.AllowHostnameUnderscore', true);
$config->set('CSS.AllowTricky', true);
$config->set('HTML.SafeIframe', true);
$config->set('HTML.TargetNoopener', false);
$config->set('HTML.TargetNoreferrer', false);
$config->set('Attr.EnableID', true);
$config->set('Attr.ID.HTML5', true);
$config->set('Output.FixInnerHTML', false);
$config->set('URI.SafeIframeRegexp', '%^(http://|https://|//)%');
$config->set('URI.AllowedSchemes', [
'http' => true,
'https' => true,
'mailto' => true,
'ftp' => true,
'nntp' => true,
'news' => true,
'tel' => true,
'file' => true,
]);
// $config->set('Cache.DefinitionImpl', null); // Disable cache during testing
}
public function configureDefinition(HTMLPurifier_HTMLDefinition $definition): void
{
// Allow the object element
$definition->addElement(
'object',
'Inline',
'Flow',
'Common',
[
'data' => 'URI',
'type' => 'Text',
'width' => 'Length',
'height' => 'Length',
]
);
// Allow the embed element
$definition->addElement(
'embed',
'Inline',
'Empty',
'Common',
[
'src' => 'URI',
'type' => 'Text',
'width' => 'Length',
'height' => 'Length',
]
);
// Allow checkbox inputs
$definition->addElement(
'input',
'Formctrl',
'Empty',
'Common',
[
'checked' => 'Bool#checked',
'disabled' => 'Bool#disabled',
'name' => 'Text',
'readonly' => 'Bool#readonly',
'type' => 'Enum#checkbox',
'value' => 'Text',
]
);
// Allow the drawio-diagram attribute on div elements
$definition->addAttribute(
'div',
'drawio-diagram',
'Number',
);
// Allow target="_blank" on links
$definition->addAttribute('a', 'target', 'Enum#_blank');
// Allow mention-ids on links
$definition->addAttribute('a', 'data-mention-user-id', 'Number');
}
public function purify(string $html): string
{
return $this->purifier->purify($html);
}
}

View File

@@ -30,6 +30,8 @@ class CspService
$this->getFrameAncestors(),
$this->getFrameSrc(),
$this->getScriptSrc(),
$this->getStyleSrc(),
$this->getImgSrc(),
$this->getObjectSrc(),
$this->getBaseUri(),
];
@@ -45,6 +47,8 @@ class CspService
$headers = [
$this->getFrameSrc(),
$this->getScriptSrc(),
$this->getStyleSrc(),
$this->getImgSrc(),
$this->getObjectSrc(),
$this->getBaseUri(),
];
@@ -65,7 +69,7 @@ class CspService
*/
protected function getScriptSrc(): string
{
if (config('app.allow_content_scripts')) {
if ($this->scriptFilteringDisabled()) {
return '';
}
@@ -108,13 +112,29 @@ class CspService
*/
protected function getObjectSrc(): string
{
if (config('app.allow_content_scripts')) {
if ($this->scriptFilteringDisabled()) {
return '';
}
return "object-src 'self'";
}
/**
* Creates CSP 'style-src' rule to restrict where styles can be loaded from.
*/
protected function getStyleSrc(): string
{
return 'style-src ' . implode(' ', $this->getAllowedStyleSources());
}
/**
* Creates CSP 'img-src' rule to restrict where images can be loaded from.
*/
protected function getImgSrc(): string
{
return 'img-src ' . implode(' ', $this->getAllowedImageSources());
}
/**
* Creates CSP 'base-uri' rule to restrict what base tags can be set on
* the page to prevent manipulation of relative links.
@@ -124,6 +144,11 @@ class CspService
return "base-uri 'self'";
}
protected function scriptFilteringDisabled(): bool
{
return !HtmlContentFilterConfig::fromConfigString(config('app.content_filtering'))->filterOutJavaScript;
}
protected function getAllowedIframeHosts(): array
{
$hosts = config('app.iframe_hosts') ?? '';
@@ -139,6 +164,51 @@ class CspService
return array_filter($sources);
}
/**
* Get allowed style sources for the style-src directive.
*/
protected function getAllowedStyleSources(): array
{
$configured = config('app.css_sources');
if (is_string($configured)) {
$sources = array_filter(explode(' ', $configured));
array_unshift($sources, "'self'");
return array_values(array_unique($sources));
}
return [
"'self'",
"'unsafe-inline'",
'http:',
'https:',
];
}
/**
* Get allowed image sources for the img-src directive.
*/
protected function getAllowedImageSources(): array
{
$configured = config('app.image_sources');
if (is_string($configured)) {
$sources = array_filter(explode(' ', $configured));
array_unshift($sources, "'self'");
return array_values(array_unique($sources));
}
return [
"'self'",
'data:',
'blob:',
'http:',
'https:',
];
}
/**
* Extract the host name of the configured drawio URL for use in CSP.
* Returns empty string if not in use.

View File

@@ -8,10 +8,46 @@ use DOMNodeList;
class HtmlContentFilter
{
/**
* Remove all the script elements from the given HTML document.
*/
public static function removeScriptsFromDocument(HtmlDocument $doc)
public function __construct(
protected HtmlContentFilterConfig $config
) {
}
public function filterDocument(HtmlDocument $doc): string
{
if ($this->config->filterOutJavaScript) {
$this->filterOutScriptsFromDocument($doc);
}
if ($this->config->filterOutFormElements) {
$this->filterOutFormElementsFromDocument($doc);
}
if ($this->config->filterOutBadHtmlElements) {
$this->filterOutBadHtmlElementsFromDocument($doc);
}
if ($this->config->filterOutNonContentElements) {
$this->filterOutNonContentElementsFromDocument($doc);
}
$filtered = $doc->getBodyInnerHtml();
if ($this->config->useAllowListFilter) {
$filtered = $this->applyAllowListFiltering($filtered);
}
return $filtered;
}
public function filterString(string $html): string
{
return $this->filterDocument(new HtmlDocument($html));
}
protected function applyAllowListFiltering(string $html): string
{
$purifier = new ConfiguredHtmlPurifier();
return $purifier->purify($html);
}
protected function filterOutScriptsFromDocument(HtmlDocument $doc): void
{
// Remove standard script tags
$scriptElems = $doc->queryXPath('//script');
@@ -21,21 +57,21 @@ class HtmlContentFilter
$badLinks = $doc->queryXPath('//*[' . static::xpathContains('@href', 'javascript:') . ']');
static::removeNodes($badLinks);
// Remove forms with calls to JavaScript URI
// Remove elements with form-like attributes with calls to JavaScript URI
$badForms = $doc->queryXPath('//*[' . static::xpathContains('@action', 'javascript:') . '] | //*[' . static::xpathContains('@formaction', 'javascript:') . ']');
static::removeNodes($badForms);
// Remove meta tag to prevent external redirects
$metaTags = $doc->queryXPath('//meta[' . static::xpathContains('@content', 'url') . ']');
static::removeNodes($metaTags);
// Remove data or JavaScript iFrames
// Remove data or JavaScript iFrames & embeds
$badIframes = $doc->queryXPath('//*[' . static::xpathContains('@src', 'data:') . '] | //*[' . static::xpathContains('@src', 'javascript:') . '] | //*[@srcdoc]');
static::removeNodes($badIframes);
// Remove data or JavaScript objects
$badObjects = $doc->queryXPath('//*[' . static::xpathContains('@data', 'data:') . '] | //*[' . static::xpathContains('@data', 'javascript:') . ']');
static::removeNodes($badObjects);
// Remove attributes, within svg children, hiding JavaScript or data uris.
// A bunch of svg element and attribute combinations expose xss possibilities.
// For example, SVG animate tag can exploit javascript in values.
// For example, SVG animate tag can exploit JavaScript in values.
$badValuesAttrs = $doc->queryXPath('//svg//@*[' . static::xpathContains('.', 'data:') . '] | //svg//@*[' . static::xpathContains('.', 'javascript:') . ']');
static::removeAttributes($badValuesAttrs);
@@ -49,23 +85,52 @@ class HtmlContentFilter
static::removeAttributes($onAttributes);
}
/**
* Remove scripts from the given HTML string.
*/
public static function removeScriptsFromHtmlString(string $html): string
protected function filterOutFormElementsFromDocument(HtmlDocument $doc): void
{
if (empty($html)) {
return $html;
// Remove form elements
$formElements = ['form', 'fieldset', 'button', 'textarea', 'select'];
foreach ($formElements as $formElement) {
$matchingFormElements = $doc->queryXPath('//' . $formElement);
static::removeNodes($matchingFormElements);
}
$doc = new HtmlDocument($html);
static::removeScriptsFromDocument($doc);
// Remove non-checkbox inputs
$inputsToRemove = $doc->queryXPath('//input');
/** @var DOMElement $input */
foreach ($inputsToRemove as $input) {
$type = strtolower($input->getAttribute('type'));
if ($type !== 'checkbox') {
$input->parentNode->removeChild($input);
}
}
return $doc->getBodyInnerHtml();
// Remove form attributes
$formAttrs = ['form', 'formaction', 'formmethod', 'formtarget'];
foreach ($formAttrs as $formAttr) {
$matchingFormAttrs = $doc->queryXPath('//@' . $formAttr);
static::removeAttributes($matchingFormAttrs);
}
}
protected function filterOutBadHtmlElementsFromDocument(HtmlDocument $doc): void
{
// Remove meta tag to prevent external redirects
$metaTags = $doc->queryXPath('//meta[' . static::xpathContains('@content', 'url') . ']');
static::removeNodes($metaTags);
}
protected function filterOutNonContentElementsFromDocument(HtmlDocument $doc): void
{
// Remove non-content elements
$formElements = ['link', 'style', 'meta', 'title', 'template'];
foreach ($formElements as $formElement) {
$matchingFormElements = $doc->queryXPath('//' . $formElement);
static::removeNodes($matchingFormElements);
}
}
/**
* Create a xpath contains statement with a translation automatically built within
* Create an x-path 'contains' statement with a translation automatically built within
* to affectively search in a cases-insensitive manner.
*/
protected static function xpathContains(string $property, string $value): string
@@ -99,4 +164,34 @@ class HtmlContentFilter
$parentNode->removeAttribute($attrName);
}
}
/**
* Alias using the old method name to avoid potential compatibility breaks during patch release.
* To remove in future feature release.
* @deprecated Use filterDocument instead.
*/
public static function removeScriptsFromDocument(HtmlDocument $doc): void
{
$config = new HtmlContentFilterConfig(
filterOutNonContentElements: false,
useAllowListFilter: false,
);
$filter = new self($config);
$filter->filterDocument($doc);
}
/**
* Alias using the old method name to avoid potential compatibility breaks during patch release.
* To remove in future feature release.
* @deprecated Use filterString instead.
*/
public static function removeScriptsFromHtmlString(string $html): string
{
$config = new HtmlContentFilterConfig(
filterOutNonContentElements: false,
useAllowListFilter: false,
);
$filter = new self($config);
return $filter->filterString($html);
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace BookStack\Util;
readonly class HtmlContentFilterConfig
{
public function __construct(
public bool $filterOutJavaScript = true,
public bool $filterOutBadHtmlElements = true,
public bool $filterOutFormElements = true,
public bool $filterOutNonContentElements = true,
public bool $useAllowListFilter = true,
) {
}
/**
* Create an instance from a config string, where the string
* is a combination of characters to enable filters.
*/
public static function fromConfigString(string $config): self
{
$config = strtolower($config);
return new self(
filterOutJavaScript: str_contains($config, 'j'),
filterOutBadHtmlElements: str_contains($config, 'h'),
filterOutFormElements: str_contains($config, 'f'),
filterOutNonContentElements: str_contains($config, 'h'),
useAllowListFilter: str_contains($config, 'a'),
);
}
}

View File

@@ -103,7 +103,13 @@ class HtmlDocument
*/
public function getBody(): DOMNode
{
return $this->document->getElementsByTagName('body')[0];
$bodies = $this->document->getElementsByTagName('body');
if ($bodies->length === 0) {
return new DOMElement('body', '');
}
return $bodies[0];
}
/**

View File

@@ -2,6 +2,8 @@
namespace BookStack\Util;
use BookStack\Facades\Theme;
class SvgIcon
{
public function __construct(
@@ -23,12 +25,9 @@ class SvgIcon
$attrString .= $attrName . '="' . $attr . '" ';
}
$iconPath = resource_path('icons/' . $this->name . '.svg');
$themeIconPath = theme_path('icons/' . $this->name . '.svg');
if ($themeIconPath && file_exists($themeIconPath)) {
$iconPath = $themeIconPath;
} elseif (!file_exists($iconPath)) {
$defaultIconPath = resource_path('icons/' . $this->name . '.svg');
$iconPath = Theme::findFirstFile("icons/{$this->name}.svg") ?? $defaultIconPath;
if (!file_exists($iconPath)) {
return '';
}

View File

@@ -19,6 +19,7 @@
"ext-zip": "*",
"bacon/bacon-qr-code": "^3.0",
"dompdf/dompdf": "^3.1",
"ezyang/htmlpurifier": "^4.19",
"guzzlehttp/guzzle": "^7.4",
"intervention/image": "^3.5",
"knplabs/knp-snappy": "^1.5",
@@ -38,7 +39,8 @@
"socialiteproviders/microsoft-azure": "^5.1",
"socialiteproviders/okta": "^4.2",
"socialiteproviders/twitch": "^5.3",
"ssddanbrown/htmldiff": "^2.0.0"
"ssddanbrown/htmldiff": "^2.0.0",
"xemlock/htmlpurifier-html5": "^0.1.12"
},
"require-dev": {
"fakerphp/faker": "^1.21",

1148
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,37 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
// TODO - Handle compatibility with older databases that don't support vectors
Schema::create('search_vectors', function (Blueprint $table) {
$table->string('entity_type', 100);
$table->integer('entity_id');
$table->text('text');
$table->index(['entity_type', 'entity_id']);
});
$table = DB::getTablePrefix() . 'search_vectors';
// TODO - Vector size might need to be dynamic
DB::statement("ALTER TABLE {$table} ADD COLUMN (embedding VECTOR(1536) NOT NULL)");
DB::statement("ALTER TABLE {$table} ADD VECTOR INDEX (embedding) DISTANCE=cosine");
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('search_vectors');
}
};

View File

@@ -79,5 +79,17 @@
"path": "/uploads/images/cover_book/2020-01/sjovall_m117hUWMu40.jpg",
"type": "cover_book",
"uploaded_to": 16
}
},
"shelves": [
{
"id": 1,
"name": "Great reads",
"slug": "great-reads"
},
{
"id": 5,
"name": "Personal Books",
"slug": "personal-books"
}
]
}

View File

@@ -31,13 +31,55 @@ BookStack has a large suite of PHP tests to cover application functionality. We
For details about setting-up, running and writing tests please see the [php-testing.md document](php-testing.md).
## Content Security Policy Controls
BookStack enforces a Content Security Policy (CSP) response header to reduce risk from injected content and untrusted embeds.
For backward compatibility, image and CSS controls are intentionally permissive by default, but can be tightened via environment options.
### Related Environment Options
These values are defined in `.env.example.complete`:
- `ALLOWED_CSS_SOURCES`
- Controls allowed `style-src` sources.
- Defaults to a permissive fallback if unset.
- `ALLOWED_IMAGE_SOURCES`
- Controls allowed `img-src` sources.
- Defaults to a permissive fallback if unset.
Values should be space-separated source expressions.
### Example Configurations
Allow Google Fonts CSS and local styles only:
```bash
ALLOWED_CSS_SOURCES="https://fonts.googleapis.com"
```
Allow local images, embedded data images, and a dedicated image CDN:
```bash
ALLOWED_IMAGE_SOURCES="data: https://images.example.com"
```
### Tightening Guidance
When hardening a deployment:
1. Start with defaults to avoid unexpected breakage.
2. Set explicit `ALLOWED_CSS_SOURCES` and `ALLOWED_IMAGE_SOURCES` values for the domains you actually use.
3. Test key workflows (editor, page display, theme assets, external embeds) and browser console CSP warnings.
4. Remove unnecessary protocols and hosts over time.
## Code Standards
We use tools to manage code standards and formatting within the project. If submitting a PR, formatting as per our project standards would help for clarity but don't worry too much about using/understanding these tools as we can always address issues at a later stage when they're picked up by our automated tools.
### PHP
PHP code standards are managed by [using PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer).
PHP code standards are managed by [using PHP_CodeSniffer](https://github.com/PHPCSStandards/PHP_CodeSniffer).
Static analysis is in place using [PHPStan](https://phpstan.org/) & [Larastan](https://github.com/nunomaduro/larastan).
The below commands can be used to utilise these tools:

View File

@@ -99,6 +99,41 @@ Theme::listen(ThemeEvents::APP_BOOT, function($app) {
});
```
## Custom View Registration Example
Using the logical theme system, you can register custom views to be rendered before/after other existing views, providing a flexible way to add content without needing to override and/or replicate existing content. This is done by listening to the `THEME_REGISTER_VIEWS`.
**Note:** You don't need to use this to override existing views, or register whole new main views to use, since that's done automatically based on their existence. This is just for advanced capabilities like inserting before/after existing views.
This event provides a `ThemeViews` instance which has the following methods made available:
- `renderBefore(string $targetView, string $localView, int $priority)`
- `renderAfter(string $targetView, string $localView, int $priority)`
The target view is the name of that which we want to insert our custom view relative to.
The local view is the name of the view we want to add and render.
The priority provides a suggestion to the ordering of view display, with lower numbers being shown first. This defaults to 50 if not provided.
Here's an example of this in use:
```php
<?php
use BookStack\Facades\Theme;
use BookStack\Theming\ThemeEvents;
use BookStack\Theming\ThemeViews;
Theme::listen(ThemeEvents::THEME_REGISTER_VIEWS, function (ThemeViews $themeViews) {
$themeViews->renderBefore('layouts.parts.header', 'welcome-banner', 4);
$themeViews->renderAfter('layouts.parts.header', 'information-alert');
$themeViews->renderAfter('layouts.parts.header', 'additions.password-notice', 20);
});
```
In this example, we're inserting custom views before and after the main header bar.
BookStack will look for a `welcome-banner.blade.php` file within our theme folder (or a theme module view folder) to render before the header. It'll look for the `information-alert.blade.php` and `additions/password-notice.blade.php` views to render afterwards.
The password notice will be shown above the information alert view, since it has a specified priority of 20, whereas the information alert view would default to a priority of 50.
## Custom Command Registration Example
The logical theme system supports adding custom [artisan commands](https://laravel.com/docs/8.x/artisan) to BookStack.

View File

@@ -0,0 +1,72 @@
# Theme System Modules
A theme system module is a collection of customizations using the [visual](visual-theme-system.md) and [logical](logical-theme-system.md) theme systems, provided along with some metadata, that can be installed alongside other modules within a theme. They can effectively be thought of as "plugins" or "extensions" that can be applied in addition to any customizations in the active theme.
### Module Location
Modules are contained within a folder themselves, which should be located inside a `modules` folder within a [BookStack theme folder](visual-theme-system.md#getting-started).
As an example, starting from the `themes/` top-level folder of a BookStack instance:
```txt
themes
└── my-theme
└── modules
├── module-a
│ └── bookstack-module.json
└── module-b
└── bookstack-module.json
```
### Module Format
A module exists as a folder in the location [as detailed above](#module-location).
The content within the module folder should then follow this format:
- `bookstack-module.json` - REQUIRED - A JSON file containing [the metadata](#module-json-metadata) for the module.
- `functions.php` - OPTIONAL - A PHP file containing code for the [logical theme system](logical-theme-system.md).
- `head/` - OPTIONAL - A folder containing HTML files which will be included into the HTML head of app-views.
- `icons/` - OPTIONAL - A folder containing any icons to use as per [the visual theme system](visual-theme-system.md#customizing-icons).
- `lang/` - OPTIONAL - A folder containing any language files to use as per [the visual theme system](visual-theme-system.md#customizing-text-content).
- `public/` - OPTIONAL - A folder containing any files to expose into public web-space as per [the visual theme system](visual-theme-system.md#publicly-accessible-files).
- `views/` - OPTIONAL - A folder containing any view additions or overrides as per [the visual theme system](visual-theme-system.md#customizing-view-files).
You can create additional directories/files for your own needs within the module, but ideally name them something unique to prevent conflicts with the above structure.
### Module JSON Metadata
Modules are required to have a `bookstack-module.json` file in the top level directory of the module.
This must be a JSON file with the following properties:
- `name` - string - An (ideally unique) name for the module.
- `description` - string - A short description of the module.
- `version` - string - A string version number generally following [semantic versioning](https://semver.org/).
- Examples: `v0.4.0`, `4.3.12`, `v0.1.0-beta4`.
### Customization Order/Precedence
It's possible that multiple modules may override/customize the same content.
Right now, there's no assurance in regard to the order in which modules may be loaded.
Generally they will be used/searched in order of their module folder name, but this is not assured and should not be relied upon.
It's also possible that modules customize the same content as the configured theme.
In this scenario, the theme takes precedence. Modules are designed to be more portable and instance abstract, whereas the theme folder would typically be specific to the instance.
This allows the theme to be used to customize or override module content for the BookStack instance, without altering the module code itself.
### Module Best Practices
Here are some general best practices when it comes to creating modules:
- Use a unique name and clear description so the user can understand the purpose of the module.
- Increment the metadata version on change, keeping to [semver](https://semver.org/) to indicate compatibility of new versions.
- Where possible, prefer to [insert views before/after](logical-theme-system.md#custom-view-registration-example) instead of overriding existing views, to reduce likelihood of conflicts or update troubles.
- When using/registering custom views, use some level of unique namespacing within the view path to prevent potential conflicts with other customizations.
- For example, I may store a view within my module as `views/my-module-name-welcome.blade.php`, to be registered as 'my-module-name-welcome'.
- This is important since views may be resolved from other modules or the active theme, which may/will override your module level view.
### Distribution Format
Modules are expected to be distributed as a compressed ZIP file, where the ZIP contents follow that of a module folder.
BookStack provides a `php artisan bookstack:install-module` command which allows modules to be installed from these ZIP files, either from a local path or from a web URL.
Currently, there's a hardcoded total filesize limit of 50MB for module contents installed via this method.
There is not yet any direct update mechanism for modules, although this is something we may introduce in the future.

View File

@@ -4,7 +4,7 @@ BookStack allows visual customization via the theme system which enables you to
This is part of the theme system alongside the [logical theme system](./logical-theme-system.md).
**Note:** This theme system itself is maintained and supported but usages of this system, including the files you are able to override, are not considered stable and may change upon any update. You should test any customizations made after updates.
**Note:** This theme system itself is maintained and supported, but usages of this system, including the files you are able to override, are not considered stable and may change upon any update. You should test any customizations made after updates.
## Getting Started
@@ -18,6 +18,9 @@ You'll need to tell BookStack to use your theme via the `APP_THEME` option in yo
Content placed in your `themes/<theme_name>/` folder will override the original view files found in the `resources/views` folder. These files are typically [Laravel Blade](https://laravel.com/docs/10.x/blade) files.
As an example, I could override the `resources/views/books/parts/list-item.blade.php` file with my own template at the path `themes/<theme_name>/books/parts/list-item.blade.php`.
In addition to overriding original views, this could be used to add new views for use via the [logical theme system](logical-theme-system.md).
By using the `THEME_REGISTER_VIEWS` logical event, you can also register your views to be rendered before/after existing views. An example of this can be found in our [logical theme guidance](logical-theme-system.md#custom-view-registration-example).
## Customizing Icons
SVG files placed in a `themes/<theme_name>/icons` folder will override any icons of the same name within `resources/icons`. You'd typically want to follow the format convention of the existing icons, where no XML deceleration is included and no width & height attributes are set, to ensure optimal compatibility.
@@ -50,7 +53,7 @@ configured application theme.
There are some considerations to these publicly served files:
- Only a predetermined range "web safe" content-types are currently served.
- Only a predetermined range of "web safe" content-types are currently served.
- This limits running into potential insecure scenarios in serving problematic file types.
- A static 1-day cache time it set on files served from this folder.
- You can use alternative cache-breaking techniques (change of query string) upon changes if needed.

View File

@@ -3321,20 +3321,6 @@ Copyright: Copyright 2022 Romain Menke, Antonio Laguna <*******@******.**>
Source: git+https://github.com/csstools/postcss-plugins.git
Link: https://github.com/csstools/postcss-plugins/tree/main/packages/css-tokenizer#readme
-----------
@emnapi/core
License: MIT
License File: node_modules/@emnapi/core/LICENSE
Copyright: Copyright (c) 2021-present Toyobayashi
Source: git+https://github.com/toyobayashi/emnapi.git
Link: https://github.com/toyobayashi/emnapi#readme
-----------
@emnapi/runtime
License: MIT
License File: node_modules/@emnapi/runtime/LICENSE
Copyright: Copyright (c) 2021-present Toyobayashi
Source: git+https://github.com/toyobayashi/emnapi.git
Link: https://github.com/toyobayashi/emnapi#readme
-----------
@esbuild/linux-x64
License: MIT
Source: git+https://github.com/evanw/esbuild.git
@@ -3784,11 +3770,6 @@ Copyright: Copyright (c) Microsoft Corporation.
Source: https://github.com/tsconfig/bases.git
Link: https://github.com/tsconfig/bases.git
-----------
@tybys/wasm-util
License: MIT
Source: https://github.com/toyobayashi/wasm-util.git
Link: https://github.com/toyobayashi/wasm-util.git
-----------
@types/babel__core
License: MIT
License File: node_modules/@types/babel__core/LICENSE

View File

@@ -8,7 +8,7 @@ aws/aws-sdk-php
License: Apache-2.0
License File: vendor/aws/aws-sdk-php/LICENSE
Source: https://github.com/aws/aws-sdk-php.git
Link: http://aws.amazon.com/sdkforphp
Link: https://aws.amazon.com/sdk-for-php
-----------
bacon/bacon-qr-code
License: BSD-2-Clause
@@ -98,6 +98,13 @@ Copyright: Copyright (c) 2013-2023 Eduardo Gulias Davis
Source: https://github.com/egulias/EmailValidator.git
Link: https://github.com/egulias/EmailValidator
-----------
ezyang/htmlpurifier
License: LGPL-2.1-or-later
License File: vendor/ezyang/htmlpurifier/LICENSE
Copyright: Copyright (C) 1991, 1999 Free Software Foundation, Inc.
Source: https://github.com/ezyang/htmlpurifier.git
Link: http://htmlpurifier.org/
-----------
firebase/php-jwt
License: BSD-3-Clause
License File: vendor/firebase/php-jwt/LICENSE
@@ -237,21 +244,21 @@ Link: https://config.thephpleague.com
league/flysystem
License: MIT
License File: vendor/league/flysystem/LICENSE
Copyright: Copyright (c) 2013-2024 Frank de Jonge
Copyright: Copyright (c) 2013-2026 Frank de Jonge
Source: https://github.com/thephpleague/flysystem.git
Link: https://github.com/thephpleague/flysystem.git
-----------
league/flysystem-aws-s3-v3
License: MIT
License File: vendor/league/flysystem-aws-s3-v3/LICENSE
Copyright: Copyright (c) 2013-2024 Frank de Jonge
Copyright: Copyright (c) 2013-2026 Frank de Jonge
Source: https://github.com/thephpleague/flysystem-aws-s3-v3.git
Link: https://github.com/thephpleague/flysystem-aws-s3-v3.git
-----------
league/flysystem-local
License: MIT
License File: vendor/league/flysystem-local/LICENSE
Copyright: Copyright (c) 2013-2024 Frank de Jonge
Copyright: Copyright (c) 2013-2026 Frank de Jonge
Source: https://github.com/thephpleague/flysystem-local.git
Link: https://github.com/thephpleague/flysystem-local.git
-----------
@@ -323,7 +330,7 @@ License: MIT
License File: vendor/nesbot/carbon/LICENSE
Copyright: Copyright (C) Brian Nesbitt
Source: https://github.com/CarbonPHP/carbon.git
Link: https://carbon.nesbot.com
Link: https://carbonphp.github.io/carbon/
-----------
nette/schema
License: BSD-3-Clause GPL-2.0-only GPL-3.0-only
@@ -465,7 +472,7 @@ Link: https://github.com/php-fig/simple-cache.git
psy/psysh
License: MIT
License File: vendor/psy/psysh/LICENSE
Copyright: Copyright (c) 2012-2025 Justin Hileman
Copyright: Copyright (c) 2012-2026 Justin Hileman
Source: https://github.com/bobthecow/psysh.git
Link: https://psysh.org
-----------
@@ -760,6 +767,13 @@ Copyright: Copyright (c) 2014-present Fabien Potencier
Source: https://github.com/symfony/var-dumper.git
Link: https://symfony.com
-----------
thecodingmachine/safe
License: MIT
License File: vendor/thecodingmachine/safe/LICENSE
Copyright: Copyright (c) 2018 TheCodingMachine
Source: https://github.com/thecodingmachine/safe.git
Link: https://github.com/thecodingmachine/safe.git
-----------
tijsverkoyen/css-to-inline-styles
License: BSD-3-Clause
License File: vendor/tijsverkoyen/css-to-inline-styles/LICENSE.md
@@ -780,3 +794,10 @@ License File: vendor/voku/portable-ascii/LICENSE.txt
Copyright: Copyright (C) 2019 Lars Moelleken
Source: https://github.com/voku/portable-ascii.git
Link: https://github.com/voku/portable-ascii
-----------
xemlock/htmlpurifier-html5
License: MIT
License File: vendor/xemlock/htmlpurifier-html5/LICENSE
Copyright: Copyright (c) 2015 Xemlock
Source: https://github.com/xemlock/htmlpurifier-html5.git
Link: https://github.com/xemlock/htmlpurifier-html5

View File

@@ -125,6 +125,7 @@ return [
'api_incorrect_token_secret' => 'الشفرة المُقدمة لرمز API المستخدم المحدد غير صحيحة',
'api_user_no_api_permission' => 'مالك رمز API المستخدم ليس لديه الصلاحية لإجراء مكالمات API',
'api_user_token_expired' => 'انتهت صلاحية رمز الترخيص المستخدم',
'api_cookie_auth_only_get' => 'Only GET requests are allowed when using the API with cookie-based authentication',
// Settings & Maintenance
'maintenance_test_email_failure' => 'حدث خطأ عند إرسال بريد إلكتروني تجريبي:',

View File

@@ -104,7 +104,7 @@ return [
'sort_rule_op_chapters_first' => 'الفصول الأولى',
'sort_rule_op_chapters_last' => 'الفصول الأخيرة',
'sorting_page_limits' => 'حدود العرض لكل صفحة',
'sorting_page_limits_desc' => 'تعيين عدد العناصر لإظهار كل صفحة في قوائم مختلفة داخل النظام. عادةً ما يكون الرقم الأقل هو الأكثر أداء، بينما وضع رقم أعلى يغني عن النقر على صفحات متعددة. يوصى باستخدام مضاعفات رقم ٣ (18 و 24 و 30 و إلخ...).',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using a multiple of 6 is recommended.',
// Maintenance settings
'maint' => 'الصيانة',

View File

@@ -6,7 +6,7 @@
*/
return [
'failed' => 'Въведените удостоверителни данни не съвпадат с нашите записи.',
'failed' => 'Въведените данни не съвпадат с информацията в системата.',
'throttle' => 'Твърде много опити за влизане. Опитайте пак след :seconds секунди.',
// Login & Register
@@ -65,7 +65,7 @@ return [
'email_confirm_thanks_desc' => 'Почакайте малко, обработвайки потвърждението ви. Ако не сте пренасочени след 3 секунди, то натиснете долу връзката "Продължаване", за да продължите.',
'email_not_confirmed' => 'Имейл адресът не е потвърден',
'email_not_confirmed_text' => 'Вашият емейл адрес все още не е потвърден.',
'email_not_confirmed_text' => 'Вашият имейл адрес все още не е потвърден.',
'email_not_confirmed_click_link' => 'Моля да последвате линка, който ви беше изпратен непосредствено след регистрацията.',
'email_not_confirmed_resend' => 'Ако не откривате писмото, може да го изпратите отново като попълните формуляра по-долу.',
'email_not_confirmed_resend_button' => 'Изпрати отново емейла за потвърждение',
@@ -91,7 +91,7 @@ return [
'mfa_option_totp_title' => 'Мобилно приложение',
'mfa_option_totp_desc' => 'За да използваш многофакторно удостоверяване, ще ти трябва мобилно приложение, което поддържа временни еднократни пароли (TOTP), като например Google Authenticator, Authy или Microsoft Authenticator.',
'mfa_option_backup_codes_title' => 'Резервни кодове',
'mfa_option_backup_codes_desc' => 'Generates a set of one-time-use backup codes which you\'ll enter on login to verify your identity. Make sure to store these in a safe & secure place.',
'mfa_option_backup_codes_desc' => 'Генерира набор от еднократни резервни кодове, които ще въвеждате при влизане, за да потвърдите самоличността си. Уверете се, че ги съхранявате на безопасно и сигурно място.',
'mfa_gen_confirm_and_enable' => 'Потвърди и включи',
'mfa_gen_backup_codes_title' => 'Настройка на резервни кодове',
'mfa_gen_backup_codes_desc' => 'Запази този лист с кодове на сигурно място. Когато достъпваш системата, ще можеш да използваш един от тези кодове като вторичен механизъм за удостоверяване.',

View File

@@ -6,7 +6,7 @@ return [
// Buttons
'cancel' => 'Отказ',
'close' => 'Close',
'close' => 'Затвори',
'confirm' => 'Потвърждаване',
'back' => 'Назад',
'save' => 'Запис',
@@ -20,7 +20,7 @@ return [
'description' => 'Описание',
'role' => 'Роля',
'cover_image' => 'Образ на корицата',
'cover_image_description' => 'This image should be approximately 440x250px although it will be flexibly scaled & cropped to fit the user interface in different scenarios as required, so actual dimensions for display will differ.',
'cover_image_description' => 'Изображението трябва да е около 440x250 px. Тъй като ще се мащабира и изрязва автоматично спрямо нуждите на интерфейса, крайните размери при показване може да се различават.',
// Actions
'actions' => 'Действия',
@@ -30,8 +30,8 @@ return [
'create' => 'Създаване',
'update' => 'Обновяване',
'edit' => 'Редактиране',
'archive' => 'Archive',
'unarchive' => 'Un-Archive',
'archive' => 'Архивирай',
'unarchive' => 'Разархивирай',
'sort' => 'Сортиране',
'move' => 'Преместване',
'copy' => 'Копиране',
@@ -44,7 +44,7 @@ return [
'remove' => 'Премахване',
'add' => 'Добавяне',
'configure' => 'Конфигуриране',
'manage' => 'Manage',
'manage' => 'Управлявай',
'fullscreen' => 'Цял екран',
'favourite' => 'Любимо',
'unfavourite' => 'Не е любимо',
@@ -54,7 +54,7 @@ return [
'filter_clear' => 'Изчистване на филтрите',
'download' => 'Изтегляне',
'open_in_tab' => 'Отваряне в раздел',
'open' => 'Open',
'open' => 'Отвори',
// Sort Options
'sort_options' => 'Опции за сортиране',
@@ -111,5 +111,5 @@ return [
'terms_of_service' => 'Условия на услугата',
// OpenSearch
'opensearch_description' => 'Search :appName',
'opensearch_description' => 'Търси :appName',
];

View File

@@ -13,7 +13,7 @@ return [
'cancel' => 'Отказ',
'save' => 'Запис',
'close' => 'Затваряне',
'apply' => 'Apply',
'apply' => 'Приложи',
'undo' => 'Отмяна',
'redo' => 'Повтаряне',
'left' => 'Вляво',

View File

@@ -10,7 +10,7 @@ return [
// Auth
'error_user_exists_different_creds' => 'Потребител с емайл :email вече съществува но с други данни.',
'auth_pre_register_theme_prevention' => 'User account could not be registered for the provided details',
'auth_pre_register_theme_prevention' => 'Потребителски профил не може да бъде създаден с посочената информация',
'email_already_confirmed' => 'Емейлът вече беше потвърден. Моля опитрайте да влезете.',
'email_confirmation_invalid' => 'Този код за достъп не е валиден или вече е бил използван, Моля опитай да се регистрираш отново.',
'email_confirmation_expired' => 'Кодът за потвърждение изтече, нов емейл за потвърждение беше изпратен.',
@@ -37,7 +37,7 @@ return [
'social_driver_not_found' => 'Кодът за връзка със социалната мрежа не съществува',
'social_driver_not_configured' => 'Социалните настройки на твоя :socialAccount не са конфигурирани правилно.',
'invite_token_expired' => 'Твоята покана е изтекла. Вместо това може да пробваш да възстановиш паролата на профила си.',
'login_user_not_found' => 'A user for this action could not be found.',
'login_user_not_found' => 'Потребител за това действие не може да бъде намерено.',
// System
'path_not_writable' => 'Не може да се качи файл в :filePath. Увери се на сървъра, че в пътя може да се записва.',
@@ -125,6 +125,7 @@ return [
'api_incorrect_token_secret' => 'Секретния код, който беше предоставен за достъп до API-а е неправилен',
'api_user_no_api_permission' => 'Собственика на АPI кода няма право да прави API заявки',
'api_user_token_expired' => 'Кода за достъп, който беше използван, вече не е валиден',
'api_cookie_auth_only_get' => 'Only GET requests are allowed when using the API with cookie-based authentication',
// Settings & Maintenance
'maintenance_test_email_failure' => 'Беше върната грешка, когато се изпрати тестовият емейл:',

View File

@@ -104,7 +104,7 @@ return [
'sort_rule_op_chapters_first' => 'Chapters First',
'sort_rule_op_chapters_last' => 'Chapters Last',
'sorting_page_limits' => 'Per-Page Display Limits',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using an even multiple of 3 (18, 24, 30, etc...) is recommended.',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using a multiple of 6 is recommended.',
// Maintenance settings
'maint' => 'Поддръжка',

View File

@@ -125,6 +125,7 @@ return [
'api_incorrect_token_secret' => 'The secret provided for the given used API token is incorrect',
'api_user_no_api_permission' => 'The owner of the used API token does not have permission to make API calls',
'api_user_token_expired' => 'The authorization token used has expired',
'api_cookie_auth_only_get' => 'Only GET requests are allowed when using the API with cookie-based authentication',
// Settings & Maintenance
'maintenance_test_email_failure' => 'Error thrown when sending a test email:',

View File

@@ -104,7 +104,7 @@ return [
'sort_rule_op_chapters_first' => 'Chapters First',
'sort_rule_op_chapters_last' => 'Chapters Last',
'sorting_page_limits' => 'Per-Page Display Limits',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using an even multiple of 3 (18, 24, 30, etc...) is recommended.',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using a multiple of 6 is recommended.',
// Maintenance settings
'maint' => 'Maintenance',

View File

@@ -125,6 +125,7 @@ return [
'api_incorrect_token_secret' => 'Tajni ključ naveden za dati korišteni API token nije tačan',
'api_user_no_api_permission' => 'Vlasnik korištenog API tokena nema dozvolu za upućivanje API poziva',
'api_user_token_expired' => 'Autorizacijski token je istekao',
'api_cookie_auth_only_get' => 'Only GET requests are allowed when using the API with cookie-based authentication',
// Settings & Maintenance
'maintenance_test_email_failure' => 'Došlo je do greške prilikom slanja testnog e-maila:',

View File

@@ -104,7 +104,7 @@ return [
'sort_rule_op_chapters_first' => 'Chapters First',
'sort_rule_op_chapters_last' => 'Chapters Last',
'sorting_page_limits' => 'Per-Page Display Limits',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using an even multiple of 3 (18, 24, 30, etc...) is recommended.',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using a multiple of 6 is recommended.',
// Maintenance settings
'maint' => 'Maintenance',

View File

@@ -125,6 +125,7 @@ return [
'api_incorrect_token_secret' => 'El secret proporcionat per al testimoni dAPI utilitzat no és correcte.',
'api_user_no_api_permission' => 'El propietari del testimoni API utilitzat no té permís per a fer crides a lAPI.',
'api_user_token_expired' => 'El testimoni dautorització utilitzat ha caducat.',
'api_cookie_auth_only_get' => 'Only GET requests are allowed when using the API with cookie-based authentication',
// Settings & Maintenance
'maintenance_test_email_failure' => 'Sha produït un error en enviar el correu electrònic de prova:',

View File

@@ -104,7 +104,7 @@ return [
'sort_rule_op_chapters_first' => 'Capítols a l\'inici',
'sort_rule_op_chapters_last' => 'Capítols al final',
'sorting_page_limits' => 'Per-Page Display Limits',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using an even multiple of 3 (18, 24, 30, etc...) is recommended.',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using a multiple of 6 is recommended.',
// Maintenance settings
'maint' => 'Manteniment',

View File

@@ -109,7 +109,7 @@ return [
'import_zip_cant_read' => 'Nelze načíst ZIP soubor.',
'import_zip_cant_decode_data' => 'Nelze najít a dekódovat data.json v archivu ZIP.',
'import_zip_no_data' => 'ZIP archiv neobsahuje knihy, kapitoly nebo stránky.',
'import_zip_data_too_large' => 'ZIP data.json content exceeds the configured application maximum upload size.',
'import_zip_data_too_large' => 'Obsah souboru data.json v archivu ZIP překračuje maximální povolenou velikost.',
'import_validation_failed' => 'Importování ZIP selhalo s chybami:',
'import_zip_failed_notification' => 'Nepodařilo se naimportovat ZIP soubor.',
'import_perms_books' => 'Chybí vám požadovaná oprávnění k vytvoření knih.',
@@ -125,6 +125,7 @@ return [
'api_incorrect_token_secret' => 'Poskytnutý Token Secret neodpovídá použitému API tokenu',
'api_user_no_api_permission' => 'Vlastník použitého API tokenu nemá oprávnění provádět API volání',
'api_user_token_expired' => 'Platnost autorizačního tokenu vypršela',
'api_cookie_auth_only_get' => 'Při používání API s ověřováním pomocí souborů cookie jsou povoleny pouze požadavky GET',
// Settings & Maintenance
'maintenance_test_email_failure' => 'Při posílání testovacího e-mailu nastala chyba:',

View File

@@ -104,7 +104,7 @@ return [
'sort_rule_op_chapters_first' => 'Kapitoly jako první',
'sort_rule_op_chapters_last' => 'Kapitoly jako poslední',
'sorting_page_limits' => 'Počet zobrazených položek na stránce',
'sorting_page_limits_desc' => 'Nastavte, kolik položek se má zobrazit na stránce v různých seznamech na webu. Obvykle bude nižší počet výkonnější, zatímco vyšší počet eliminuje nutnost proklikávat se několika stránkami. Doporučuje se použít sudý násobek čísla 3 (18, 24, 30 atd.).',
'sorting_page_limits_desc' => 'Nastavte, kolik položek se má zobrazit na stránce v různých seznamech na webu. Obvykle bude nižší počet výkonnější, zatímco vyšší počet eliminuje nutnost proklikávat se několika stránkami. Doporučuje se použít násobek čísla 6.',
// Maintenance settings
'maint' => 'Údržba',

View File

@@ -106,7 +106,7 @@ return [
'uploaded' => 'Nahrávání :attribute se nezdařilo.',
'zip_file' => ':attribute musí odkazovat na soubor v archivu ZIP.',
'zip_file_size' => 'The file :attribute must not exceed :size MB.',
'zip_file_size' => 'Soubor :attribute nesmí překročit :size MB.',
'zip_file_mime' => ':attribute musí odkazovat na soubor typu :validTypes, nalezen :foundType.',
'zip_model_expected' => 'Očekáván datový objekt, ale nalezen „:type“.',
'zip_unique' => ':attribute musí být jedinečný pro typ objektu v archivu ZIP.',

View File

@@ -125,6 +125,7 @@ return [
'api_incorrect_token_secret' => 'Mae\'r gyfrinach a ddarparwyd ar gyfer y tocyn API defnyddiedig a roddwyd yn anghywir',
'api_user_no_api_permission' => 'Nid oes gan berchennog y tocyn API a ddefnyddiwyd ganiatâd i wneud galwadau API',
'api_user_token_expired' => 'Mae\'r tocyn awdurdodi a ddefnyddiwyd wedi dod i ben',
'api_cookie_auth_only_get' => 'Only GET requests are allowed when using the API with cookie-based authentication',
// Settings & Maintenance
'maintenance_test_email_failure' => 'Gwall a daflwyd wrth anfon e-bost prawf:',

View File

@@ -104,7 +104,7 @@ return [
'sort_rule_op_chapters_first' => 'Chapters First',
'sort_rule_op_chapters_last' => 'Chapters Last',
'sorting_page_limits' => 'Per-Page Display Limits',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using an even multiple of 3 (18, 24, 30, etc...) is recommended.',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using a multiple of 6 is recommended.',
// Maintenance settings
'maint' => 'Cynnal',

View File

@@ -48,7 +48,7 @@ return [
'superscript' => 'Hævet',
'subscript' => 'Sænket',
'text_color' => 'Tekstfarve',
'highlight_color' => 'Highlight color',
'highlight_color' => 'Fremhævelsesfarve',
'custom_color' => 'Tilpasset farve',
'remove_color' => 'Fjern farve',
'background_color' => 'Baggrundsfarve',

View File

@@ -252,7 +252,7 @@ return [
'pages_edit_switch_to_markdown_stable' => '(Stabilt indhold)',
'pages_edit_switch_to_wysiwyg' => 'Skift til WYSIWYG redigering',
'pages_edit_switch_to_new_wysiwyg' => 'Skift til ny WYSIWYG (Hvad man ser, er hvad man får)',
'pages_edit_switch_to_new_wysiwyg_desc' => '(In Beta Testing)',
'pages_edit_switch_to_new_wysiwyg_desc' => '(I Beta Test)',
'pages_edit_set_changelog' => 'Sæt ændringsoversigt',
'pages_edit_enter_changelog_desc' => 'Indtast en kort beskrivelse af ændringer du har lavet',
'pages_edit_enter_changelog' => 'Indtast ændringsoversigt',
@@ -397,11 +397,11 @@ return [
'comment' => 'Kommentar',
'comments' => 'Kommentarer',
'comment_add' => 'Tilføj kommentar',
'comment_none' => 'No comments to display',
'comment_none' => 'Ingen kommentarer at vise',
'comment_placeholder' => 'Skriv en kommentar her',
'comment_thread_count' => ':count Comment Thread|:count Comment Threads',
'comment_thread_count' => ':count Kommentar Tråde:count Kommentar Tråde',
'comment_archived_count' => ':count Arkiveret',
'comment_archived_threads' => 'Archived Threads',
'comment_archived_threads' => 'Arkiverede Tråde',
'comment_save' => 'Gem kommentar',
'comment_new' => 'Ny kommentar',
'comment_created' => 'kommenteret :createDiff',
@@ -410,8 +410,8 @@ return [
'comment_deleted_success' => 'Kommentar slettet',
'comment_created_success' => 'Kommentaren er tilføjet',
'comment_updated_success' => 'Kommentaren er opdateret',
'comment_archive_success' => 'Comment archived',
'comment_unarchive_success' => 'Comment un-archived',
'comment_archive_success' => 'Kommentar arkiveret',
'comment_unarchive_success' => 'Kommentaren er ikke længere arkiveret',
'comment_view' => 'Se kommentar',
'comment_jump_to_thread' => 'Hop til tråd',
'comment_delete_confirm' => 'Er du sikker på, at du vil slette denne kommentar?',

View File

@@ -109,7 +109,7 @@ return [
'import_zip_cant_read' => 'Kunne ikke læse ZIP-filen.',
'import_zip_cant_decode_data' => 'Kunne ikke finde og afkode ZIP data.json-indhold.',
'import_zip_no_data' => 'ZIP-filens data har ikke noget forventet bog-, kapitel- eller sideindhold.',
'import_zip_data_too_large' => 'ZIP data.json content exceeds the configured application maximum upload size.',
'import_zip_data_too_large' => 'Indholdet af ZIP data.json overstiger den konfigurerede maksimale uploadstørrelse for applikationen.',
'import_validation_failed' => 'Import ZIP kunne ikke valideres med fejl:',
'import_zip_failed_notification' => 'Kunne ikke importere ZIP-fil.',
'import_perms_books' => 'Du mangler de nødvendige tilladelser til at oprette bøger.',
@@ -125,6 +125,7 @@ return [
'api_incorrect_token_secret' => 'Hemmeligheden leveret til det givne anvendte API-token er forkert',
'api_user_no_api_permission' => 'Ejeren af den brugte API token har ikke adgang til at foretage API-kald',
'api_user_token_expired' => 'Den brugte godkendelsestoken er udløbet',
'api_cookie_auth_only_get' => 'Only GET requests are allowed when using the API with cookie-based authentication',
// Settings & Maintenance
'maintenance_test_email_failure' => 'Følgende fejl opstod under afsendelse af testemail:',

View File

@@ -11,8 +11,8 @@ return [
'updated_page_subject' => 'Opdateret side: :pageName',
'updated_page_intro' => 'En side er blevet opdateret i :appName:',
'updated_page_debounce' => 'For at forhindre en masse af notifikationer, i et stykke tid vil du ikke blive sendt notifikationer for yderligere redigeringer til denne side af den samme editor.',
'comment_mention_subject' => 'You have been mentioned in a comment on page: :pageName',
'comment_mention_intro' => 'You were mentioned in a comment on :appName:',
'comment_mention_subject' => 'Du er blevet nævnt i en kommentar på siden: :pageName',
'comment_mention_intro' => 'Du blev nævnt i en kommentar på :appName:',
'detail_page_name' => 'Sidens navn:',
'detail_page_path' => 'Sidesti:',

View File

@@ -23,7 +23,7 @@ return [
'notifications_desc' => 'Administrer de e-mail-notifikationer, du modtager, når visse aktiviteter udføres i systemet.',
'notifications_opt_own_page_changes' => 'Adviser ved ændringer af sider, jeg ejer',
'notifications_opt_own_page_comments' => 'Adviser ved kommentarer på sider, jeg ejer',
'notifications_opt_comment_mentions' => 'Notify when I\'m mentioned in a comment',
'notifications_opt_comment_mentions' => 'Giv besked, når jeg er nævnt i en kommentar',
'notifications_opt_comment_replies' => 'Adviser ved svar på mine kommentarer',
'notifications_save' => 'Gem indstillinger',
'notifications_update_success' => 'Indstillinger for notifikationer er blevet opdateret!',

View File

@@ -75,8 +75,8 @@ return [
'reg_confirm_restrict_domain_placeholder' => 'Ingen restriktion opsat',
// Sorting Settings
'sorting' => 'Lists & Sorting',
'sorting_book_default' => 'Default Book Sort Rule',
'sorting' => 'Lister & Sortering',
'sorting_book_default' => 'Standardregel for sortering af bog',
'sorting_book_default_desc' => 'Vælg den standardsorteringsregel, der skal gælde for nye bøger. Dette påvirker ikke eksisterende bøger og kan tilsidesættes for hver enkelt bog.',
'sorting_rules' => 'Regler for sortering',
'sorting_rules_desc' => 'Det er foruddefinerede sorteringsoperationer, som kan anvendes på indhold i systemet.',
@@ -103,8 +103,8 @@ return [
'sort_rule_op_updated_date' => 'Opdateret dato',
'sort_rule_op_chapters_first' => 'Kapitler først',
'sort_rule_op_chapters_last' => 'De sidste kapitler',
'sorting_page_limits' => 'Per-Page Display Limits',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using an even multiple of 3 (18, 24, 30, etc...) is recommended.',
'sorting_page_limits' => 'Visningsgrænser pr. side',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using a multiple of 6 is recommended.',
// Maintenance settings
'maint' => 'Vedligeholdelse',
@@ -197,13 +197,13 @@ return [
'role_import_content' => 'Importer indhold',
'role_editor_change' => 'Skift side editor',
'role_notifications' => 'Modtag og administrer notifikationer',
'role_permission_note_users_and_roles' => 'These permissions will technically also provide visibility & searching of users & roles in the system.',
'role_permission_note_users_and_roles' => 'Disse tilladelser vil teknisk set også give synlighed og søgning efter brugere og roller i systemet.',
'role_asset' => 'Tilladelser for medier og "assets"',
'roles_system_warning' => 'Vær opmærksom på, at adgang til alle af de ovennævnte tre tilladelser, kan give en bruger mulighed for at ændre deres egne brugerrettigheder eller brugerrettigheder for andre i systemet. Tildel kun roller med disse tilladelser til betroede brugere.',
'role_asset_desc' => 'Disse tilladelser kontrollerer standardadgang til medier og "assets" i systemet. Tilladelser til bøger, kapitler og sider tilsidesætter disse tilladelser.',
'role_asset_admins' => 'Administratorer får automatisk adgang til alt indhold, men disse indstillinger kan vise eller skjule UI-indstillinger.',
'role_asset_image_view_note' => 'Dette vedrører synlighed i billedhåndteringen. Den faktiske adgang til uploadede billedfiler vil afhænge af systemets billedlagringsindstilling.',
'role_asset_users_note' => 'These permissions will technically also provide visibility & searching of users in the system.',
'role_asset_users_note' => 'Disse tilladelser vil teknisk set også give synlighed og søgning efter brugere i systemet.',
'role_all' => 'Alle',
'role_own' => 'Eget',
'role_controlled_by_asset' => 'Styres af det medie/"asset", de uploades til',

View File

@@ -106,7 +106,7 @@ return [
'uploaded' => 'Filen kunne ikke oploades. Serveren accepterer muligvis ikke filer af denne størrelse.',
'zip_file' => 'Attributten skal henvise til en fil i ZIP.',
'zip_file_size' => 'The file :attribute must not exceed :size MB.',
'zip_file_size' => 'Filen :attribute må ikke overstige: størrelse MB.',
'zip_file_mime' => 'Attributten skal henvise til en fil af typen: validTypes, fundet:foundType.',
'zip_model_expected' => 'Data objekt forventet men ":type" fundet.',
'zip_unique' => 'Attributten skal være unik for objekttypen i ZIP.',

View File

@@ -109,7 +109,7 @@ return [
'import_zip_cant_read' => 'ZIP-Datei konnte nicht gelesen werden.',
'import_zip_cant_decode_data' => 'ZIP data.json konnte nicht gefunden und dekodiert werden.',
'import_zip_no_data' => 'ZIP-Datei Daten haben kein erwartetes Buch, Kapitel oder Seiteninhalt.',
'import_zip_data_too_large' => 'ZIP data.json content exceeds the configured application maximum upload size.',
'import_zip_data_too_large' => 'Der Inhalt der ZIP data.json überschreitet die maximale Dateigröße der Anwendung.',
'import_validation_failed' => 'ZIP Import konnte mit Fehlern nicht validiert werden:',
'import_zip_failed_notification' => 'Importieren der ZIP-Datei fehlgeschlagen.',
'import_perms_books' => 'Ihnen fehlt die erforderliche Berechtigung, um Bücher zu erstellen.',
@@ -125,6 +125,7 @@ return [
'api_incorrect_token_secret' => 'Das Kennwort für das angegebene API-Token ist falsch',
'api_user_no_api_permission' => 'Der Besitzer des verwendeten API-Tokens hat keine Berechtigung für API-Aufrufe',
'api_user_token_expired' => 'Das verwendete Autorisierungstoken ist abgelaufen',
'api_cookie_auth_only_get' => 'Nur GET Anfragen sind erlaubt, wenn die API mit Cookie-basierter Authentifizierung verwendet wird',
// Settings & Maintenance
'maintenance_test_email_failure' => 'Fehler beim Versenden einer Test E-Mail:',

View File

@@ -11,8 +11,8 @@ return [
'updated_page_subject' => 'Aktualisierte Seite: :pageName',
'updated_page_intro' => 'Eine Seite wurde in :appName aktualisiert:',
'updated_page_debounce' => 'Um eine Flut von Benachrichtigungen zu vermeiden, werden Sie für eine gewisse Zeit keine Benachrichtigungen für weitere Bearbeitungen dieser Seite durch denselben Bearbeiter erhalten.',
'comment_mention_subject' => 'You have been mentioned in a comment on page: :pageName',
'comment_mention_intro' => 'You were mentioned in a comment on :appName:',
'comment_mention_subject' => 'Sie wurden in einem Kommentar auf der Seite :pageName erwähnt',
'comment_mention_intro' => 'Sie wurden in einem Kommentar zu :appName: erwähnt',
'detail_page_name' => 'Name der Seite:',
'detail_page_path' => 'Seitenpfad:',

View File

@@ -23,7 +23,7 @@ return [
'notifications_desc' => 'Legen Sie fest, welche E-Mail-Benachrichtigungen Sie erhalten, wenn bestimmte Aktivitäten im System durchgeführt werden.',
'notifications_opt_own_page_changes' => 'Benachrichtigung bei Änderungen an eigenen Seiten',
'notifications_opt_own_page_comments' => 'Benachrichtigung bei Kommentaren an eigenen Seiten',
'notifications_opt_comment_mentions' => 'Notify when I\'m mentioned in a comment',
'notifications_opt_comment_mentions' => 'Bei Erwähnung mich benachrichtigen',
'notifications_opt_comment_replies' => 'Bei Antworten auf meine Kommentare benachrichtigen',
'notifications_save' => 'Einstellungen speichern',
'notifications_update_success' => 'Benachrichtigungseinstellungen wurden aktualisiert!',

View File

@@ -105,7 +105,7 @@ Hinweis: Benutzer können ihre E-Mail-Adresse nach erfolgreicher Registrierung
'sort_rule_op_chapters_first' => 'Kapitel zuerst',
'sort_rule_op_chapters_last' => 'Kapitel zuletzt',
'sorting_page_limits' => 'Per-Page Display Limits',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using an even multiple of 3 (18, 24, 30, etc...) is recommended.',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using a multiple of 6 is recommended.',
// Maintenance settings
'maint' => 'Wartung',

View File

@@ -109,7 +109,7 @@ return [
'import_zip_cant_read' => 'ZIP-Datei konnte nicht gelesen werden.',
'import_zip_cant_decode_data' => 'Konnte Inhalt der data.json im ZIP nicht finden und dekodieren.',
'import_zip_no_data' => 'ZIP-Datei hat kein erwartetes Buch, Kapitel oder Seiteninhalt.',
'import_zip_data_too_large' => 'ZIP data.json content exceeds the configured application maximum upload size.',
'import_zip_data_too_large' => 'Der Inhalt der ZIP data.json überschreitet die maximale Dateigröße der Anwendung.',
'import_validation_failed' => 'ZIP Import konnte aufgrund folgender Fehler nicht validiert werden:',
'import_zip_failed_notification' => 'Importieren der ZIP-Datei fehlgeschlagen.',
'import_perms_books' => 'Dir fehlt die erforderliche Berechtigung, um Bücher zu erstellen.',
@@ -125,6 +125,7 @@ return [
'api_incorrect_token_secret' => 'Das für den API-Token angegebene geheime Token ist falsch',
'api_user_no_api_permission' => 'Der Besitzer des verwendeten API-Token hat keine Berechtigung für API-Aufrufe',
'api_user_token_expired' => 'Das verwendete Autorisierungs-Token ist abgelaufen',
'api_cookie_auth_only_get' => 'Nur GET Anfragen sind erlaubt, wenn die API mit Cookie-basierter Authentifizierung verwendet wird',
// Settings & Maintenance
'maintenance_test_email_failure' => 'Fehler beim Senden einer Test E-Mail:',

View File

@@ -11,8 +11,8 @@ return [
'updated_page_subject' => 'Aktualisierte Seite: :pageName',
'updated_page_intro' => 'Eine Seite wurde in :appName aktualisiert:',
'updated_page_debounce' => 'Um eine Flut von Benachrichtigungen zu vermeiden, wirst du für eine gewisse Zeit keine Benachrichtigungen für weitere Bearbeitungen dieser Seite durch denselben Bearbeiter erhalten.',
'comment_mention_subject' => 'You have been mentioned in a comment on page: :pageName',
'comment_mention_intro' => 'You were mentioned in a comment on :appName:',
'comment_mention_subject' => 'Sie wurden in einem Kommentar auf der Seite :pageName erwähnt',
'comment_mention_intro' => 'Sie wurden in einem Kommentar zu :appName: erwähnt',
'detail_page_name' => 'Seitenname:',
'detail_page_path' => 'Seitenpfad:',

View File

@@ -23,7 +23,7 @@ return [
'notifications_desc' => 'Lege fest, welche E-Mail-Benachrichtigungen du erhältst, wenn bestimmte Aktivitäten im System durchgeführt werden.',
'notifications_opt_own_page_changes' => 'Benachrichtigung bei Änderungen an eigenen Seiten',
'notifications_opt_own_page_comments' => 'Benachrichtigung bei Kommentaren an eigenen Seiten',
'notifications_opt_comment_mentions' => 'Notify when I\'m mentioned in a comment',
'notifications_opt_comment_mentions' => 'Bei Erwähnung mich benachrichtigen',
'notifications_opt_comment_replies' => 'Bei Antworten auf meine Kommentare benachrichtigen',
'notifications_save' => 'Einstellungen speichern',
'notifications_update_success' => 'Benachrichtigungseinstellungen wurden aktualisiert!',

View File

@@ -105,7 +105,7 @@ Hinweis: Benutzer können ihre E-Mail Adresse nach erfolgreicher Registrierung
'sort_rule_op_chapters_first' => 'Kapitel zuerst',
'sort_rule_op_chapters_last' => 'Kapitel zuletzt',
'sorting_page_limits' => 'Per-Page Display Limits',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using an even multiple of 3 (18, 24, 30, etc...) is recommended.',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using a multiple of 6 is recommended.',
// Maintenance settings
'maint' => 'Wartung',

View File

@@ -125,6 +125,7 @@ return [
'api_incorrect_token_secret' => 'Το μυστικό που παρέχεται για το δεδομένο χρησιμοποιημένο διακριτικό API είναι εσφαλμένο',
'api_user_no_api_permission' => 'Ο ιδιοκτήτης του χρησιμοποιημένου διακριτικού API δεν έχει άδεια για να κάνει κλήσεις API',
'api_user_token_expired' => 'Το διακριτικό εξουσιοδότησης που χρησιμοποιείται έχει λήξει',
'api_cookie_auth_only_get' => 'Only GET requests are allowed when using the API with cookie-based authentication',
// Settings & Maintenance
'maintenance_test_email_failure' => 'Σφάλμα κατά την αποστολή δοκιμαστικού email:',

View File

@@ -104,7 +104,7 @@ return [
'sort_rule_op_chapters_first' => 'Chapters First',
'sort_rule_op_chapters_last' => 'Chapters Last',
'sorting_page_limits' => 'Per-Page Display Limits',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using an even multiple of 3 (18, 24, 30, etc...) is recommended.',
'sorting_page_limits_desc' => 'Set how many items to show per-page in various lists within the system. Typically a lower amount will be more performant, while a higher amount avoids the need to click through multiple pages. Using a multiple of 6 is recommended.',
// Maintenance settings
'maint' => 'Συντήρηση',

Some files were not shown because too many files have changed in this diff Show More