mirror of
https://github.com/BookStackApp/BookStack.git
synced 2026-05-04 18:08:46 +03:00
Compare commits
181 Commits
McTom234/o
...
sort_rule_
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e3fa4822f | ||
|
|
684a94c419 | ||
|
|
c3c8577f05 | ||
|
|
5fbaab4740 | ||
|
|
3d9d5fef51 | ||
|
|
5e78dc6ed5 | ||
|
|
c33853ed84 | ||
|
|
e033578fea | ||
|
|
a7dd998ac9 | ||
|
|
b9d650785a | ||
|
|
25790fd024 | ||
|
|
1763ac550b | ||
|
|
fd6867e577 | ||
|
|
5ebc1fe3b0 | ||
|
|
a44756168d | ||
|
|
fa1dc162bd | ||
|
|
5763d26b17 | ||
|
|
04dd9f8e19 | ||
|
|
0120b475eb | ||
|
|
8a59895ba0 | ||
|
|
a9ffd3e0c7 | ||
|
|
4f18fea086 | ||
|
|
362859ac23 | ||
|
|
7cbfd72920 | ||
|
|
49df47836e | ||
|
|
f4c9d2b049 | ||
|
|
60a3b0c0ac | ||
|
|
5f5fea7c83 | ||
|
|
6e7cc169d1 | ||
|
|
6216c89f82 | ||
|
|
404e67afbc | ||
|
|
6d64262a61 | ||
|
|
151823b84e | ||
|
|
27240be499 | ||
|
|
d0d1bb9829 | ||
|
|
7d0237c798 | ||
|
|
f2f76a3c56 | ||
|
|
ec3dd856db | ||
|
|
25ed242f61 | ||
|
|
10c46534e0 | ||
|
|
dd42b9b43f | ||
|
|
9a12e3a8b7 | ||
|
|
7aef0a48b3 | ||
|
|
6808292c90 | ||
|
|
c10b0fd5b9 | ||
|
|
1077a4efd0 | ||
|
|
23f3f35f6b | ||
|
|
229a99ba24 | ||
|
|
8e99fc6783 | ||
|
|
80204518a2 | ||
|
|
a8d96fd389 | ||
|
|
9d15c79fee | ||
|
|
e1de1f0583 | ||
|
|
a2017ffa55 | ||
|
|
9646339933 | ||
|
|
e4383765e1 | ||
|
|
5d547fcf4c | ||
|
|
826b36c985 | ||
|
|
3fa1174e7a | ||
|
|
50e8501027 | ||
|
|
8a221f64e4 | ||
|
|
035be66ebc | ||
|
|
227027fc45 | ||
|
|
0f040fe8b1 | ||
|
|
10ebe53bd9 | ||
|
|
5e12b678c7 | ||
|
|
057d7be0bc | ||
|
|
984a73159f | ||
|
|
a20438b901 | ||
|
|
9d3d0a4a07 | ||
|
|
5038d124e1 | ||
|
|
f7890c2dd9 | ||
|
|
45ae03ceac | ||
|
|
aa0a8dda11 | ||
|
|
120ee38383 | ||
|
|
cd84074cdf | ||
|
|
4949520194 | ||
|
|
46dcc30bf7 | ||
|
|
9f7d3b55dd | ||
|
|
3e5e88dc87 | ||
|
|
c77a0fdff3 | ||
|
|
6a63b38bb3 | ||
|
|
1b17bb3929 | ||
|
|
9fcfc762ec | ||
|
|
c32b1686a9 | ||
|
|
36649a6188 | ||
|
|
ff59bbdc07 | ||
|
|
4dc443b7df | ||
|
|
19f02d927e | ||
|
|
da7bedd2e4 | ||
|
|
20db372596 | ||
|
|
43eed1660c | ||
|
|
e6b754fad0 | ||
|
|
018de5def3 | ||
|
|
5c4fc3dc2c | ||
|
|
07ec880e33 | ||
|
|
ab436ed5c3 | ||
|
|
082befb2fc | ||
|
|
b0a8cb0c5d | ||
|
|
b08d1b36de | ||
|
|
88d86df66f | ||
|
|
38d3697246 | ||
|
|
d93354ff0e | ||
|
|
3336e0c6ae | ||
|
|
8fc9a2af4e | ||
|
|
8aec571123 | ||
|
|
382f4db276 | ||
|
|
d504b19143 | ||
|
|
d87e8d05c7 | ||
|
|
0b48361780 | ||
|
|
2de3247ae4 | ||
|
|
48df2be0d8 | ||
|
|
a4c0556551 | ||
|
|
a941d1b403 | ||
|
|
51f9b63db0 | ||
|
|
90fc02c57f | ||
|
|
4aeb571126 | ||
|
|
3d9aba7b1f | ||
|
|
48cdaab690 | ||
|
|
4f760479c3 | ||
|
|
9211062e8e | ||
|
|
221c6c7e9f | ||
|
|
e2f91c2bbb | ||
|
|
147ff00c7a | ||
|
|
1e768ce33f | ||
|
|
313326b32a | ||
|
|
1d87b513be | ||
|
|
9bf9ae9c37 | ||
|
|
50540e23a1 | ||
|
|
3e1b0587ec | ||
|
|
6661ae8178 | ||
|
|
1ee5711435 | ||
|
|
08e7ba7064 | ||
|
|
34e747162f | ||
|
|
10f5ceee35 | ||
|
|
9886bbd3a0 | ||
|
|
92a3c22b4c | ||
|
|
b5246a28f0 | ||
|
|
ab4b1c8efa | ||
|
|
8890746278 | ||
|
|
dfdcfcfdb8 | ||
|
|
ebceba0afe | ||
|
|
65f7b61c1f | ||
|
|
2fde803c76 | ||
|
|
adfac3e30e | ||
|
|
21730aeb39 | ||
|
|
75231d2d4a | ||
|
|
9d732d8dd8 | ||
|
|
9e8088f186 | ||
|
|
cf847974d2 | ||
|
|
3cd3e73f60 | ||
|
|
bb350639c6 | ||
|
|
9de294343d | ||
|
|
98a09bcc37 | ||
|
|
959981a676 | ||
|
|
674bb84fac | ||
|
|
ba675b6349 | ||
|
|
f073994bc3 | ||
|
|
0f40aeb0d3 | ||
|
|
cdd164e3e3 | ||
|
|
c90816987c | ||
|
|
dd393691b1 | ||
|
|
dd5375f480 | ||
|
|
291a807d98 | ||
|
|
e64fc60bdf | ||
|
|
ad582ab9f8 | ||
|
|
870f3c58c0 | ||
|
|
22a7772c3d | ||
|
|
9934f85ba9 | ||
|
|
73c6bf4f8d | ||
|
|
47f12cc8f6 | ||
|
|
b2f81f5c62 | ||
|
|
1be2969055 | ||
|
|
99a1d82f0a | ||
|
|
f06a6de2e7 | ||
|
|
aaa28186bc | ||
|
|
8ab9252f9b | ||
|
|
befc645705 | ||
|
|
4eb4407ef7 | ||
|
|
570ded10fa | ||
|
|
b6110ed3cd |
@@ -26,6 +26,13 @@ DB_DATABASE=database_database
|
||||
DB_USERNAME=database_username
|
||||
DB_PASSWORD=database_user_password
|
||||
|
||||
# Storage system to use
|
||||
# By default files are stored on the local filesystem, with images being placed in
|
||||
# public web space so they can be efficiently served directly by the web-server.
|
||||
# For other options with different security levels & considerations, refer to:
|
||||
# https://www.bookstackapp.com/docs/admin/upload-config/
|
||||
STORAGE_TYPE=local
|
||||
|
||||
# Mail system to use
|
||||
# Can be 'smtp' or 'sendmail'
|
||||
MAIL_DRIVER=smtp
|
||||
|
||||
@@ -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.
|
||||
|
||||
28
.github/translators.txt
vendored
28
.github/translators.txt
vendored
@@ -444,7 +444,7 @@ Irjan Olsen (Irch) :: Norwegian Bokmal
|
||||
Aleksandar Jovanovic (jovanoviczaleksandar) :: Serbian (Cyrillic)
|
||||
Red (RedVortex) :: Hebrew
|
||||
xgrug :: Chinese Simplified
|
||||
HrCalmar :: Danish
|
||||
Calle Calmar (HrCalmar) :: Danish
|
||||
Avishay Rapp (AvishayRapp) :: Hebrew
|
||||
matthias4217 :: French
|
||||
Berke BOYLU2 (berkeboylu2) :: Turkish
|
||||
@@ -511,3 +511,29 @@ MrCharlesIII :: Arabic
|
||||
David Olsen (dawin) :: Danish
|
||||
ltnzr :: French
|
||||
Frank Holler (holler.frank) :: German; German Informal
|
||||
Korab Arifi (korabidev) :: Albanian
|
||||
Petr Husák (petrhusak) :: Czech
|
||||
Bernardo Maia (bernardo.bmaia2) :: Portuguese, Brazilian
|
||||
Amr (amr3k) :: Arabic
|
||||
Tahsin Ahmed (tahsinahmed2012) :: Bengali
|
||||
bojan_che :: Serbian (Cyrillic)
|
||||
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
|
||||
Veyilla Nightwhisper (Veyilla) :: German
|
||||
João Barbosa (hypeedd) :: Portuguese
|
||||
Abcdefg Hijklmn (collatek) :: Korean
|
||||
|
||||
2
.github/workflows/test-js.yml
vendored
2
.github/workflows/test-js.yml
vendored
@@ -17,7 +17,7 @@ jobs:
|
||||
if: ${{ github.ref != 'refs/heads/l10n_development' }}
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Install NPM deps
|
||||
run: npm ci
|
||||
|
||||
2
.github/workflows/test-migrations.yml
vendored
2
.github/workflows/test-migrations.yml
vendored
@@ -16,7 +16,7 @@ jobs:
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
matrix:
|
||||
php: ['8.2', '8.3', '8.4']
|
||||
php: ['8.2', '8.3', '8.4', '8.5']
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
||||
2
.github/workflows/test-php.yml
vendored
2
.github/workflows/test-php.yml
vendored
@@ -16,7 +16,7 @@ jobs:
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
matrix:
|
||||
php: ['8.2', '8.3', '8.4']
|
||||
php: ['8.2', '8.3', '8.4', '8.5']
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,6 +2,7 @@
|
||||
/node_modules
|
||||
/.vscode
|
||||
/composer
|
||||
/composer.phar
|
||||
/coverage
|
||||
Homestead.yaml
|
||||
.env
|
||||
|
||||
2
LICENSE
2
LICENSE
@@ -1,6 +1,6 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-2025, Dan Brown and the BookStack project contributors.
|
||||
Copyright (c) 2015-2026, Dan Brown and the BookStack project contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -9,11 +9,9 @@ use Illuminate\Http\Request;
|
||||
|
||||
class OidcController extends Controller
|
||||
{
|
||||
protected OidcService $oidcService;
|
||||
|
||||
public function __construct(OidcService $oidcService)
|
||||
{
|
||||
$this->oidcService = $oidcService;
|
||||
public function __construct(
|
||||
protected OidcService $oidcService
|
||||
) {
|
||||
$this->middleware('guard:oidc');
|
||||
}
|
||||
|
||||
@@ -30,7 +28,7 @@ class OidcController extends Controller
|
||||
return redirect('/login');
|
||||
}
|
||||
|
||||
session()->flash('oidc_state', $loginDetails['state']);
|
||||
session()->put('oidc_state', time() . ':' . $loginDetails['state']);
|
||||
|
||||
return redirect($loginDetails['url']);
|
||||
}
|
||||
@@ -41,10 +39,16 @@ class OidcController extends Controller
|
||||
*/
|
||||
public function callback(Request $request)
|
||||
{
|
||||
$storedState = session()->pull('oidc_state');
|
||||
$responseState = $request->query('state');
|
||||
$splitState = explode(':', session()->pull('oidc_state', ':'), 2);
|
||||
if (count($splitState) !== 2) {
|
||||
$splitState = [null, null];
|
||||
}
|
||||
|
||||
if ($storedState !== $responseState) {
|
||||
[$storedStateTime, $storedState] = $splitState;
|
||||
$threeMinutesAgo = time() - 3 * 60;
|
||||
|
||||
if (!$storedState || $storedState !== $responseState || intval($storedStateTime) < $threeMinutesAgo) {
|
||||
$this->showErrorNotification(trans('errors.oidc_fail_authed', ['system' => config('oidc.name')]));
|
||||
|
||||
return redirect('/login');
|
||||
@@ -62,7 +66,7 @@ class OidcController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* Log the user out then start the OIDC RP-initiated logout process.
|
||||
* Log the user out, then start the OIDC RP-initiated logout process.
|
||||
*/
|
||||
public function logout()
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace BookStack\Access;
|
||||
use BookStack\Access\Notifications\ConfirmEmailNotification;
|
||||
use BookStack\Exceptions\ConfirmationEmailException;
|
||||
use BookStack\Users\Models\User;
|
||||
use Exception;
|
||||
|
||||
class EmailConfirmationService extends UserTokenService
|
||||
{
|
||||
@@ -16,6 +17,7 @@ class EmailConfirmationService extends UserTokenService
|
||||
* Also removes any existing old ones.
|
||||
*
|
||||
* @throws ConfirmationEmailException
|
||||
* @throws Exception
|
||||
*/
|
||||
public function sendConfirmation(User $user): void
|
||||
{
|
||||
|
||||
@@ -71,7 +71,7 @@ class LoginService
|
||||
}
|
||||
|
||||
$lastLoginDetails = $this->getLastLoginAttemptDetails();
|
||||
$this->login($user, $lastLoginDetails['method'], $lastLoginDetails['remember'] ?? false);
|
||||
$this->login($user, $lastLoginDetails['method'], $lastLoginDetails['remember']);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -48,17 +48,16 @@ class MfaValue extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* Easily get the decrypted MFA value for the given user and method.
|
||||
* Get the decrypted MFA value for the given user and method.
|
||||
*/
|
||||
public static function getValueForUser(User $user, string $method): ?string
|
||||
{
|
||||
/** @var MfaValue $mfaVal */
|
||||
$mfaVal = static::query()
|
||||
->where('user_id', '=', $user->id)
|
||||
->where('method', '=', $method)
|
||||
->first();
|
||||
|
||||
return $mfaVal ? $mfaVal->getValue() : null;
|
||||
return $mfaVal?->getValue();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -14,10 +14,9 @@ use PragmaRX\Google2FA\Support\Constants;
|
||||
|
||||
class TotpService
|
||||
{
|
||||
protected $google2fa;
|
||||
|
||||
public function __construct(Google2FA $google2fa)
|
||||
{
|
||||
public function __construct(
|
||||
protected Google2FA $google2fa
|
||||
) {
|
||||
$this->google2fa = $google2fa;
|
||||
// Use SHA1 as a default, Personal testing of other options in 2021 found
|
||||
// many apps lack support for other algorithms yet still will scan
|
||||
@@ -35,7 +34,7 @@ class TotpService
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a TOTP URL from secret key.
|
||||
* Generate a TOTP URL from a secret key.
|
||||
*/
|
||||
public function generateUrl(string $secret, User $user): string
|
||||
{
|
||||
|
||||
@@ -9,10 +9,7 @@ use phpseclib3\Math\BigInteger;
|
||||
|
||||
class OidcJwtSigningKey
|
||||
{
|
||||
/**
|
||||
* @var PublicKey
|
||||
*/
|
||||
protected $key;
|
||||
protected PublicKey $key;
|
||||
|
||||
/**
|
||||
* Can be created either from a JWK parameter array or local file path to load a certificate from.
|
||||
@@ -20,15 +17,13 @@ class OidcJwtSigningKey
|
||||
* 'file:///var/www/cert.pem'
|
||||
* ['kty' => 'RSA', 'alg' => 'RS256', 'n' => 'abc123...'].
|
||||
*
|
||||
* @param array|string $jwkOrKeyPath
|
||||
*
|
||||
* @throws OidcInvalidKeyException
|
||||
*/
|
||||
public function __construct($jwkOrKeyPath)
|
||||
public function __construct(array|string $jwkOrKeyPath)
|
||||
{
|
||||
if (is_array($jwkOrKeyPath)) {
|
||||
$this->loadFromJwkArray($jwkOrKeyPath);
|
||||
} elseif (is_string($jwkOrKeyPath) && strpos($jwkOrKeyPath, 'file://') === 0) {
|
||||
} elseif (str_starts_with($jwkOrKeyPath, 'file://')) {
|
||||
$this->loadFromPath($jwkOrKeyPath);
|
||||
} else {
|
||||
throw new OidcInvalidKeyException('Unexpected type of key value provided');
|
||||
@@ -38,7 +33,7 @@ class OidcJwtSigningKey
|
||||
/**
|
||||
* @throws OidcInvalidKeyException
|
||||
*/
|
||||
protected function loadFromPath(string $path)
|
||||
protected function loadFromPath(string $path): void
|
||||
{
|
||||
try {
|
||||
$key = PublicKeyLoader::load(
|
||||
@@ -58,7 +53,7 @@ class OidcJwtSigningKey
|
||||
/**
|
||||
* @throws OidcInvalidKeyException
|
||||
*/
|
||||
protected function loadFromJwkArray(array $jwk)
|
||||
protected function loadFromJwkArray(array $jwk): void
|
||||
{
|
||||
// 'alg' is optional for a JWK, but we will still attempt to validate if
|
||||
// it exists otherwise presume it will be compatible.
|
||||
@@ -82,7 +77,7 @@ class OidcJwtSigningKey
|
||||
throw new OidcInvalidKeyException('A "n" parameter on the provided key is expected');
|
||||
}
|
||||
|
||||
$n = strtr($jwk['n'] ?? '', '-_', '+/');
|
||||
$n = strtr($jwk['n'], '-_', '+/');
|
||||
|
||||
try {
|
||||
$key = PublicKeyLoader::load([
|
||||
|
||||
@@ -102,12 +102,12 @@ class OidcJwtWithClaims implements ProvidesClaims
|
||||
protected function validateTokenStructure(): void
|
||||
{
|
||||
foreach (['header', 'payload'] as $prop) {
|
||||
if (empty($this->$prop) || !is_array($this->$prop)) {
|
||||
if (empty($this->$prop)) {
|
||||
throw new OidcInvalidTokenException("Could not parse out a valid {$prop} within the provided token");
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($this->signature) || !is_string($this->signature)) {
|
||||
if (empty($this->signature)) {
|
||||
throw new OidcInvalidTokenException('Could not parse out a valid signature within the provided token');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -39,7 +39,7 @@ class OidcUserDetails
|
||||
): void {
|
||||
$this->externalId = $claims->getClaim($idClaim) ?? $this->externalId;
|
||||
$this->email = $claims->getClaim('email') ?? $this->email;
|
||||
$this->name = static::getUserDisplayName($displayNameClaims, $claims) ?? $this->name;
|
||||
$this->name = static::getUserDisplayName($displayNameClaims, $claims) ?: $this->name;
|
||||
$this->groups = static::getUserGroups($groupsClaim, $claims) ?? $this->groups;
|
||||
$this->picture = static::getPicture($claims) ?: $this->picture;
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -266,7 +266,7 @@ class Saml2Service
|
||||
/**
|
||||
* Extract the details of a user from a SAML response.
|
||||
*
|
||||
* @return array{external_id: string, name: string, email: string, saml_id: string}
|
||||
* @return array{external_id: string, name: string, email: string|null, saml_id: string}
|
||||
*/
|
||||
protected function getUserDetails(string $samlID, $samlAttributes): array
|
||||
{
|
||||
@@ -357,7 +357,7 @@ class Saml2Service
|
||||
]);
|
||||
}
|
||||
|
||||
if ($userDetails['email'] === null) {
|
||||
if (empty($userDetails['email'])) {
|
||||
throw new SamlException(trans('errors.saml_no_email_address'));
|
||||
}
|
||||
|
||||
|
||||
@@ -117,14 +117,14 @@ class SocialAuthService
|
||||
}
|
||||
|
||||
// When a user is logged in and the social account exists and is already linked to the current user.
|
||||
if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
|
||||
if ($isLoggedIn && $socialAccount->user->id === $currentUser->id) {
|
||||
session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => $titleCaseDriver]));
|
||||
|
||||
return redirect('/my-account/auth#social_accounts');
|
||||
}
|
||||
|
||||
// When a user is logged in, A social account exists but the users do not match.
|
||||
if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
|
||||
if ($isLoggedIn && $socialAccount->user->id != $currentUser->id) {
|
||||
session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => $titleCaseDriver]));
|
||||
|
||||
return redirect('/my-account/auth#social_accounts');
|
||||
|
||||
@@ -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;
|
||||
@@ -41,7 +42,19 @@ class Comment extends Model implements Loggable, OwnableInterface
|
||||
*/
|
||||
public function entity(): MorphTo
|
||||
{
|
||||
return $this->morphTo('commentable');
|
||||
// We specifically define null here to avoid the different name (commentable)
|
||||
// being used by Laravel eager loading instead of the method name, which it was doing
|
||||
// in some scenarios like when deserialized when going through the queue system.
|
||||
// So we instead specify the type and id column names to use.
|
||||
// Related to:
|
||||
// https://github.com/laravel/framework/pull/24815
|
||||
// https://github.com/laravel/framework/issues/27342
|
||||
// https://github.com/laravel/framework/issues/47953
|
||||
// (and probably more)
|
||||
|
||||
// Ultimately, we could just align the method name to 'commentable' but that would be a potential
|
||||
// breaking change and not really worthwhile in a patch due to the risk of creating extra problems.
|
||||
return $this->morphTo(null, 'commentable_type', 'commentable_id');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -70,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
|
||||
|
||||
20
app/Activity/Models/MentionHistory.php
Normal file
20
app/Activity/Models/MentionHistory.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Activity\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* @property int $id
|
||||
* @property string $mentionable_type
|
||||
* @property int $mentionable_id
|
||||
* @property int $from_user_id
|
||||
* @property int $to_user_id
|
||||
* @property Carbon $created_at
|
||||
* @property Carbon $updated_at
|
||||
*/
|
||||
class MentionHistory extends Model
|
||||
{
|
||||
protected $table = 'mention_history';
|
||||
}
|
||||
@@ -20,6 +20,7 @@ abstract class BaseNotificationHandler implements NotificationHandler
|
||||
{
|
||||
$users = User::query()->whereIn('id', array_unique($userIds))->get();
|
||||
|
||||
/** @var User $user */
|
||||
foreach ($users as $user) {
|
||||
// Prevent sending to the user that initiated the activity
|
||||
if ($user->id === $initiator->id) {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Activity\Notifications\Handlers;
|
||||
|
||||
use BookStack\Activity\ActivityType;
|
||||
use BookStack\Activity\Models\Activity;
|
||||
use BookStack\Activity\Models\Comment;
|
||||
use BookStack\Activity\Models\Loggable;
|
||||
use BookStack\Activity\Models\MentionHistory;
|
||||
use BookStack\Activity\Notifications\Messages\CommentMentionNotification;
|
||||
use BookStack\Activity\Tools\MentionParser;
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Settings\UserNotificationPreferences;
|
||||
use BookStack\Users\Models\User;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class CommentMentionNotificationHandler extends BaseNotificationHandler
|
||||
{
|
||||
public function handle(Activity $activity, Loggable|string $detail, User $user): void
|
||||
{
|
||||
if (!($detail instanceof Comment) || !($detail->entity instanceof Page)) {
|
||||
throw new \InvalidArgumentException("Detail for comment mention notifications must be a comment on a page");
|
||||
}
|
||||
|
||||
/** @var Page $page */
|
||||
$page = $detail->entity;
|
||||
|
||||
$parser = new MentionParser();
|
||||
$mentionedUserIds = $parser->parseUserIdsFromHtml($detail->html);
|
||||
$realMentionedUsers = User::whereIn('id', $mentionedUserIds)->get();
|
||||
|
||||
$receivingNotifications = $realMentionedUsers->filter(function (User $user) {
|
||||
$prefs = new UserNotificationPreferences($user);
|
||||
return $prefs->notifyOnCommentMentions();
|
||||
});
|
||||
$receivingNotificationsUserIds = $receivingNotifications->pluck('id')->toArray();
|
||||
|
||||
$userMentionsToLog = $realMentionedUsers;
|
||||
|
||||
// When an edit, we check our history to see if we've already notified the user about this comment before
|
||||
// so that we can filter them out to avoid double notifications.
|
||||
if ($activity->type === ActivityType::COMMENT_UPDATE) {
|
||||
$previouslyNotifiedUserIds = $this->getPreviouslyNotifiedUserIds($detail);
|
||||
$receivingNotificationsUserIds = array_values(array_diff($receivingNotificationsUserIds, $previouslyNotifiedUserIds));
|
||||
$userMentionsToLog = $userMentionsToLog->filter(function (User $user) use ($previouslyNotifiedUserIds) {
|
||||
return !in_array($user->id, $previouslyNotifiedUserIds);
|
||||
});
|
||||
}
|
||||
|
||||
$this->logMentions($userMentionsToLog, $detail, $user);
|
||||
$this->sendNotificationToUserIds(CommentMentionNotification::class, $receivingNotificationsUserIds, $user, $detail, $page);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<User> $mentionedUsers
|
||||
*/
|
||||
protected function logMentions(Collection $mentionedUsers, Comment $comment, User $fromUser): void
|
||||
{
|
||||
$mentions = [];
|
||||
$now = Carbon::now();
|
||||
|
||||
foreach ($mentionedUsers as $mentionedUser) {
|
||||
$mentions[] = [
|
||||
'mentionable_type' => $comment->getMorphClass(),
|
||||
'mentionable_id' => $comment->id,
|
||||
'from_user_id' => $fromUser->id,
|
||||
'to_user_id' => $mentionedUser->id,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
];
|
||||
}
|
||||
|
||||
MentionHistory::query()->insert($mentions);
|
||||
}
|
||||
|
||||
protected function getPreviouslyNotifiedUserIds(Comment $comment): array
|
||||
{
|
||||
return MentionHistory::query()
|
||||
->where('mentionable_id', $comment->id)
|
||||
->where('mentionable_type', $comment->getMorphClass())
|
||||
->pluck('to_user_id')
|
||||
->toArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Activity\Notifications\Messages;
|
||||
|
||||
use BookStack\Activity\Models\Comment;
|
||||
use BookStack\Activity\Notifications\MessageParts\EntityLinkMessageLine;
|
||||
use BookStack\Activity\Notifications\MessageParts\ListMessageLine;
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Users\Models\User;
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
|
||||
class CommentMentionNotification extends BaseActivityNotification
|
||||
{
|
||||
public function toMail(User $notifiable): MailMessage
|
||||
{
|
||||
/** @var Comment $comment */
|
||||
$comment = $this->detail;
|
||||
/** @var Page $page */
|
||||
$page = $comment->entity;
|
||||
|
||||
$locale = $notifiable->getLocale();
|
||||
|
||||
$listLines = array_filter([
|
||||
$locale->trans('notifications.detail_page_name') => new EntityLinkMessageLine($page),
|
||||
$locale->trans('notifications.detail_page_path') => $this->buildPagePathLine($page, $notifiable),
|
||||
$locale->trans('notifications.detail_commenter') => $this->user->name,
|
||||
$locale->trans('notifications.detail_comment') => strip_tags($comment->html),
|
||||
]);
|
||||
|
||||
return $this->newMailMessage($locale)
|
||||
->subject($locale->trans('notifications.comment_mention_subject', ['pageName' => $page->getShortName()]))
|
||||
->line($locale->trans('notifications.comment_mention_intro', ['appName' => setting('app-name')]))
|
||||
->line(new ListMessageLine($listLines))
|
||||
->action($locale->trans('notifications.action_view_comment'), $page->getUrl('#comment' . $comment->local_id))
|
||||
->line($this->buildReasonFooterLine($locale));
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use BookStack\Activity\ActivityType;
|
||||
use BookStack\Activity\Models\Activity;
|
||||
use BookStack\Activity\Models\Loggable;
|
||||
use BookStack\Activity\Notifications\Handlers\CommentCreationNotificationHandler;
|
||||
use BookStack\Activity\Notifications\Handlers\CommentMentionNotificationHandler;
|
||||
use BookStack\Activity\Notifications\Handlers\NotificationHandler;
|
||||
use BookStack\Activity\Notifications\Handlers\PageCreationNotificationHandler;
|
||||
use BookStack\Activity\Notifications\Handlers\PageUpdateNotificationHandler;
|
||||
@@ -14,14 +15,14 @@ use BookStack\Users\Models\User;
|
||||
class NotificationManager
|
||||
{
|
||||
/**
|
||||
* @var class-string<NotificationHandler>[]
|
||||
* @var array<string, class-string<NotificationHandler>[]>
|
||||
*/
|
||||
protected array $handlers = [];
|
||||
protected array $handlersByActivity = [];
|
||||
|
||||
public function handle(Activity $activity, string|Loggable $detail, User $user): void
|
||||
{
|
||||
$activityType = $activity->type;
|
||||
$handlersToRun = $this->handlers[$activityType] ?? [];
|
||||
$handlersToRun = $this->handlersByActivity[$activityType] ?? [];
|
||||
foreach ($handlersToRun as $handlerClass) {
|
||||
/** @var NotificationHandler $handler */
|
||||
$handler = new $handlerClass();
|
||||
@@ -34,12 +35,12 @@ class NotificationManager
|
||||
*/
|
||||
public function registerHandler(string $activityType, string $handlerClass): void
|
||||
{
|
||||
if (!isset($this->handlers[$activityType])) {
|
||||
$this->handlers[$activityType] = [];
|
||||
if (!isset($this->handlersByActivity[$activityType])) {
|
||||
$this->handlersByActivity[$activityType] = [];
|
||||
}
|
||||
|
||||
if (!in_array($handlerClass, $this->handlers[$activityType])) {
|
||||
$this->handlers[$activityType][] = $handlerClass;
|
||||
if (!in_array($handlerClass, $this->handlersByActivity[$activityType])) {
|
||||
$this->handlersByActivity[$activityType][] = $handlerClass;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,5 +49,7 @@ class NotificationManager
|
||||
$this->registerHandler(ActivityType::PAGE_CREATE, PageCreationNotificationHandler::class);
|
||||
$this->registerHandler(ActivityType::PAGE_UPDATE, PageUpdateNotificationHandler::class);
|
||||
$this->registerHandler(ActivityType::COMMENT_CREATE, CommentCreationNotificationHandler::class);
|
||||
$this->registerHandler(ActivityType::COMMENT_CREATE, CommentMentionNotificationHandler::class);
|
||||
$this->registerHandler(ActivityType::COMMENT_UPDATE, CommentMentionNotificationHandler::class);
|
||||
}
|
||||
}
|
||||
|
||||
28
app/Activity/Tools/MentionParser.php
Normal file
28
app/Activity/Tools/MentionParser.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Activity\Tools;
|
||||
|
||||
use BookStack\Util\HtmlDocument;
|
||||
use DOMElement;
|
||||
|
||||
class MentionParser
|
||||
{
|
||||
public function parseUserIdsFromHtml(string $html): array
|
||||
{
|
||||
$doc = new HtmlDocument($html);
|
||||
|
||||
$ids = [];
|
||||
$mentionLinks = $doc->queryXPath('//a[@data-mention-user-id]');
|
||||
|
||||
foreach ($mentionLinks as $link) {
|
||||
if ($link instanceof DOMElement) {
|
||||
$id = intval($link->getAttribute('data-mention-user-id'));
|
||||
if ($id > 0) {
|
||||
$ids[] = $id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($ids));
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,14 @@ use ReflectionMethod;
|
||||
|
||||
class ApiDocsGenerator
|
||||
{
|
||||
/**
|
||||
* @var array<string, ReflectionClass>
|
||||
*/
|
||||
protected array $reflectionClasses = [];
|
||||
|
||||
/**
|
||||
* @var array<string, ApiController>
|
||||
*/
|
||||
protected array $controllerClasses = [];
|
||||
|
||||
/**
|
||||
@@ -107,7 +114,6 @@ class ApiDocsGenerator
|
||||
*/
|
||||
protected function getBodyParamsFromClass(string $className, string $methodName): ?array
|
||||
{
|
||||
/** @var ApiController $class */
|
||||
$class = $this->controllerClasses[$className] ?? null;
|
||||
if ($class === null) {
|
||||
$class = app()->make($className);
|
||||
@@ -153,7 +159,7 @@ class ApiDocsGenerator
|
||||
$matches = [];
|
||||
preg_match_all('/^\s*?\*\s?($|((?![\/@\s]).*?))$/m', $comment, $matches);
|
||||
|
||||
$text = implode(' ', $matches[1] ?? []);
|
||||
$text = implode(' ', $matches[1]);
|
||||
return str_replace(' ', "\n", $text);
|
||||
}
|
||||
|
||||
|
||||
@@ -74,18 +74,21 @@ class ApiEntityListFormatter
|
||||
|
||||
/**
|
||||
* Include parent book/chapter info in the formatted data.
|
||||
* These functions are careful to not load the relation themselves, since they should
|
||||
* have already been loaded in a more efficient manner, with permissions applied, by the time
|
||||
* the parent fields are handled here.
|
||||
*/
|
||||
public function withParents(): self
|
||||
{
|
||||
$this->withField('book', function (Entity $entity) {
|
||||
if ($entity instanceof BookChild && $entity->book) {
|
||||
if ($entity instanceof BookChild && $entity->relationLoaded('book') && $entity->getRelationValue('book')) {
|
||||
return $entity->book->only(['id', 'name', 'slug']);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
$this->withField('chapter', function (Entity $entity) {
|
||||
if ($entity instanceof Page && $entity->chapter) {
|
||||
if ($entity instanceof Page && $entity->relationLoaded('chapter') && $entity->getRelationValue('chapter')) {
|
||||
return $entity->chapter->only(['id', 'name', 'slug']);
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -16,30 +16,15 @@ class ApiTokenGuard implements Guard
|
||||
{
|
||||
use GuardHelpers;
|
||||
|
||||
/**
|
||||
* The request instance.
|
||||
*/
|
||||
protected $request;
|
||||
|
||||
/**
|
||||
* @var LoginService
|
||||
*/
|
||||
protected $loginService;
|
||||
|
||||
/**
|
||||
* The last auth exception thrown in this request.
|
||||
*
|
||||
* @var ApiAuthException
|
||||
*/
|
||||
protected $lastAuthException;
|
||||
protected ApiAuthException|null $lastAuthException = null;
|
||||
|
||||
/**
|
||||
* ApiTokenGuard constructor.
|
||||
*/
|
||||
public function __construct(Request $request, LoginService $loginService)
|
||||
{
|
||||
$this->request = $request;
|
||||
$this->loginService = $loginService;
|
||||
public function __construct(
|
||||
protected Request $request,
|
||||
protected LoginService $loginService
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,7 +52,7 @@ class ApiTokenGuard implements Guard
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if current user is authenticated. If not, throw an exception.
|
||||
* Determine if the current user is authenticated. If not, throw an exception.
|
||||
*
|
||||
* @throws ApiAuthException
|
||||
*
|
||||
@@ -121,7 +106,7 @@ class ApiTokenGuard implements Guard
|
||||
throw new ApiAuthException(trans('errors.api_no_authorization_found'));
|
||||
}
|
||||
|
||||
if (strpos($authToken, ':') === false || strpos($authToken, 'Token ') !== 0) {
|
||||
if (!str_contains($authToken, ':') || !str_starts_with($authToken, 'Token ')) {
|
||||
throw new ApiAuthException(trans('errors.api_bad_authorization_format'));
|
||||
}
|
||||
}
|
||||
@@ -155,7 +140,7 @@ class ApiTokenGuard implements Guard
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function validate(array $credentials = [])
|
||||
public function validate(array $credentials = []): bool
|
||||
{
|
||||
if (empty($credentials['id']) || empty($credentials['secret'])) {
|
||||
return false;
|
||||
@@ -175,7 +160,7 @@ class ApiTokenGuard implements Guard
|
||||
/**
|
||||
* "Log out" the currently authenticated user.
|
||||
*/
|
||||
public function logout()
|
||||
public function logout(): void
|
||||
{
|
||||
$this->user = null;
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ class HomeController extends Controller
|
||||
if ($homepageOption === 'bookshelves') {
|
||||
$shelves = $this->queries->shelves->visibleForListWithCover()
|
||||
->orderBy($commonData['listOptions']->getSort(), $commonData['listOptions']->getOrder())
|
||||
->paginate(18);
|
||||
->paginate(setting()->getInteger('lists-page-count-shelves', 18, 1, 1000));
|
||||
$data = array_merge($commonData, ['shelves' => $shelves]);
|
||||
|
||||
return view('home.shelves', $data);
|
||||
@@ -92,7 +92,7 @@ class HomeController extends Controller
|
||||
if ($homepageOption === 'books') {
|
||||
$books = $this->queries->books->visibleForListWithCover()
|
||||
->orderBy($commonData['listOptions']->getSort(), $commonData['listOptions']->getOrder())
|
||||
->paginate(18);
|
||||
->paginate(setting()->getInteger('lists-page-count-books', 18, 1, 1000));
|
||||
$data = array_merge($commonData, ['books' => $books]);
|
||||
|
||||
return view('home.books', $data);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace BookStack\App\Providers;
|
||||
|
||||
use BookStack\Access\SocialDriverManager;
|
||||
use BookStack\Activity\Models\Comment;
|
||||
use BookStack\Activity\Tools\ActivityLogger;
|
||||
use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Models\Bookshelf;
|
||||
@@ -64,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);
|
||||
|
||||
@@ -73,6 +81,7 @@ class AppServiceProvider extends ServiceProvider
|
||||
'book' => Book::class,
|
||||
'chapter' => Chapter::class,
|
||||
'page' => Page::class,
|
||||
'comment' => Comment::class,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,11 +5,9 @@ namespace BookStack\App;
|
||||
/**
|
||||
* Assigned to models that can have slugs.
|
||||
* Must have the below properties.
|
||||
*
|
||||
* @property string $slug
|
||||
*/
|
||||
interface SluggableInterface
|
||||
{
|
||||
/**
|
||||
* Regenerate the slug for this model.
|
||||
*/
|
||||
public function refreshSlug(): string;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -81,7 +81,8 @@ return [
|
||||
'strict' => false,
|
||||
'engine' => null,
|
||||
'options' => extension_loaded('pdo_mysql') ? array_filter([
|
||||
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
|
||||
// @phpstan-ignore class.notFound
|
||||
(PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
|
||||
]) : [],
|
||||
],
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ return [
|
||||
'bookshelves_view_type' => env('APP_VIEWS_BOOKSHELVES', 'grid'),
|
||||
'bookshelf_view_type' => env('APP_VIEWS_BOOKSHELF', 'grid'),
|
||||
'books_view_type' => env('APP_VIEWS_BOOKS', 'grid'),
|
||||
'notifications#comment-mentions' => true,
|
||||
],
|
||||
|
||||
];
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -32,7 +32,7 @@ class AssignSortRuleCommand extends Command
|
||||
*/
|
||||
public function handle(BookSorter $sorter): int
|
||||
{
|
||||
$sortRuleId = intval($this->argument('sort-rule')) ?? 0;
|
||||
$sortRuleId = intval($this->argument('sort-rule'));
|
||||
if ($sortRuleId === 0) {
|
||||
return $this->listSortRules();
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ class CopyShelfPermissionsCommand extends Command
|
||||
{
|
||||
$shelfSlug = $this->option('slug');
|
||||
$cascadeAll = $this->option('all');
|
||||
$noInteraction = boolval($this->option('no-interaction'));
|
||||
$shelves = null;
|
||||
|
||||
if (!$cascadeAll && !$shelfSlug) {
|
||||
@@ -41,14 +42,16 @@ class CopyShelfPermissionsCommand extends Command
|
||||
}
|
||||
|
||||
if ($cascadeAll) {
|
||||
$continue = $this->confirm(
|
||||
'Permission settings for all shelves will be cascaded. ' .
|
||||
'Books assigned to multiple shelves will receive only the permissions of it\'s last processed shelf. ' .
|
||||
'Are you sure you want to proceed?'
|
||||
);
|
||||
if (!$noInteraction) {
|
||||
$continue = $this->confirm(
|
||||
'Permission settings for all shelves will be cascaded. ' .
|
||||
'Books assigned to multiple shelves will receive only the permissions of it\'s last processed shelf. ' .
|
||||
'Are you sure you want to proceed?',
|
||||
);
|
||||
|
||||
if (!$continue && !$this->hasOption('no-interaction')) {
|
||||
return 0;
|
||||
if (!$continue) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
$shelves = $queries->start()->get(['id']);
|
||||
|
||||
320
app/Console/Commands/InstallModuleCommand.php
Normal file
320
app/Console/Commands/InstallModuleCommand.php
Normal file
@@ -0,0 +1,320 @@
|
||||
<?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);
|
||||
$redirectOriginMatches = ($originalUrl['host'] ?? '') === ($redirectUrl['host'] ?? '')
|
||||
&& ($originalUrl['scheme'] ?? '') === ($redirectUrl['scheme'] ?? '')
|
||||
&& ($originalUrl['port'] ?? '') === ($redirectUrl['port'] ?? '');
|
||||
|
||||
if (!$redirectOriginMatches) {
|
||||
$redirectOrigin = ($redirectUrl['scheme'] ?? '') . '://' . ($redirectUrl['host'] ?? '') . (isset($redirectUrl['port']) ? ':' . $redirectUrl['port'] : '');
|
||||
$this->info("The download URL is redirecting to a different site: {$redirectOrigin}");
|
||||
$shouldContinue = $this->confirm("Do you trust downloading the module from this site?");
|
||||
if (!$shouldContinue) {
|
||||
$this->error("Stopping module installation");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
$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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
|
||||
@@ -8,6 +8,7 @@ use BookStack\Activity\Models\View;
|
||||
use BookStack\Activity\Tools\UserEntityWatchOptions;
|
||||
use BookStack\Entities\Queries\BookQueries;
|
||||
use BookStack\Entities\Queries\BookshelfQueries;
|
||||
use BookStack\Entities\Queries\EntityQueries;
|
||||
use BookStack\Entities\Repos\BookRepo;
|
||||
use BookStack\Entities\Tools\BookContents;
|
||||
use BookStack\Entities\Tools\Cloner;
|
||||
@@ -31,6 +32,7 @@ class BookController extends Controller
|
||||
protected ShelfContext $shelfContext,
|
||||
protected BookRepo $bookRepo,
|
||||
protected BookQueries $queries,
|
||||
protected EntityQueries $entityQueries,
|
||||
protected BookshelfQueries $shelfQueries,
|
||||
protected ReferenceFetcher $referenceFetcher,
|
||||
) {
|
||||
@@ -50,7 +52,7 @@ class BookController extends Controller
|
||||
|
||||
$books = $this->queries->visibleForListWithCover()
|
||||
->orderBy($listOptions->getSort(), $listOptions->getOrder())
|
||||
->paginate(18);
|
||||
->paginate(setting()->getInteger('lists-page-count-books', 18, 1, 1000));
|
||||
$recents = $this->isSignedIn() ? $this->queries->recentlyViewedForCurrentUser()->take(4)->get() : false;
|
||||
$popular = $this->queries->popularForList()->take(4)->get();
|
||||
$new = $this->queries->visibleForList()->orderBy('created_at', 'desc')->take(4)->get();
|
||||
@@ -127,7 +129,16 @@ class BookController extends Controller
|
||||
*/
|
||||
public function show(Request $request, ActivityQueries $activities, string $slug)
|
||||
{
|
||||
$book = $this->queries->findVisibleBySlugOrFail($slug);
|
||||
try {
|
||||
$book = $this->queries->findVisibleBySlugOrFail($slug);
|
||||
} catch (NotFoundException $exception) {
|
||||
$book = $this->entityQueries->findVisibleByOldSlugs('book', $slug);
|
||||
if (is_null($book)) {
|
||||
throw $exception;
|
||||
}
|
||||
return redirect($book->getUrl());
|
||||
}
|
||||
|
||||
$bookChildren = (new BookContents($book))->getTree(true);
|
||||
$bookParentShelves = $book->shelves()->scopes('visible')->get();
|
||||
|
||||
@@ -213,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');
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ use BookStack\Activity\ActivityQueries;
|
||||
use BookStack\Activity\Models\View;
|
||||
use BookStack\Entities\Queries\BookQueries;
|
||||
use BookStack\Entities\Queries\BookshelfQueries;
|
||||
use BookStack\Entities\Queries\EntityQueries;
|
||||
use BookStack\Entities\Repos\BookshelfRepo;
|
||||
use BookStack\Entities\Tools\ShelfContext;
|
||||
use BookStack\Exceptions\ImageUploadException;
|
||||
@@ -23,6 +24,7 @@ class BookshelfController extends Controller
|
||||
public function __construct(
|
||||
protected BookshelfRepo $shelfRepo,
|
||||
protected BookshelfQueries $queries,
|
||||
protected EntityQueries $entityQueries,
|
||||
protected BookQueries $bookQueries,
|
||||
protected ShelfContext $shelfContext,
|
||||
protected ReferenceFetcher $referenceFetcher,
|
||||
@@ -43,7 +45,7 @@ class BookshelfController extends Controller
|
||||
|
||||
$shelves = $this->queries->visibleForListWithCover()
|
||||
->orderBy($listOptions->getSort(), $listOptions->getOrder())
|
||||
->paginate(18);
|
||||
->paginate(setting()->getInteger('lists-page-count-shelves', 18, 1, 1000));
|
||||
$recents = $this->isSignedIn() ? $this->queries->recentlyViewedForCurrentUser()->get() : false;
|
||||
$popular = $this->queries->popularForList()->get();
|
||||
$new = $this->queries->visibleForList()
|
||||
@@ -105,7 +107,16 @@ class BookshelfController extends Controller
|
||||
*/
|
||||
public function show(Request $request, ActivityQueries $activities, string $slug)
|
||||
{
|
||||
$shelf = $this->queries->findVisibleBySlugOrFail($slug);
|
||||
try {
|
||||
$shelf = $this->queries->findVisibleBySlugOrFail($slug);
|
||||
} catch (NotFoundException $exception) {
|
||||
$shelf = $this->entityQueries->findVisibleByOldSlugs('bookshelf', $slug);
|
||||
if (is_null($shelf)) {
|
||||
throw $exception;
|
||||
}
|
||||
return redirect($shelf->getUrl());
|
||||
}
|
||||
|
||||
$this->checkOwnablePermission(Permission::BookshelfView, $shelf);
|
||||
|
||||
$listOptions = SimpleListOptions::fromRequest($request, 'shelf_books')->withSortOptions([
|
||||
|
||||
@@ -77,7 +77,15 @@ class ChapterController extends Controller
|
||||
*/
|
||||
public function show(string $bookSlug, string $chapterSlug)
|
||||
{
|
||||
$chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug);
|
||||
try {
|
||||
$chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug);
|
||||
} catch (NotFoundException $exception) {
|
||||
$chapter = $this->entityQueries->findVisibleByOldSlugs('chapter', $chapterSlug, $bookSlug);
|
||||
if (is_null($chapter)) {
|
||||
throw $exception;
|
||||
}
|
||||
return redirect($chapter->getUrl());
|
||||
}
|
||||
|
||||
$sidebarTree = (new BookContents($chapter->book))->getTree();
|
||||
$pages = $this->entityQueries->pages->visibleForChapterList($chapter->id)->get();
|
||||
|
||||
@@ -17,11 +17,12 @@ use BookStack\Entities\Tools\PageContent;
|
||||
use BookStack\Entities\Tools\PageEditActivity;
|
||||
use BookStack\Entities\Tools\PageEditorData;
|
||||
use BookStack\Exceptions\NotFoundException;
|
||||
use BookStack\Exceptions\NotifyException;
|
||||
use BookStack\Exceptions\PermissionsException;
|
||||
use BookStack\Http\Controller;
|
||||
use BookStack\Permissions\Permission;
|
||||
use BookStack\References\ReferenceFetcher;
|
||||
use BookStack\Util\HtmlContentFilter;
|
||||
use BookStack\Util\HtmlContentFilterConfig;
|
||||
use Exception;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -140,9 +141,7 @@ class PageController extends Controller
|
||||
try {
|
||||
$page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
|
||||
} catch (NotFoundException $e) {
|
||||
$revision = $this->entityQueries->revisions->findLatestVersionBySlugs($bookSlug, $pageSlug);
|
||||
$page = $revision->page ?? null;
|
||||
|
||||
$page = $this->entityQueries->findVisibleByOldSlugs('page', $pageSlug, $bookSlug);
|
||||
if (is_null($page)) {
|
||||
throw $e;
|
||||
}
|
||||
@@ -176,7 +175,7 @@ class PageController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* Get page from an ajax request.
|
||||
* Get a page from an ajax request.
|
||||
*
|
||||
* @throws NotFoundException
|
||||
*/
|
||||
@@ -186,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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', [
|
||||
|
||||
@@ -17,7 +17,7 @@ use Illuminate\Support\Collection;
|
||||
*
|
||||
* @property string $description
|
||||
* @property string $description_html
|
||||
* @property int $image_id
|
||||
* @property ?int $image_id
|
||||
* @property ?int $default_template_id
|
||||
* @property ?int $sort_rule_id
|
||||
* @property \Illuminate\Database\Eloquent\Collection $chapters
|
||||
@@ -67,8 +67,7 @@ class Book extends Entity implements HasDescriptionInterface, HasCoverInterface,
|
||||
*/
|
||||
public function chapters(): HasMany
|
||||
{
|
||||
return $this->hasMany(Chapter::class)
|
||||
->where('type', '=', 'chapter');
|
||||
return $this->hasMany(Chapter::class);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
namespace BookStack\Entities\Models;
|
||||
|
||||
use BookStack\References\ReferenceUpdater;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
@@ -17,34 +16,10 @@ abstract class BookChild extends Entity
|
||||
{
|
||||
/**
|
||||
* Get the book this page sits in.
|
||||
* @return BelongsTo<Book, $this>
|
||||
*/
|
||||
public function book(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Book::class)->withTrashed();
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the book that this entity belongs to.
|
||||
*/
|
||||
public function changeBook(int $newBookId): self
|
||||
{
|
||||
$oldUrl = $this->getUrl();
|
||||
$this->book_id = $newBookId;
|
||||
$this->unsetRelation('book');
|
||||
$this->refreshSlug();
|
||||
$this->save();
|
||||
|
||||
if ($oldUrl !== $this->getUrl()) {
|
||||
app()->make(ReferenceUpdater::class)->updateEntityReferences($this, $oldUrl);
|
||||
}
|
||||
|
||||
// Update all child pages if a chapter
|
||||
if ($this instanceof Chapter) {
|
||||
foreach ($this->pages()->withTrashed()->get() as $page) {
|
||||
$page->changeBook($newBookId);
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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'];
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,7 +13,6 @@ use BookStack\Activity\Models\Viewable;
|
||||
use BookStack\Activity\Models\Watch;
|
||||
use BookStack\App\Model;
|
||||
use BookStack\App\SluggableInterface;
|
||||
use BookStack\Entities\Tools\SlugGenerator;
|
||||
use BookStack\Permissions\JointPermissionBuilder;
|
||||
use BookStack\Permissions\Models\EntityPermission;
|
||||
use BookStack\Permissions\Models\JointPermission;
|
||||
@@ -405,16 +404,6 @@ abstract class Entity extends Model implements
|
||||
app()->make(SearchIndex::class)->indexEntity(clone $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function refreshSlug(): string
|
||||
{
|
||||
$this->slug = app()->make(SlugGenerator::class)->generate($this, $this->name);
|
||||
|
||||
return $this->slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
@@ -441,6 +430,14 @@ abstract class Entity extends Model implements
|
||||
return $this->morphMany(Watch::class, 'watchable');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the related slug history for this entity.
|
||||
*/
|
||||
public function slugHistory(): MorphMany
|
||||
{
|
||||
return $this->morphMany(SlugHistory::class, 'sluggable');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
@@ -482,6 +479,7 @@ abstract class Entity extends Model implements
|
||||
'chapter' => new Chapter(),
|
||||
'book' => new Book(),
|
||||
'bookshelf' => new Bookshelf(),
|
||||
default => throw new \InvalidArgumentException("Invalid entity type: {$type}"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,11 +15,12 @@ class EntityScope implements Scope
|
||||
public function apply(Builder $builder, Model $model): void
|
||||
{
|
||||
$builder = $builder->where('type', '=', $model->getMorphClass());
|
||||
$table = $model->getTable();
|
||||
if ($model instanceof Page) {
|
||||
$builder->leftJoin('entity_page_data', 'entity_page_data.page_id', '=', 'entities.id');
|
||||
$builder->leftJoin('entity_page_data', 'entity_page_data.page_id', '=', "{$table}.id");
|
||||
} else {
|
||||
$builder->leftJoin('entity_container_data', function (JoinClause $join) use ($model) {
|
||||
$join->on('entity_container_data.entity_id', '=', 'entities.id')
|
||||
$builder->leftJoin('entity_container_data', function (JoinClause $join) use ($model, $table) {
|
||||
$join->on('entity_container_data.entity_id', '=', "{$table}.id")
|
||||
->where('entity_container_data.entity_type', '=', $model->getMorphClass());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
* @property bool $draft
|
||||
* @property int $revision_count
|
||||
* @property string $editor
|
||||
* @property Chapter $chapter
|
||||
* @property Chapter|null $chapter
|
||||
* @property Collection $attachments
|
||||
* @property Collection $revisions
|
||||
* @property PageRevision $currentRevision
|
||||
@@ -124,6 +124,14 @@ class Page extends BookChild
|
||||
return url('/' . implode('/', $parts));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the ID-based permalink for this page.
|
||||
*/
|
||||
public function getPermalink(): string
|
||||
{
|
||||
return url("/link/{$this->id}");
|
||||
}
|
||||
|
||||
/**
|
||||
* Get this page for JSON display.
|
||||
*/
|
||||
|
||||
28
app/Entities/Models/SlugHistory.php
Normal file
28
app/Entities/Models/SlugHistory.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Entities\Models;
|
||||
|
||||
use BookStack\App\Model;
|
||||
use BookStack\Permissions\Models\JointPermission;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* @property int $id
|
||||
* @property int $sluggable_id
|
||||
* @property string $sluggable_type
|
||||
* @property string $slug
|
||||
* @property ?string $parent_slug
|
||||
*/
|
||||
class SlugHistory extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'slug_history';
|
||||
|
||||
public function jointPermissions(): HasMany
|
||||
{
|
||||
return $this->hasMany(JointPermission::class, 'entity_id', 'sluggable_id')
|
||||
->whereColumn('joint_permissions.entity_type', '=', 'slug_history.sluggable_type');
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace BookStack\Entities\Queries;
|
||||
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Entities\Models\EntityTable;
|
||||
use BookStack\Entities\Tools\SlugHistory;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Query\Builder as QueryBuilder;
|
||||
use Illuminate\Database\Query\JoinClause;
|
||||
@@ -18,6 +19,7 @@ class EntityQueries
|
||||
public ChapterQueries $chapters,
|
||||
public PageQueries $pages,
|
||||
public PageRevisionQueries $revisions,
|
||||
protected SlugHistory $slugHistory,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -31,9 +33,30 @@ class EntityQueries
|
||||
$explodedId = explode(':', $identifier);
|
||||
$entityType = $explodedId[0];
|
||||
$entityId = intval($explodedId[1]);
|
||||
$queries = $this->getQueriesForType($entityType);
|
||||
|
||||
return $queries->findVisibleById($entityId);
|
||||
return $this->findVisibleById($entityType, $entityId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an entity by its ID.
|
||||
*/
|
||||
public function findVisibleById(string $type, int $id): ?Entity
|
||||
{
|
||||
$queries = $this->getQueriesForType($type);
|
||||
return $queries->findVisibleById($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an entity by looking up old slugs in the slug history.
|
||||
*/
|
||||
public function findVisibleByOldSlugs(string $type, string $slug, string $parentSlug = ''): ?Entity
|
||||
{
|
||||
$id = $this->slugHistory->lookupEntityIdUsingSlugs($type, $slug, $parentSlug);
|
||||
if ($id === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->findVisibleById($type, $id);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,6 +8,8 @@ use BookStack\Entities\Models\HasCoverInterface;
|
||||
use BookStack\Entities\Models\HasDescriptionInterface;
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Entities\Queries\PageQueries;
|
||||
use BookStack\Entities\Tools\SlugGenerator;
|
||||
use BookStack\Entities\Tools\SlugHistory;
|
||||
use BookStack\Exceptions\ImageUploadException;
|
||||
use BookStack\References\ReferenceStore;
|
||||
use BookStack\References\ReferenceUpdater;
|
||||
@@ -25,6 +27,8 @@ class BaseRepo
|
||||
protected ReferenceStore $referenceStore,
|
||||
protected PageQueries $pageQueries,
|
||||
protected BookSorter $bookSorter,
|
||||
protected SlugGenerator $slugGenerator,
|
||||
protected SlugHistory $slugHistory,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -43,7 +47,7 @@ class BaseRepo
|
||||
'updated_by' => user()->id,
|
||||
'owned_by' => user()->id,
|
||||
]);
|
||||
$entity->refreshSlug();
|
||||
$this->refreshSlug($entity);
|
||||
|
||||
if ($entity instanceof HasDescriptionInterface) {
|
||||
$this->updateDescription($entity, $input);
|
||||
@@ -78,7 +82,7 @@ class BaseRepo
|
||||
$entity->updated_by = user()->id;
|
||||
|
||||
if ($entity->isDirty('name') || empty($entity->slug)) {
|
||||
$entity->refreshSlug();
|
||||
$this->refreshSlug($entity);
|
||||
}
|
||||
|
||||
if ($entity instanceof HasDescriptionInterface) {
|
||||
@@ -155,4 +159,13 @@ class BaseRepo
|
||||
$entity->descriptionInfo()->set('', $input['description']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the slug for the given entity.
|
||||
*/
|
||||
public function refreshSlug(Entity $entity): void
|
||||
{
|
||||
$this->slugHistory->recordForEntity($entity);
|
||||
$this->slugGenerator->regenerateForEntity($entity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Models\Chapter;
|
||||
use BookStack\Entities\Queries\EntityQueries;
|
||||
use BookStack\Entities\Tools\BookContents;
|
||||
use BookStack\Entities\Tools\ParentChanger;
|
||||
use BookStack\Entities\Tools\TrashCan;
|
||||
use BookStack\Exceptions\MoveOperationException;
|
||||
use BookStack\Exceptions\PermissionsException;
|
||||
@@ -21,6 +22,7 @@ class ChapterRepo
|
||||
protected BaseRepo $baseRepo,
|
||||
protected EntityQueries $entityQueries,
|
||||
protected TrashCan $trashCan,
|
||||
protected ParentChanger $parentChanger,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -97,7 +99,7 @@ class ChapterRepo
|
||||
}
|
||||
|
||||
return (new DatabaseTransaction(function () use ($chapter, $parent) {
|
||||
$chapter = $chapter->changeBook($parent->id);
|
||||
$this->parentChanger->changeBook($chapter, $parent->id);
|
||||
$chapter->rebuildPermissions();
|
||||
Activity::add(ActivityType::CHAPTER_MOVE, $chapter);
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ use BookStack\Entities\Queries\EntityQueries;
|
||||
use BookStack\Entities\Tools\BookContents;
|
||||
use BookStack\Entities\Tools\PageContent;
|
||||
use BookStack\Entities\Tools\PageEditorType;
|
||||
use BookStack\Entities\Tools\ParentChanger;
|
||||
use BookStack\Entities\Tools\TrashCan;
|
||||
use BookStack\Exceptions\MoveOperationException;
|
||||
use BookStack\Exceptions\PermissionsException;
|
||||
@@ -31,6 +32,7 @@ class PageRepo
|
||||
protected ReferenceStore $referenceStore,
|
||||
protected ReferenceUpdater $referenceUpdater,
|
||||
protected TrashCan $trashCan,
|
||||
protected ParentChanger $parentChanger,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -58,7 +60,7 @@ class PageRepo
|
||||
$page->book_id = $parent->id;
|
||||
}
|
||||
|
||||
$defaultTemplate = $page->chapter?->defaultTemplate()->get() ?? $page->book?->defaultTemplate()->get();
|
||||
$defaultTemplate = $page->chapter?->defaultTemplate()->get() ?? $page->book->defaultTemplate()->get();
|
||||
if ($defaultTemplate) {
|
||||
$page->forceFill([
|
||||
'html' => $defaultTemplate->html,
|
||||
@@ -242,7 +244,7 @@ class PageRepo
|
||||
}
|
||||
|
||||
$page->updated_by = user()->id;
|
||||
$page->refreshSlug();
|
||||
$this->baseRepo->refreshSlug($page);
|
||||
$page->save();
|
||||
$page->indexForSearch();
|
||||
$this->referenceStore->updateForEntity($page);
|
||||
@@ -284,7 +286,7 @@ class PageRepo
|
||||
return (new DatabaseTransaction(function () use ($page, $parent) {
|
||||
$page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
|
||||
$newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
|
||||
$page = $page->changeBook($newBookId);
|
||||
$this->parentChanger->changeBook($page, $newBookId);
|
||||
$page->rebuildPermissions();
|
||||
|
||||
Activity::add(ActivityType::PAGE_MOVE, $page);
|
||||
|
||||
@@ -13,30 +13,47 @@ use BookStack\Entities\Repos\BookRepo;
|
||||
use BookStack\Entities\Repos\ChapterRepo;
|
||||
use BookStack\Entities\Repos\PageRepo;
|
||||
use BookStack\Permissions\Permission;
|
||||
use BookStack\References\ReferenceChangeContext;
|
||||
use BookStack\References\ReferenceUpdater;
|
||||
use BookStack\Uploads\Image;
|
||||
use BookStack\Uploads\ImageService;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
|
||||
class Cloner
|
||||
{
|
||||
protected ReferenceChangeContext $referenceChangeContext;
|
||||
|
||||
public function __construct(
|
||||
protected PageRepo $pageRepo,
|
||||
protected ChapterRepo $chapterRepo,
|
||||
protected BookRepo $bookRepo,
|
||||
protected ImageService $imageService,
|
||||
protected ReferenceUpdater $referenceUpdater,
|
||||
) {
|
||||
$this->referenceChangeContext = new ReferenceChangeContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone the given page into the given parent using the provided name.
|
||||
*/
|
||||
public function clonePage(Page $original, Entity $parent, string $newName): Page
|
||||
{
|
||||
$context = $this->newReferenceChangeContext();
|
||||
$page = $this->createPageClone($original, $parent, $newName);
|
||||
$this->referenceUpdater->changeReferencesUsingContext($context);
|
||||
return $page;
|
||||
}
|
||||
|
||||
protected function createPageClone(Page $original, Entity $parent, string $newName): Page
|
||||
{
|
||||
$copyPage = $this->pageRepo->getNewDraftPage($parent);
|
||||
$pageData = $this->entityToInputData($original);
|
||||
$pageData['name'] = $newName;
|
||||
|
||||
return $this->pageRepo->publishDraft($copyPage, $pageData);
|
||||
$newPage = $this->pageRepo->publishDraft($copyPage, $pageData);
|
||||
$this->referenceChangeContext->add($original, $newPage);
|
||||
|
||||
return $newPage;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -44,6 +61,14 @@ class Cloner
|
||||
* Clones all child pages.
|
||||
*/
|
||||
public function cloneChapter(Chapter $original, Book $parent, string $newName): Chapter
|
||||
{
|
||||
$context = $this->newReferenceChangeContext();
|
||||
$chapter = $this->createChapterClone($original, $parent, $newName);
|
||||
$this->referenceUpdater->changeReferencesUsingContext($context);
|
||||
return $chapter;
|
||||
}
|
||||
|
||||
protected function createChapterClone(Chapter $original, Book $parent, string $newName): Chapter
|
||||
{
|
||||
$chapterDetails = $this->entityToInputData($original);
|
||||
$chapterDetails['name'] = $newName;
|
||||
@@ -53,10 +78,12 @@ class Cloner
|
||||
if (userCan(Permission::PageCreate, $copyChapter)) {
|
||||
/** @var Page $page */
|
||||
foreach ($original->getVisiblePages() as $page) {
|
||||
$this->clonePage($page, $copyChapter, $page->name);
|
||||
$this->createPageClone($page, $copyChapter, $page->name);
|
||||
}
|
||||
}
|
||||
|
||||
$this->referenceChangeContext->add($original, $copyChapter);
|
||||
|
||||
return $copyChapter;
|
||||
}
|
||||
|
||||
@@ -65,6 +92,14 @@ class Cloner
|
||||
* Clones all child chapters and pages.
|
||||
*/
|
||||
public function cloneBook(Book $original, string $newName): Book
|
||||
{
|
||||
$context = $this->newReferenceChangeContext();
|
||||
$book = $this->createBookClone($original, $newName);
|
||||
$this->referenceUpdater->changeReferencesUsingContext($context);
|
||||
return $book;
|
||||
}
|
||||
|
||||
protected function createBookClone(Book $original, string $newName): Book
|
||||
{
|
||||
$bookDetails = $this->entityToInputData($original);
|
||||
$bookDetails['name'] = $newName;
|
||||
@@ -76,11 +111,11 @@ class Cloner
|
||||
$directChildren = $original->getDirectVisibleChildren();
|
||||
foreach ($directChildren as $child) {
|
||||
if ($child instanceof Chapter && userCan(Permission::ChapterCreate, $copyBook)) {
|
||||
$this->cloneChapter($child, $copyBook, $child->name);
|
||||
$this->createChapterClone($child, $copyBook, $child->name);
|
||||
}
|
||||
|
||||
if ($child instanceof Page && !$child->draft && userCan(Permission::PageCreate, $copyBook)) {
|
||||
$this->clonePage($child, $copyBook, $child->name);
|
||||
$this->createPageClone($child, $copyBook, $child->name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,6 +127,8 @@ class Cloner
|
||||
}
|
||||
}
|
||||
|
||||
$this->referenceChangeContext->add($original, $copyBook);
|
||||
|
||||
return $copyBook;
|
||||
}
|
||||
|
||||
@@ -155,4 +192,10 @@ class Cloner
|
||||
|
||||
return $tags;
|
||||
}
|
||||
|
||||
protected function newReferenceChangeContext(): ReferenceChangeContext
|
||||
{
|
||||
$this->referenceChangeContext = new ReferenceChangeContext();
|
||||
return $this->referenceChangeContext;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -17,7 +17,8 @@ class HierarchyTransformer
|
||||
protected BookRepo $bookRepo,
|
||||
protected BookshelfRepo $shelfRepo,
|
||||
protected Cloner $cloner,
|
||||
protected TrashCan $trashCan
|
||||
protected TrashCan $trashCan,
|
||||
protected ParentChanger $parentChanger,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -35,7 +36,7 @@ class HierarchyTransformer
|
||||
foreach ($chapter->pages as $page) {
|
||||
$page->chapter_id = 0;
|
||||
$page->save();
|
||||
$page->changeBook($book->id);
|
||||
$this->parentChanger->changeBook($page, $book->id);
|
||||
}
|
||||
|
||||
$this->trashCan->destroyEntity($chapter);
|
||||
|
||||
@@ -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}";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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,
|
||||
|
||||
40
app/Entities/Tools/ParentChanger.php
Normal file
40
app/Entities/Tools/ParentChanger.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Entities\Tools;
|
||||
|
||||
use BookStack\Entities\Models\BookChild;
|
||||
use BookStack\Entities\Models\Chapter;
|
||||
use BookStack\References\ReferenceUpdater;
|
||||
|
||||
class ParentChanger
|
||||
{
|
||||
public function __construct(
|
||||
protected SlugGenerator $slugGenerator,
|
||||
protected ReferenceUpdater $referenceUpdater
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the parent book of a chapter or page.
|
||||
*/
|
||||
public function changeBook(BookChild $child, int $newBookId): void
|
||||
{
|
||||
$oldUrl = $child->getUrl();
|
||||
|
||||
$child->book_id = $newBookId;
|
||||
$child->unsetRelation('book');
|
||||
$this->slugGenerator->regenerateForEntity($child);
|
||||
$child->save();
|
||||
|
||||
if ($oldUrl !== $child->getUrl()) {
|
||||
$this->referenceUpdater->updateEntityReferences($child, $oldUrl);
|
||||
}
|
||||
|
||||
// Update all child pages if a chapter
|
||||
if ($child instanceof Chapter) {
|
||||
foreach ($child->pages()->withTrashed()->get() as $page) {
|
||||
$this->changeBook($page, $newBookId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ class PermissionsUpdater
|
||||
{
|
||||
if (isset($data['role_permissions'])) {
|
||||
$entity->permissions()->where('role_id', '!=', 0)->delete();
|
||||
$rolePermissionData = $this->formatPermissionsFromApiRequestToEntityPermissions($data['role_permissions'] ?? [], false);
|
||||
$rolePermissionData = $this->formatPermissionsFromApiRequestToEntityPermissions($data['role_permissions'], false);
|
||||
$entity->permissions()->createMany($rolePermissionData);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,14 @@ namespace BookStack\Entities\Tools;
|
||||
use BookStack\App\Model;
|
||||
use BookStack\App\SluggableInterface;
|
||||
use BookStack\Entities\Models\BookChild;
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Users\Models\User;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class SlugGenerator
|
||||
{
|
||||
/**
|
||||
* Generate a fresh slug for the given entity.
|
||||
* Generate a fresh slug for the given item.
|
||||
* The slug will be generated so that it doesn't conflict within the same parent item.
|
||||
*/
|
||||
public function generate(SluggableInterface&Model $model, string $slugSource): string
|
||||
@@ -23,6 +25,26 @@ class SlugGenerator
|
||||
return $slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate the slug for the given entity.
|
||||
*/
|
||||
public function regenerateForEntity(Entity $entity): string
|
||||
{
|
||||
$entity->slug = $this->generate($entity, $entity->name);
|
||||
|
||||
return $entity->slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate the slug for a user.
|
||||
*/
|
||||
public function regenerateForUser(User $user): string
|
||||
{
|
||||
$user->slug = $this->generate($user, $user->name);
|
||||
|
||||
return $user->slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a name as a URL slug.
|
||||
*/
|
||||
|
||||
97
app/Entities/Tools/SlugHistory.php
Normal file
97
app/Entities/Tools/SlugHistory.php
Normal file
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Entities\Tools;
|
||||
|
||||
use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Models\BookChild;
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Entities\Models\EntityTable;
|
||||
use BookStack\Entities\Models\SlugHistory as SlugHistoryModel;
|
||||
use BookStack\Permissions\PermissionApplicator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class SlugHistory
|
||||
{
|
||||
public function __construct(
|
||||
protected PermissionApplicator $permissions,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Record the current slugs for the given entity.
|
||||
*/
|
||||
public function recordForEntity(Entity $entity): void
|
||||
{
|
||||
if (!$entity->id || !$entity->slug) {
|
||||
return;
|
||||
}
|
||||
|
||||
$parentSlug = null;
|
||||
if ($entity instanceof BookChild) {
|
||||
$parentSlug = $entity->book()->first()?->slug;
|
||||
}
|
||||
|
||||
$latest = $this->getLatestEntryForEntity($entity);
|
||||
if ($latest && $latest->slug === $entity->slug && $latest->parent_slug === $parentSlug) {
|
||||
return;
|
||||
}
|
||||
|
||||
$info = [
|
||||
'sluggable_type' => $entity->getMorphClass(),
|
||||
'sluggable_id' => $entity->id,
|
||||
'slug' => $entity->slug,
|
||||
'parent_slug' => $parentSlug,
|
||||
];
|
||||
|
||||
$entry = new SlugHistoryModel();
|
||||
$entry->forceFill($info);
|
||||
$entry->save();
|
||||
|
||||
if ($entity instanceof Book) {
|
||||
$this->recordForBookChildren($entity);
|
||||
}
|
||||
}
|
||||
|
||||
protected function recordForBookChildren(Book $book): void
|
||||
{
|
||||
$query = EntityTable::query()
|
||||
->select(['type', 'id', 'slug', DB::raw("'{$book->slug}' as parent_slug"), DB::raw('now() as created_at'), DB::raw('now() as updated_at')])
|
||||
->where('book_id', '=', $book->id)
|
||||
->whereNotNull('book_id');
|
||||
|
||||
SlugHistoryModel::query()->insertUsing(
|
||||
['sluggable_type', 'sluggable_id', 'slug', 'parent_slug', 'created_at', 'updated_at'],
|
||||
$query
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the latest visible entry for an entity which uses the given slug(s) in the history.
|
||||
*/
|
||||
public function lookupEntityIdUsingSlugs(string $type, string $slug, string $parentSlug = ''): ?int
|
||||
{
|
||||
$query = SlugHistoryModel::query()
|
||||
->where('sluggable_type', '=', $type)
|
||||
->where('slug', '=', $slug);
|
||||
|
||||
if ($parentSlug) {
|
||||
$query->where('parent_slug', '=', $parentSlug);
|
||||
}
|
||||
|
||||
$query = $this->permissions->restrictEntityRelationQuery($query, 'slug_history', 'sluggable_id', 'sluggable_type');
|
||||
|
||||
/** @var SlugHistoryModel|null $result */
|
||||
$result = $query->orderBy('created_at', 'desc')->first();
|
||||
|
||||
return $result?->sluggable_id;
|
||||
}
|
||||
|
||||
protected function getLatestEntryForEntity(Entity $entity): SlugHistoryModel|null
|
||||
{
|
||||
return SlugHistoryModel::query()
|
||||
->where('sluggable_type', '=', $entity->getMorphClass())
|
||||
->where('sluggable_id', '=', $entity->id)
|
||||
->orderBy('created_at', 'desc')
|
||||
->first();
|
||||
}
|
||||
}
|
||||
@@ -388,7 +388,7 @@ class TrashCan
|
||||
/**
|
||||
* Update entity relations to remove or update outstanding connections.
|
||||
*/
|
||||
protected function destroyCommonRelations(Entity $entity)
|
||||
protected function destroyCommonRelations(Entity $entity): void
|
||||
{
|
||||
Activity::removeEntity($entity);
|
||||
$entity->views()->delete();
|
||||
@@ -402,6 +402,7 @@ class TrashCan
|
||||
$entity->watches()->delete();
|
||||
$entity->referencesTo()->delete();
|
||||
$entity->referencesFrom()->delete();
|
||||
$entity->slugHistory()->delete();
|
||||
|
||||
if ($entity instanceof HasCoverInterface && $entity->coverInfo()->exists()) {
|
||||
$imageService = app()->make(ImageService::class);
|
||||
|
||||
@@ -208,7 +208,7 @@ class ExportFormatter
|
||||
preg_match_all("/\<img.*?src\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $imageTagsOutput);
|
||||
|
||||
// Replace image src with base64 encoded image strings
|
||||
if (isset($imageTagsOutput[0]) && count($imageTagsOutput[0]) > 0) {
|
||||
if (count($imageTagsOutput[0]) > 0) {
|
||||
foreach ($imageTagsOutput[0] as $index => $imgMatch) {
|
||||
$oldImgTagString = $imgMatch;
|
||||
$srcString = $imageTagsOutput[2][$index];
|
||||
@@ -225,7 +225,7 @@ class ExportFormatter
|
||||
preg_match_all("/\<a.*href\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $linksOutput);
|
||||
|
||||
// Update relative links to be absolute, with instance url
|
||||
if (isset($linksOutput[0]) && count($linksOutput[0]) > 0) {
|
||||
if (count($linksOutput[0]) > 0) {
|
||||
foreach ($linksOutput[0] as $index => $linkMatch) {
|
||||
$oldLinkString = $linkMatch;
|
||||
$srcString = $linksOutput[2][$index];
|
||||
@@ -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";
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,16 @@ class ZipExportReader
|
||||
{
|
||||
$this->open();
|
||||
|
||||
$info = $this->zip->statName('data.json');
|
||||
if ($info === false) {
|
||||
throw new ZipExportException(trans('errors.import_zip_cant_decode_data'));
|
||||
}
|
||||
|
||||
$maxSize = max(intval(config()->get('app.upload_limit')), 1) * 1000000;
|
||||
if ($info['size'] > $maxSize) {
|
||||
throw new ZipExportException(trans('errors.import_zip_data_too_large'));
|
||||
}
|
||||
|
||||
// Validate json data exists, including metadata
|
||||
$jsonData = $this->zip->getFromName('data.json') ?: '';
|
||||
$importData = json_decode($jsonData, true);
|
||||
@@ -73,6 +83,17 @@ class ZipExportReader
|
||||
return $this->zip->statName("files/{$fileName}") !== false;
|
||||
}
|
||||
|
||||
public function fileWithinSizeLimit(string $fileName): bool
|
||||
{
|
||||
$fileInfo = $this->zip->statName("files/{$fileName}");
|
||||
if ($fileInfo === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$maxSize = max(intval(config()->get('app.upload_limit')), 1) * 1000000;
|
||||
return $fileInfo['size'] <= $maxSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return false|resource
|
||||
*/
|
||||
|
||||
@@ -15,6 +15,7 @@ use BookStack\Exports\ZipExports\Models\ZipExportPage;
|
||||
use BookStack\Permissions\Permission;
|
||||
use BookStack\Uploads\Attachment;
|
||||
use BookStack\Uploads\Image;
|
||||
use BookStack\Uploads\ImageService;
|
||||
|
||||
class ZipExportReferences
|
||||
{
|
||||
@@ -33,6 +34,7 @@ class ZipExportReferences
|
||||
|
||||
public function __construct(
|
||||
protected ZipReferenceParser $parser,
|
||||
protected ImageService $imageService,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -133,10 +135,17 @@ class ZipExportReferences
|
||||
return "[[bsexport:image:{$model->id}]]";
|
||||
}
|
||||
|
||||
// Find and include images if in visibility
|
||||
// Get the page which we'll reference this image upon
|
||||
$page = $model->getPage();
|
||||
$pageExportModel = $this->pages[$page->id] ?? ($exportModel instanceof ZipExportPage ? $exportModel : null);
|
||||
if (isset($this->images[$model->id]) || ($page && $pageExportModel && userCan(Permission::PageView, $page))) {
|
||||
$pageExportModel = null;
|
||||
if ($page && isset($this->pages[$page->id])) {
|
||||
$pageExportModel = $this->pages[$page->id];
|
||||
} elseif ($exportModel instanceof ZipExportPage) {
|
||||
$pageExportModel = $exportModel;
|
||||
}
|
||||
|
||||
// Add the image to the export if it's accessible or just return the existing reference if already added
|
||||
if (isset($this->images[$model->id]) || ($pageExportModel && $this->imageService->imageAccessible($model))) {
|
||||
if (!isset($this->images[$model->id])) {
|
||||
$exportImage = ZipExportImage::fromModel($model, $files);
|
||||
$this->images[$model->id] = $exportImage;
|
||||
@@ -144,6 +153,7 @@ class ZipExportReferences
|
||||
}
|
||||
return "[[bsexport:image:{$model->id}]]";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ class ZipFileReferenceRule implements ValidationRule
|
||||
) {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
@@ -23,6 +22,13 @@ class ZipFileReferenceRule implements ValidationRule
|
||||
$fail('validation.zip_file')->translate();
|
||||
}
|
||||
|
||||
if (!$this->context->zipReader->fileWithinSizeLimit($value)) {
|
||||
$fail('validation.zip_file_size')->translate([
|
||||
'attribute' => $value,
|
||||
'size' => config('app.upload_limit'),
|
||||
]);
|
||||
}
|
||||
|
||||
if (!empty($this->acceptedMimes)) {
|
||||
$fileMime = $this->context->zipReader->sniffFileMime($value);
|
||||
if (!in_array($fileMime, $this->acceptedMimes)) {
|
||||
|
||||
@@ -82,10 +82,8 @@ class ZipImportRunner
|
||||
$entity = $this->importBook($exportModel, $reader);
|
||||
} else if ($exportModel instanceof ZipExportChapter) {
|
||||
$entity = $this->importChapter($exportModel, $parent, $reader);
|
||||
} else if ($exportModel instanceof ZipExportPage) {
|
||||
$entity = $this->importPage($exportModel, $parent, $reader);
|
||||
} else {
|
||||
throw new ZipImportException(['No importable data found in import data.']);
|
||||
$entity = $this->importPage($exportModel, $parent, $reader);
|
||||
}
|
||||
|
||||
$this->references->replaceReferences();
|
||||
@@ -132,7 +130,7 @@ class ZipImportRunner
|
||||
'name' => $exportBook->name,
|
||||
'description_html' => $exportBook->description_html ?? '',
|
||||
'image' => $exportBook->cover ? $this->zipFileToUploadedFile($exportBook->cover, $reader) : null,
|
||||
'tags' => $this->exportTagsToInputArray($exportBook->tags ?? []),
|
||||
'tags' => $this->exportTagsToInputArray($exportBook->tags),
|
||||
]);
|
||||
|
||||
if ($book->coverInfo()->getImage()) {
|
||||
@@ -151,7 +149,7 @@ class ZipImportRunner
|
||||
foreach ($children as $child) {
|
||||
if ($child instanceof ZipExportChapter) {
|
||||
$this->importChapter($child, $book, $reader);
|
||||
} else if ($child instanceof ZipExportPage) {
|
||||
} else {
|
||||
$this->importPage($child, $book, $reader);
|
||||
}
|
||||
}
|
||||
@@ -166,7 +164,7 @@ class ZipImportRunner
|
||||
$chapter = $this->chapterRepo->create([
|
||||
'name' => $exportChapter->name,
|
||||
'description_html' => $exportChapter->description_html ?? '',
|
||||
'tags' => $this->exportTagsToInputArray($exportChapter->tags ?? []),
|
||||
'tags' => $this->exportTagsToInputArray($exportChapter->tags),
|
||||
], $parent);
|
||||
|
||||
$exportPages = $exportChapter->pages;
|
||||
@@ -199,7 +197,7 @@ class ZipImportRunner
|
||||
'name' => $exportPage->name,
|
||||
'markdown' => $exportPage->markdown ?? '',
|
||||
'html' => $exportPage->html ?? '',
|
||||
'tags' => $this->exportTagsToInputArray($exportPage->tags ?? []),
|
||||
'tags' => $this->exportTagsToInputArray($exportPage->tags),
|
||||
]);
|
||||
|
||||
$this->references->addPage($page, $exportPage);
|
||||
@@ -265,6 +263,12 @@ class ZipImportRunner
|
||||
|
||||
protected function zipFileToUploadedFile(string $fileName, ZipExportReader $reader): UploadedFile
|
||||
{
|
||||
if (!$reader->fileWithinSizeLimit($fileName)) {
|
||||
throw new ZipImportException([
|
||||
"File $fileName exceeds app upload limit."
|
||||
]);
|
||||
}
|
||||
|
||||
$tempPath = tempnam(sys_get_temp_dir(), 'bszipextract');
|
||||
$fileStream = $reader->streamFile($fileName);
|
||||
$tempStream = fopen($tempPath, 'wb');
|
||||
@@ -296,7 +300,7 @@ class ZipImportRunner
|
||||
array_push($chapters, ...$exportModel->chapters);
|
||||
} else if ($exportModel instanceof ZipExportChapter) {
|
||||
$chapters[] = $exportModel;
|
||||
} else if ($exportModel instanceof ZipExportPage) {
|
||||
} else {
|
||||
$pages[] = $exportModel;
|
||||
}
|
||||
|
||||
|
||||
@@ -68,10 +68,6 @@ class ZipReferenceParser
|
||||
$matches = [];
|
||||
preg_match_all($referenceRegex, $content, $matches);
|
||||
|
||||
if (count($matches) < 3) {
|
||||
return $content;
|
||||
}
|
||||
|
||||
for ($i = 0; $i < count($matches[0]); $i++) {
|
||||
$referenceText = $matches[0][$i];
|
||||
$type = strtolower($matches[1][$i]);
|
||||
|
||||
@@ -62,7 +62,7 @@ abstract class Controller extends BaseController
|
||||
*/
|
||||
protected function checkPermission(string|Permission $permission): void
|
||||
{
|
||||
if (!user() || !user()->can($permission)) {
|
||||
if (!user()->can($permission)) {
|
||||
$this->showPermissionError();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,10 @@ use Illuminate\Session\Middleware\StartSession as Middleware;
|
||||
class StartSessionExtended extends Middleware
|
||||
{
|
||||
protected static array $pathPrefixesExcludedFromHistory = [
|
||||
'uploads/images/'
|
||||
'uploads/images/',
|
||||
'dist/',
|
||||
'manifest.json',
|
||||
'opensearch.xml',
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -61,8 +61,7 @@ class JointPermissionBuilder
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var BookChild $entity */
|
||||
if ($entity->book) {
|
||||
if ($entity instanceof BookChild) {
|
||||
$entities[] = $entity->book;
|
||||
}
|
||||
|
||||
|
||||
45
app/References/ReferenceChangeContext.php
Normal file
45
app/References/ReferenceChangeContext.php
Normal file
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\References;
|
||||
|
||||
use BookStack\Entities\Models\Entity;
|
||||
|
||||
class ReferenceChangeContext
|
||||
{
|
||||
/**
|
||||
* Entity pairs where the first is the old entity and the second is the new entity.
|
||||
* @var array<array{0: Entity, 1: Entity}>
|
||||
*/
|
||||
protected array $changes = [];
|
||||
|
||||
public function add(Entity $oldEntity, Entity $newEntity): void
|
||||
{
|
||||
$this->changes[] = [$oldEntity, $newEntity];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the new entities from the changes.
|
||||
*/
|
||||
public function getNewEntities(): array
|
||||
{
|
||||
return array_column($this->changes, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the old entities from the changes.
|
||||
*/
|
||||
public function getOldEntities(): array
|
||||
{
|
||||
return array_column($this->changes, 0);
|
||||
}
|
||||
|
||||
public function getNewForOld(Entity $oldEntity): ?Entity
|
||||
{
|
||||
foreach ($this->changes as [$old, $new]) {
|
||||
if ($old->id === $oldEntity->id && $old->type === $oldEntity->type) {
|
||||
return $new;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ namespace BookStack\References;
|
||||
use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Models\HasDescriptionInterface;
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Entities\Models\EntityContainerData;
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Entities\Repos\RevisionRepo;
|
||||
use BookStack\Util\HtmlDocument;
|
||||
@@ -30,6 +29,47 @@ class ReferenceUpdater
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Change existing references for a range of entities using the given context.
|
||||
*/
|
||||
public function changeReferencesUsingContext(ReferenceChangeContext $context): void
|
||||
{
|
||||
$bindings = [];
|
||||
foreach ($context->getOldEntities() as $old) {
|
||||
$bindings[] = $old->getMorphClass();
|
||||
$bindings[] = $old->id;
|
||||
}
|
||||
|
||||
// No targets to update within the context, so no need to continue.
|
||||
if (count($bindings) < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
$toReferenceQuery = '(to_type, to_id) IN (' . rtrim(str_repeat('(?,?),', count($bindings) / 2), ',') . ')';
|
||||
|
||||
// Cycle each new entity in the context
|
||||
foreach ($context->getNewEntities() as $new) {
|
||||
// For each, get all references from it which lead to other items within the context of the change
|
||||
$newReferencesInContext = $new->referencesFrom()->whereRaw($toReferenceQuery, $bindings)->get();
|
||||
// For each reference, update the URL and the reference entry
|
||||
foreach ($newReferencesInContext as $reference) {
|
||||
$oldToEntity = $reference->to;
|
||||
$newToEntity = $context->getNewForOld($oldToEntity);
|
||||
if ($newToEntity === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->updateReferencesWithinEntity($new, $oldToEntity->getUrl(), $newToEntity->getUrl());
|
||||
if ($newToEntity instanceof Page && $oldToEntity instanceof Page) {
|
||||
$this->updateReferencesWithinEntity($new, $oldToEntity->getPermalink(), $newToEntity->getPermalink());
|
||||
}
|
||||
$reference->to_id = $newToEntity->id;
|
||||
$reference->to_type = $newToEntity->getMorphClass();
|
||||
$reference->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Reference[]
|
||||
*/
|
||||
|
||||
@@ -25,11 +25,12 @@ class SearchController extends Controller
|
||||
$searchOpts = SearchOptions::fromRequest($request);
|
||||
$fullSearchString = $searchOpts->toString();
|
||||
$page = intval($request->get('page', '0')) ?: 1;
|
||||
$count = setting()->getInteger('lists-page-count-search', 18, 1, 1000);
|
||||
|
||||
$results = $this->searchRunner->searchEntities($searchOpts, 'all', $page, 20);
|
||||
$results = $this->searchRunner->searchEntities($searchOpts, 'all', $page, $count);
|
||||
$formatter->format($results['results']->all(), $searchOpts);
|
||||
$paginator = new LengthAwarePaginator($results['results'], $results['total'], 20, $page);
|
||||
$paginator->setPath('/search');
|
||||
$paginator = new LengthAwarePaginator($results['results'], $results['total'], $count, $page);
|
||||
$paginator->setPath(url('/search'));
|
||||
$paginator->appends($request->except('page'));
|
||||
|
||||
$this->setPageTitle(trans('entities.search_for_term', ['term' => $fullSearchString]));
|
||||
@@ -77,8 +78,9 @@ class SearchController extends Controller
|
||||
|
||||
// Search for entities otherwise show most popular
|
||||
if ($searchTerm !== false) {
|
||||
$searchTerm .= ' {type:' . implode('|', $entityTypes) . '}';
|
||||
$entities = $this->searchRunner->searchEntities(SearchOptions::fromString($searchTerm), 'all', 1, 20)['results'];
|
||||
$options = SearchOptions::fromString($searchTerm);
|
||||
$options->setFilter('type', implode('|', $entityTypes));
|
||||
$entities = $this->searchRunner->searchEntities($options, 'all', 1, 20)['results'];
|
||||
} else {
|
||||
$entities = $queryPopular->run(20, 0, $entityTypes);
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ class SearchIndex
|
||||
$termMap = $this->textToTermCountMap($text);
|
||||
|
||||
foreach ($termMap as $term => $count) {
|
||||
$termMap[$term] = floor($count * $scoreAdjustment);
|
||||
$termMap[$term] = intval($count * $scoreAdjustment);
|
||||
}
|
||||
|
||||
return $termMap;
|
||||
|
||||
@@ -82,4 +82,12 @@ class SearchOptionSet
|
||||
$values = array_values(array_filter($this->options, fn (SearchOption $option) => !$option->negated));
|
||||
return new self($values);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self<T>
|
||||
*/
|
||||
public function limit(int $limit): self
|
||||
{
|
||||
return new self(array_slice(array_values($this->options), 0, $limit));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ class SearchOptions
|
||||
{
|
||||
$instance = new self();
|
||||
$instance->addOptionsFromString($search);
|
||||
$instance->limitOptions();
|
||||
return $instance;
|
||||
}
|
||||
|
||||
@@ -87,6 +88,8 @@ class SearchOptions
|
||||
$instance->filters = $instance->filters->merge($extras->filters);
|
||||
}
|
||||
|
||||
$instance->limitOptions();
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
@@ -118,13 +121,11 @@ class SearchOptions
|
||||
foreach ($patterns as $termType => $pattern) {
|
||||
$matches = [];
|
||||
preg_match_all($pattern, $searchString, $matches);
|
||||
if (count($matches) > 0) {
|
||||
foreach ($matches[1] as $index => $value) {
|
||||
$negated = str_starts_with($matches[0][$index], '-');
|
||||
$terms[$termType][] = $constructors[$termType]($value, $negated);
|
||||
}
|
||||
$searchString = preg_replace($pattern, '', $searchString);
|
||||
foreach ($matches[1] as $index => $value) {
|
||||
$negated = str_starts_with($matches[0][$index], '-');
|
||||
$terms[$termType][] = $constructors[$termType]($value, $negated);
|
||||
}
|
||||
$searchString = preg_replace($pattern, '', $searchString);
|
||||
}
|
||||
|
||||
// Unescape exacts and backslash escapes
|
||||
@@ -147,6 +148,25 @@ class SearchOptions
|
||||
$this->filters = $this->filters->merge(new SearchOptionSet($terms['filters']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Limit the amount of search options to reasonable levels.
|
||||
* Provides higher limits to logged-in users since that signals a slightly
|
||||
* higher level of trust.
|
||||
*/
|
||||
protected function limitOptions(): void
|
||||
{
|
||||
$userLoggedIn = !user()->isGuest();
|
||||
$searchLimit = $userLoggedIn ? 10 : 5;
|
||||
$exactLimit = $userLoggedIn ? 4 : 2;
|
||||
$tagLimit = $userLoggedIn ? 8 : 4;
|
||||
$filterLimit = $userLoggedIn ? 10 : 5;
|
||||
|
||||
$this->searches = $this->searches->limit($searchLimit);
|
||||
$this->exacts = $this->exacts->limit($exactLimit);
|
||||
$this->tags = $this->tags->limit($tagLimit);
|
||||
$this->filters = $this->filters->limit($filterLimit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode backslash escaping within the input string.
|
||||
*/
|
||||
@@ -239,7 +259,7 @@ class SearchOptions
|
||||
$userFilters = ['updated_by', 'created_by', 'owned_by'];
|
||||
$unsupportedFilters = ['is_template', 'sort_by'];
|
||||
foreach ($this->filters->all() as $filter) {
|
||||
if (in_array($filter->getKey(), $userFilters, true) && $filter->value !== null && $filter->value !== 'me') {
|
||||
if (in_array($filter->getKey(), $userFilters, true) && $filter->value && $filter->value !== 'me') {
|
||||
$options[] = $filter;
|
||||
} else if (in_array($filter->getKey(), $unsupportedFilters, true)) {
|
||||
$options[] = $filter;
|
||||
|
||||
@@ -14,7 +14,7 @@ class AppSettingsStore
|
||||
) {
|
||||
}
|
||||
|
||||
public function storeFromUpdateRequest(Request $request, string $category)
|
||||
public function storeFromUpdateRequest(Request $request, string $category): void
|
||||
{
|
||||
$this->storeSimpleSettings($request);
|
||||
if ($category === 'customization') {
|
||||
@@ -76,7 +76,7 @@ class AppSettingsStore
|
||||
protected function storeSimpleSettings(Request $request): void
|
||||
{
|
||||
foreach ($request->all() as $name => $value) {
|
||||
if (strpos($name, 'setting-') !== 0) {
|
||||
if (!str_starts_with($name, 'setting-')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ class AppSettingsStore
|
||||
}
|
||||
}
|
||||
|
||||
protected function destroyExistingSettingImage(string $settingKey)
|
||||
protected function destroyExistingSettingImage(string $settingKey): void
|
||||
{
|
||||
$existingVal = setting()->get($settingKey);
|
||||
if ($existingVal) {
|
||||
|
||||
@@ -28,6 +28,21 @@ class SettingService
|
||||
return $this->formatValue($value, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a setting from the database as an integer.
|
||||
* Returns the default value if not found or not an integer, and clamps the value to the given min/max range.
|
||||
*/
|
||||
public function getInteger(string $key, int $default, int $min = 0, int $max = PHP_INT_MAX): int
|
||||
{
|
||||
$value = $this->get($key, $default);
|
||||
if (!is_numeric($value)) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
$int = intval($value);
|
||||
return max($min, min($max, $int));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a value from the session instead of the main store option.
|
||||
*/
|
||||
|
||||
@@ -26,9 +26,14 @@ class UserNotificationPreferences
|
||||
return $this->getNotificationSetting('comment-replies');
|
||||
}
|
||||
|
||||
public function notifyOnCommentMentions(): bool
|
||||
{
|
||||
return $this->getNotificationSetting('comment-mentions');
|
||||
}
|
||||
|
||||
public function updateFromSettingsArray(array $settings)
|
||||
{
|
||||
$allowList = ['own-page-changes', 'own-page-comments', 'comment-replies'];
|
||||
$allowList = ['own-page-changes', 'own-page-comments', 'comment-replies', 'comment-mentions'];
|
||||
foreach ($settings as $setting => $status) {
|
||||
if (!in_array($setting, $allowList)) {
|
||||
continue;
|
||||
|
||||
@@ -8,12 +8,14 @@ use BookStack\Entities\Models\Chapter;
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Entities\Queries\EntityQueries;
|
||||
use BookStack\Entities\Tools\ParentChanger;
|
||||
use BookStack\Permissions\Permission;
|
||||
|
||||
class BookSorter
|
||||
{
|
||||
public function __construct(
|
||||
protected EntityQueries $queries,
|
||||
protected ParentChanger $parentChanger,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -123,9 +125,8 @@ class BookSorter
|
||||
*/
|
||||
protected function applySortUpdates(BookSortMapItem $sortMapItem, array $modelMap): void
|
||||
{
|
||||
/** @var BookChild $model */
|
||||
$model = $modelMap[$sortMapItem->type . ':' . $sortMapItem->id] ?? null;
|
||||
if (!$model) {
|
||||
if (!($model instanceof BookChild)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -155,7 +156,7 @@ class BookSorter
|
||||
|
||||
// Action the required changes
|
||||
if ($bookChanged) {
|
||||
$model = $model->changeBook($newBook->id);
|
||||
$this->parentChanger->changeBook($model, $newBook->id);
|
||||
}
|
||||
|
||||
if ($model instanceof Page && $chapterChanged) {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
59
app/Theming/ThemeModule.php
Normal file
59
app/Theming/ThemeModule.php
Normal 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;
|
||||
}
|
||||
}
|
||||
7
app/Theming/ThemeModuleException.php
Normal file
7
app/Theming/ThemeModuleException.php
Normal file
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Theming;
|
||||
|
||||
class ThemeModuleException extends \Exception
|
||||
{
|
||||
}
|
||||
140
app/Theming/ThemeModuleManager.php
Normal file
140
app/Theming/ThemeModuleManager.php
Normal file
@@ -0,0 +1,140 @@
|
||||
<?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;
|
||||
try {
|
||||
$zip->extractTo($folderPath);
|
||||
} catch (ThemeModuleException $exception) {
|
||||
if (is_dir($folderPath)) {
|
||||
$this->deleteDirectoryRecursively($folderPath);
|
||||
}
|
||||
throw new ThemeModuleException("Failed to load extract files from module ZIP with error: {$exception->getMessage()}");
|
||||
}
|
||||
|
||||
$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;
|
||||
}
|
||||
}
|
||||
155
app/Theming/ThemeModuleZip.php
Normal file
155
app/Theming/ThemeModuleZip.php
Normal file
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Theming;
|
||||
|
||||
use BookStack\Util\FilePathNormalizer;
|
||||
use ZipArchive;
|
||||
|
||||
readonly class ThemeModuleZip
|
||||
{
|
||||
public function __construct(
|
||||
protected string $path
|
||||
) {
|
||||
}
|
||||
|
||||
public function extractTo(string $destinationPath): void
|
||||
{
|
||||
$zip = new ZipArchive();
|
||||
$zip->open($this->path);
|
||||
$prefix = $this->getZipContentPrefix($zip);
|
||||
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$name = $zip->getNameIndex($i);
|
||||
$entryIsDir = str_ends_with($name, "/");
|
||||
if ($entryIsDir) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$stream = $zip->getStreamIndex($i);
|
||||
|
||||
if ($prefix) {
|
||||
if (!str_starts_with($name, $prefix) || $name === $prefix) {
|
||||
continue;
|
||||
}
|
||||
$name = str_replace($prefix, '', $name);
|
||||
}
|
||||
|
||||
try {
|
||||
$targetPath = $destinationPath . DIRECTORY_SEPARATOR . FilePathNormalizer::normalize($name);
|
||||
} catch (\Exception $exception) {
|
||||
throw new ThemeModuleException("Bad file path found in module ZIP file: {$name}");
|
||||
}
|
||||
|
||||
$targetPathDir = dirname($targetPath);
|
||||
if (!is_dir($targetPathDir)) {
|
||||
$dirCreated = mkdir($targetPathDir, 0777, true);
|
||||
if (!$dirCreated) {
|
||||
throw new ThemeModuleException("Failed to create directory {$targetPathDir} when extracting module files");
|
||||
}
|
||||
}
|
||||
|
||||
$targetFile = fopen($targetPath, 'w');
|
||||
$written = stream_copy_to_stream($stream, $targetFile);
|
||||
if (!$written) {
|
||||
throw new ThemeModuleException("Failed to write to {$targetPath} when extracting module files");
|
||||
}
|
||||
fclose($targetFile);
|
||||
}
|
||||
|
||||
$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}");
|
||||
}
|
||||
|
||||
$prefix = $this->getZipContentPrefix($zip);
|
||||
$moduleJsonText = $zip->getFromName("{$prefix}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;
|
||||
}
|
||||
|
||||
protected function getZipContentPrefix(ZipArchive $zip): string
|
||||
{
|
||||
$index = $zip->locateName('bookstack-module.json', ZipArchive::FL_NODIR);
|
||||
if ($index === false) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$location = $zip->getNameIndex($index);
|
||||
$pathParts = explode('/', $location);
|
||||
if (count($pathParts) !== 2) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $pathParts[0] . '/';
|
||||
}
|
||||
}
|
||||
@@ -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
115
app/Theming/ThemeViews.php
Normal 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);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user