mirror of
https://github.com/BookStackApp/BookStack.git
synced 2026-02-05 00:29:48 +03:00
Compare commits
401 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0838d5ea16 | ||
|
|
449ac40114 | ||
|
|
f8e4ea82c6 | ||
|
|
047195c033 | ||
|
|
a7b30c284c | ||
|
|
c3412d8c1c | ||
|
|
3131050acd | ||
|
|
c0d2874892 | ||
|
|
481f356068 | ||
|
|
955837c9aa | ||
|
|
c6e35c2e7c | ||
|
|
0436ccfebf | ||
|
|
f5da31037d | ||
|
|
46613f76f6 | ||
|
|
519acaf324 | ||
|
|
849bc4d6c3 | ||
|
|
ee994fa2b7 | ||
|
|
13a79b3f96 | ||
|
|
7c79b10fb6 | ||
|
|
5c481b4282 | ||
|
|
9443682ae4 | ||
|
|
0311e3d2d7 | ||
|
|
5940a91809 | ||
|
|
9a4651badb | ||
|
|
a50a256939 | ||
|
|
4830248a1e | ||
|
|
1256b30ad4 | ||
|
|
777cca76da | ||
|
|
a2d13124af | ||
|
|
bd966ef99e | ||
|
|
a6b5733ec2 | ||
|
|
e899066e96 | ||
|
|
f4f2435856 | ||
|
|
fca4a0563e | ||
|
|
0bc9ddd780 | ||
|
|
c66f3b2a37 | ||
|
|
7bc0d54af1 | ||
|
|
92d15d9cf2 | ||
|
|
b06147fef7 | ||
|
|
776ec7b9e7 | ||
|
|
8aa6bdc8ab | ||
|
|
4ab17157b1 | ||
|
|
6d7ffab115 | ||
|
|
c8cfec96dc | ||
|
|
d145efb6f6 | ||
|
|
c54101c603 | ||
|
|
865e5aecc9 | ||
|
|
ae4d1d804a | ||
|
|
5fc19b0edf | ||
|
|
0a73b70b64 | ||
|
|
2668aae09b | ||
|
|
3b9c0b34ae | ||
|
|
53f32849a9 | ||
|
|
7ca8bdc231 | ||
|
|
6621d55f3d | ||
|
|
d55db06c01 | ||
|
|
6b4b500a33 | ||
|
|
5ffec2c52d | ||
|
|
ec07793cda | ||
|
|
61adc735c8 | ||
|
|
7bbf591a7f | ||
|
|
61f8d18af5 | ||
|
|
f786d25f2e | ||
|
|
e62f4426ea | ||
|
|
32ba3a591f | ||
|
|
73025719a4 | ||
|
|
d55684531f | ||
|
|
d15eb129b0 | ||
|
|
3626a2265b | ||
|
|
d13abc7e1d | ||
|
|
2442829ef2 | ||
|
|
795b28162a | ||
|
|
31706ea06b | ||
|
|
4b9e6042d5 | ||
|
|
d279b0830b | ||
|
|
181ab91b1d | ||
|
|
841350a937 | ||
|
|
12183bac07 | ||
|
|
306f41b6f0 | ||
|
|
c1d76d2571 | ||
|
|
f83074d50e | ||
|
|
2be892be70 | ||
|
|
c934b9319f | ||
|
|
35a51197ce | ||
|
|
47fd578edb | ||
|
|
add091305c | ||
|
|
3d017594a8 | ||
|
|
0dcb2ec78c | ||
|
|
9186e77d27 | ||
|
|
6045aff33a | ||
|
|
dca9765d5d | ||
|
|
a37d0c57dc | ||
|
|
054475135a | ||
|
|
02a35b6db4 | ||
|
|
b80992ca59 | ||
|
|
c606970e38 | ||
|
|
dfeca246a0 | ||
|
|
3476d83ecc | ||
|
|
3617ab1540 | ||
|
|
e65b4b63a2 | ||
|
|
7cac3f4780 | ||
|
|
c4839c783a | ||
|
|
a5751a584c | ||
|
|
f518a3be37 | ||
|
|
0208f066c5 | ||
|
|
2d0461b63a | ||
|
|
b913ae703d | ||
|
|
1611b0399f | ||
|
|
8d4b8ff4f3 | ||
|
|
77a88618c2 | ||
|
|
8b062d4795 | ||
|
|
717b516341 | ||
|
|
fda242d3da | ||
|
|
aac547934c | ||
|
|
92cd11d105 | ||
|
|
13115ace84 | ||
|
|
5c9b90ea0d | ||
|
|
074f193e2f | ||
|
|
7f2604c8e8 | ||
|
|
b71b2a4376 | ||
|
|
68df43e5a8 | ||
|
|
c5ca865723 | ||
|
|
b862f12a50 | ||
|
|
b0f8b11054 | ||
|
|
7650ebf2f9 | ||
|
|
d9ea52522e | ||
|
|
2e718c12e1 | ||
|
|
a43a1832f5 | ||
|
|
c4f7368c1c | ||
|
|
2a32475541 | ||
|
|
1243108e0f | ||
|
|
3280919370 | ||
|
|
d149b809b1 | ||
|
|
eb47e11916 | ||
|
|
9d6bc1ad4d | ||
|
|
30bf0ce632 | ||
|
|
b64c9b31d5 | ||
|
|
f9dbbe5d70 | ||
|
|
05f7f4cb17 | ||
|
|
454b152b95 | ||
|
|
b29fe5c46d | ||
|
|
131ac29df4 | ||
|
|
3a9d18a6cd | ||
|
|
59e2c5e52a | ||
|
|
d29b14ebfd | ||
|
|
73f9834e6f | ||
|
|
3afe855156 | ||
|
|
cdd446ac73 | ||
|
|
1dd1024eba | ||
|
|
752cfe2f67 | ||
|
|
25baaa8189 | ||
|
|
d2d0331782 | ||
|
|
8121418e18 | ||
|
|
5ab31a8191 | ||
|
|
0e69ab1938 | ||
|
|
058007109e | ||
|
|
32b29fcdfc | ||
|
|
8f92b6f21b | ||
|
|
62f78f1c6d | ||
|
|
f8c0aaff03 | ||
|
|
a27df485bb | ||
|
|
bfde896f0b | ||
|
|
1cdc0a7a3d | ||
|
|
3e99ce4098 | ||
|
|
d19b86640b | ||
|
|
2936ba609b | ||
|
|
ce1e20501c | ||
|
|
295532fa7a | ||
|
|
642ba668b1 | ||
|
|
4f36cdd757 | ||
|
|
8821844c4a | ||
|
|
1262083fcf | ||
|
|
c82fa33210 | ||
|
|
15c79c38db | ||
|
|
e7dcc2dcdf | ||
|
|
099f6104d0 | ||
|
|
8bdf948743 | ||
|
|
e8f44186a8 | ||
|
|
ecda4e1d6f | ||
|
|
64da80cbf4 | ||
|
|
5fa728f28a | ||
|
|
c61ce8dee4 | ||
|
|
f656a82fe7 | ||
|
|
5bfba281fc | ||
|
|
18ede9bbd3 | ||
|
|
2e7544a865 | ||
|
|
5e3c3ad634 | ||
|
|
add238fe9f | ||
|
|
8d159f77e4 | ||
|
|
573a2dd22a | ||
|
|
b55cc803d3 | ||
|
|
fa566f156a | ||
|
|
78a0a2f519 | ||
|
|
42cbd6adef | ||
|
|
6117349893 | ||
|
|
1256320c72 | ||
|
|
1ba0d26fdd | ||
|
|
802f69cf35 | ||
|
|
bb44334224 | ||
|
|
9bfcadd95f | ||
|
|
62c8eb3357 | ||
|
|
c03e44124a | ||
|
|
5c6671b3bf | ||
|
|
abe7467ae5 | ||
|
|
304ade418e | ||
|
|
997931c42f | ||
|
|
0ec0913846 | ||
|
|
e980564fd6 | ||
|
|
8a9215ecad | ||
|
|
304a1d8f91 | ||
|
|
dfbc78947f | ||
|
|
4f5ad171ac | ||
|
|
94b1cffa2d | ||
|
|
268e353431 | ||
|
|
b491b5fbca | ||
|
|
13dae24cbe | ||
|
|
6211d6bcfc | ||
|
|
a384599cfa | ||
|
|
dca14feaaa | ||
|
|
d7ccb3ce6a | ||
|
|
6548ea4a12 | ||
|
|
c3a1fabbf0 | ||
|
|
d2542d6265 | ||
|
|
0e343c408f | ||
|
|
5c78f8352e | ||
|
|
35b45a2b8d | ||
|
|
5050719ea3 | ||
|
|
5508c171db | ||
|
|
3b4d3430a5 | ||
|
|
213a86e3c0 | ||
|
|
2b746425c9 | ||
|
|
5c15f4add2 | ||
|
|
92ad81429f | ||
|
|
f1b8e857bf | ||
|
|
c291d27c19 | ||
|
|
f4449928f8 | ||
|
|
45a15b4792 | ||
|
|
2291d78382 | ||
|
|
7901ca9e6b | ||
|
|
a7de251876 | ||
|
|
7bd89316bc | ||
|
|
b9306a9029 | ||
|
|
a208c46b62 | ||
|
|
a65701294e | ||
|
|
69683d50ec | ||
|
|
37d020c083 | ||
|
|
ec79517493 | ||
|
|
d938565839 | ||
|
|
ccd94684eb | ||
|
|
103a8a8e8e | ||
|
|
c13ce18837 | ||
|
|
7093daa49d | ||
|
|
b897af2ed0 | ||
|
|
d28278bba6 | ||
|
|
12cc2f0689 | ||
|
|
bf8a84a8b1 | ||
|
|
4f5f7c10b1 | ||
|
|
a34023f715 | ||
|
|
b2ac3e0834 | ||
|
|
5b0cb3dd50 | ||
|
|
ac0cd9995d | ||
|
|
7e03a973d8 | ||
|
|
d89a2fdb15 | ||
|
|
958b537a49 | ||
|
|
8a66365d48 | ||
|
|
da82e70ca3 | ||
|
|
04cca77ae6 | ||
|
|
c091f67db3 | ||
|
|
7f5fd16dc6 | ||
|
|
0d1a237f81 | ||
|
|
786a434c03 | ||
|
|
25c4f4b02b | ||
|
|
481580be17 | ||
|
|
593645acfe | ||
|
|
b9751807e7 | ||
|
|
ee88832f1a | ||
|
|
dbda82ef92 | ||
|
|
ad8bc5fe21 | ||
|
|
5bf75786c6 | ||
|
|
cf9ccfcd5b | ||
|
|
5116d83d38 | ||
|
|
387c786768 | ||
|
|
2641586a6f | ||
|
|
33b46882f3 | ||
|
|
9a5c287470 | ||
|
|
6effc6d262 | ||
|
|
ff6c5aaecb | ||
|
|
1ff2826678 | ||
|
|
7e31725d48 | ||
|
|
6d7ff59a89 | ||
|
|
6d2cd20e80 | ||
|
|
b0c574356a | ||
|
|
980a684b14 | ||
|
|
d56eea9279 | ||
|
|
2be504e0d2 | ||
|
|
c84d999456 | ||
|
|
01825ddb93 | ||
|
|
1f88bc2a59 | ||
|
|
ebe2ca7faf | ||
|
|
f4005a139b | ||
|
|
fca8f928a3 | ||
|
|
ace8af077d | ||
|
|
e50cd33277 | ||
|
|
8486775edf | ||
|
|
5887322178 | ||
|
|
3f86937f74 | ||
|
|
2f119d3033 | ||
|
|
5f07f31c9f | ||
|
|
a71aa241ad | ||
|
|
97b201f61f | ||
|
|
a8ef820443 | ||
|
|
7e1a8e5ec6 | ||
|
|
19ee1c9be7 | ||
|
|
fcf0bf79a9 | ||
|
|
0ece664475 | ||
|
|
509af2463d | ||
|
|
5632fef621 | ||
|
|
8ec26e8083 | ||
|
|
617b2edea0 | ||
|
|
55d074f1a5 | ||
|
|
7e6f6af463 | ||
|
|
d00cf6e1ba | ||
|
|
9fdd100f2d | ||
|
|
57d8449660 | ||
|
|
ebd4604f21 | ||
|
|
36a4d79120 | ||
|
|
f3fa63a5ae | ||
|
|
5164375b18 | ||
|
|
fec44452cb | ||
|
|
18ab38a87b | ||
|
|
0f9957bc03 | ||
|
|
80f258c3c5 | ||
|
|
90341e0e00 | ||
|
|
3298374113 | ||
|
|
227c5e155b | ||
|
|
fdbbcf2b8a | ||
|
|
0a07b0d162 | ||
|
|
07e45a20e5 | ||
|
|
14056c69e6 | ||
|
|
fb9c840c46 | ||
|
|
94165cc18f | ||
|
|
f5ecd51461 | ||
|
|
e9f906ce56 | ||
|
|
4630f07282 | ||
|
|
978acecdcf | ||
|
|
bc1f1d92e5 | ||
|
|
415cd6a360 | ||
|
|
68ce340741 | ||
|
|
bdca9fc1ce | ||
|
|
edb684c72c | ||
|
|
17f7afe12d | ||
|
|
0a182a45ba | ||
|
|
95d62e7f57 | ||
|
|
9ecc91929a | ||
|
|
f79c6aef8d | ||
|
|
c0dff6d4a6 | ||
|
|
59cfc087e1 | ||
|
|
e2f6e50df4 | ||
|
|
c2c64e207f | ||
|
|
8645aeaa4a | ||
|
|
7681e32dca | ||
|
|
b7476a9e7f | ||
|
|
48c101aa7a | ||
|
|
378f0d595f | ||
|
|
f12946d581 | ||
|
|
d13e4d2eef | ||
|
|
7b84558ca1 | ||
|
|
92cfde495e | ||
|
|
14578c2257 | ||
|
|
8f6f81948e | ||
|
|
c6109c7087 | ||
|
|
8ea3855e02 | ||
|
|
74fce9640e | ||
|
|
259aa829d4 | ||
|
|
c4ec50d437 | ||
|
|
b50b7b667d | ||
|
|
fbeb2e23d4 | ||
|
|
4b60c03caa | ||
|
|
a56a28fbb7 | ||
|
|
4051d5b803 | ||
|
|
87242ce6cb | ||
|
|
72d9ffd8b4 | ||
|
|
f606711463 | ||
|
|
d1f69feb4a | ||
|
|
484342f26a | ||
|
|
42ada66fdd | ||
|
|
f732ef05d5 | ||
|
|
4fb4fe0931 | ||
|
|
06ffd8ee72 | ||
|
|
90a8070518 | ||
|
|
3e656efb00 | ||
|
|
7c39dd5cba | ||
|
|
21ccfa97dd | ||
|
|
bf0262d7d1 | ||
|
|
42b9700673 | ||
|
|
42bd07d733 | ||
|
|
1930af91ce | ||
|
|
e088d09e47 | ||
|
|
209fa04752 | ||
|
|
f41c02cbd7 | ||
|
|
2e8d6ce7d9 |
@@ -56,6 +56,7 @@ APP_PROXIES=null
|
||||
|
||||
# Database details
|
||||
# Host can contain a port (localhost:3306) or a separate DB_PORT option can be used.
|
||||
# An ipv6 address can be used via the square bracket format ([::1]).
|
||||
DB_HOST=localhost
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=database_database
|
||||
|
||||
1
.github/ISSUE_TEMPLATE/support_request.yml
vendored
1
.github/ISSUE_TEMPLATE/support_request.yml
vendored
@@ -42,6 +42,7 @@ body:
|
||||
label: Log Content
|
||||
description: If the issue has produced an error, provide any [BookStack or server log](https://www.bookstackapp.com/docs/admin/debugging/) content below.
|
||||
placeholder: Be sure to remove any confidential details in your logs
|
||||
render: text
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
|
||||
9
.github/ISSUE_TEMPLATE/z_blank_request.yml
vendored
Normal file
9
.github/ISSUE_TEMPLATE/z_blank_request.yml
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
name: Blank Request (Maintainers Only)
|
||||
description: For maintainers only - Start a blank request
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: "**This blank request option is only for existing official maintainers of the project!** Please instead use a different request option. If you use this your issue will be closed off."
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Description
|
||||
58
.github/translators.txt
vendored
58
.github/translators.txt
vendored
@@ -438,7 +438,7 @@ javadataherian :: Persian
|
||||
Ludo-code :: French
|
||||
hollsten :: Swedish
|
||||
Ngoc Lan Phung (lanpncz) :: Vietnamese
|
||||
Worive :: Catalan
|
||||
Worive :: Catalan; French
|
||||
Илья Скаба (skabailya) :: Russian
|
||||
Irjan Olsen (Irch) :: Norwegian Bokmal
|
||||
Aleksandar Jovanovic (jovanoviczaleksandar) :: Serbian (Cyrillic)
|
||||
@@ -453,3 +453,59 @@ Mohammed srhiri (m.sghiri20) :: Arabic
|
||||
YongMin Kim (kym0118) :: Korean
|
||||
Rivo Zängov (Eraser) :: Estonian
|
||||
Francisco Rafael Fonseca (chicoraf) :: Portuguese, Brazilian
|
||||
ИEØ_ΙΙØZ (NEO_IIOZ) :: Chinese Traditional
|
||||
madnjpn (madnjpn.) :: Georgian
|
||||
Ásgeir Shiny Ásgeirsson (AsgeirShiny) :: Icelandic
|
||||
Mohammad Aftab Uddin (chirohorit) :: Bengali
|
||||
Yannis Karlaftis (meliseus) :: Greek
|
||||
felixxx :: German Informal
|
||||
randi (randi65535) :: Korean
|
||||
test65428 :: Greek
|
||||
zeronell :: Chinese Simplified
|
||||
julien Vinber (julienVinber) :: French
|
||||
Hyunwoo Park (oksure) :: Korean
|
||||
aram.rafeq.7 (aramrafeq2) :: Kurdish
|
||||
Raphael Moreno (RaphaelMoreno) :: Portuguese, Brazilian
|
||||
yn (user99) :: Arabic
|
||||
Pavel Zlatarov (pzlatarov) :: Bulgarian
|
||||
ingelres :: French
|
||||
mabdullah :: Arabic
|
||||
Skrabák Csaba (kekcsi) :: Hungarian
|
||||
Evert Meulie (Evert) :: Norwegian Bokmal
|
||||
Jasper Backer (jasperb) :: Dutch
|
||||
Alexandar Cavdarovski (ace.200112) :: Swedish
|
||||
구닥다리TV (yjj8353) :: Korean
|
||||
Onur Oskay (o.oskay) :: Turkish
|
||||
Sébastien Merveille (SebastienMerv) :: French
|
||||
Maxim Kouznetsov (masya.work) :: Hebrew
|
||||
neodvisnost :: Slovenian
|
||||
Soubi Agatsuma (bisouya) :: Hebrew
|
||||
Ilya Shaulov (ishaulov) :: Russian
|
||||
Konstantin Bobkov (b.konstantv) :: Russian
|
||||
Ruben Sutter (rubensutter) :: German
|
||||
jellium :: French
|
||||
Qxlkdr :: Swedish
|
||||
Hari (muhhari) :: Indonesian
|
||||
仙君御 (xjy) :: Chinese Simplified
|
||||
TapioM :: Finnish
|
||||
lingb58 :: Chinese Traditional
|
||||
Angel Pandey (angel-pandey) :: Nepali
|
||||
Supriya Shrestha (supriyashrestha) :: Nepali
|
||||
gprabhat :: Nepali
|
||||
CellCat :: Chinese Simplified
|
||||
Al Desrahim (aldesrahim) :: Indonesian
|
||||
ahmad abbaspour (deshneh.dar.diss) :: Persian
|
||||
Erjon K. (ekr) :: Albanian
|
||||
LiZerui (iamzrli) :: Chinese Traditional
|
||||
Ticker (ticker.com) :: Hebrew
|
||||
CrazyComputer :: Chinese Simplified
|
||||
Firr (FirrV) :: Russian
|
||||
João Faro (FaroJoaoFaro) :: Portuguese
|
||||
Danilo dos Santos Barbosa (bozochegou) :: Portuguese, Brazilian
|
||||
Chris (furesoft) :: German
|
||||
Silvia Isern (eiendragon) :: Catalan
|
||||
Dennis Kron Pedersen (ahjdp) :: Danish
|
||||
iamwhoiamwhoami :: Swedish
|
||||
Grogui :: French
|
||||
MrCharlesIII :: Arabic
|
||||
David Olsen (dawin) :: Danish
|
||||
|
||||
4
.github/workflows/analyse-php.yml
vendored
4
.github/workflows/analyse-php.yml
vendored
@@ -11,9 +11,9 @@ on:
|
||||
jobs:
|
||||
build:
|
||||
if: ${{ github.ref != 'refs/heads/l10n_development' }}
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
|
||||
6
.github/workflows/lint-php.yml
vendored
6
.github/workflows/lint-php.yml
vendored
@@ -11,14 +11,14 @@ on:
|
||||
jobs:
|
||||
build:
|
||||
if: ${{ github.ref != 'refs/heads/l10n_development' }}
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: 8.1
|
||||
php-version: 8.3
|
||||
tools: phpcs
|
||||
|
||||
- name: Run formatting check
|
||||
|
||||
6
.github/workflows/test-migrations.yml
vendored
6
.github/workflows/test-migrations.yml
vendored
@@ -13,12 +13,12 @@ on:
|
||||
jobs:
|
||||
build:
|
||||
if: ${{ github.ref != 'refs/heads/l10n_development' }}
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
matrix:
|
||||
php: ['8.1', '8.2', '8.3']
|
||||
php: ['8.2', '8.3', '8.4']
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
|
||||
6
.github/workflows/test-php.yml
vendored
6
.github/workflows/test-php.yml
vendored
@@ -13,12 +13,12 @@ on:
|
||||
jobs:
|
||||
build:
|
||||
if: ${{ github.ref != 'refs/heads/l10n_development' }}
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
matrix:
|
||||
php: ['8.1', '8.2', '8.3']
|
||||
php: ['8.2', '8.3', '8.4']
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -32,3 +32,4 @@ webpack-stats.json
|
||||
phpstan.neon
|
||||
esbuild-meta.json
|
||||
.phpactor.json
|
||||
/*.zip
|
||||
|
||||
2
LICENSE
2
LICENSE
@@ -1,6 +1,6 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-2024, Dan Brown and the BookStack Project contributors.
|
||||
Copyright (c) 2015-2025, 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
|
||||
|
||||
@@ -8,27 +8,15 @@ use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ExternalBaseUserProvider implements UserProvider
|
||||
{
|
||||
/**
|
||||
* The user model.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $model;
|
||||
|
||||
/**
|
||||
* LdapUserProvider constructor.
|
||||
*/
|
||||
public function __construct(string $model)
|
||||
{
|
||||
$this->model = $model;
|
||||
public function __construct(
|
||||
protected string $model
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new instance of the model.
|
||||
*
|
||||
* @return Model
|
||||
*/
|
||||
public function createModel()
|
||||
public function createModel(): Model
|
||||
{
|
||||
$class = '\\' . ltrim($this->model, '\\');
|
||||
|
||||
@@ -37,12 +25,8 @@ class ExternalBaseUserProvider implements UserProvider
|
||||
|
||||
/**
|
||||
* Retrieve a user by their unique identifier.
|
||||
*
|
||||
* @param mixed $identifier
|
||||
*
|
||||
* @return Authenticatable|null
|
||||
*/
|
||||
public function retrieveById($identifier)
|
||||
public function retrieveById(mixed $identifier): ?Authenticatable
|
||||
{
|
||||
return $this->createModel()->newQuery()->find($identifier);
|
||||
}
|
||||
@@ -50,12 +34,9 @@ class ExternalBaseUserProvider implements UserProvider
|
||||
/**
|
||||
* Retrieve a user by their unique identifier and "remember me" token.
|
||||
*
|
||||
* @param mixed $identifier
|
||||
* @param string $token
|
||||
*
|
||||
* @return Authenticatable|null
|
||||
*/
|
||||
public function retrieveByToken($identifier, $token)
|
||||
public function retrieveByToken(mixed $identifier, $token): null
|
||||
{
|
||||
return null;
|
||||
}
|
||||
@@ -75,12 +56,8 @@ class ExternalBaseUserProvider implements UserProvider
|
||||
|
||||
/**
|
||||
* Retrieve a user by the given credentials.
|
||||
*
|
||||
* @param array $credentials
|
||||
*
|
||||
* @return Authenticatable|null
|
||||
*/
|
||||
public function retrieveByCredentials(array $credentials)
|
||||
public function retrieveByCredentials(array $credentials): ?Authenticatable
|
||||
{
|
||||
// Search current user base by looking up a uid
|
||||
$model = $this->createModel();
|
||||
@@ -92,15 +69,15 @@ class ExternalBaseUserProvider implements UserProvider
|
||||
|
||||
/**
|
||||
* Validate a user against the given credentials.
|
||||
*
|
||||
* @param Authenticatable $user
|
||||
* @param array $credentials
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function validateCredentials(Authenticatable $user, array $credentials)
|
||||
public function validateCredentials(Authenticatable $user, array $credentials): bool
|
||||
{
|
||||
// Should be done in the guard.
|
||||
return false;
|
||||
}
|
||||
|
||||
public function rehashPasswordIfRequired(Authenticatable $user, #[\SensitiveParameter] array $credentials, bool $force = false)
|
||||
{
|
||||
// No action to perform, any passwords are external in the auth system
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,16 +57,13 @@ class LdapSessionGuard extends ExternalBaseSessionGuard
|
||||
/**
|
||||
* Attempt to authenticate a user using the given credentials.
|
||||
*
|
||||
* @param array $credentials
|
||||
* @param bool $remember
|
||||
*
|
||||
* @throws LdapException*@throws \BookStack\Exceptions\JsonDebugException
|
||||
* @throws LdapException
|
||||
* @throws LoginAttemptException
|
||||
* @throws JsonDebugException
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function attempt(array $credentials = [], $remember = false)
|
||||
public function attempt(array $credentials = [], $remember = false): bool
|
||||
{
|
||||
$username = $credentials['username'];
|
||||
$userDetails = $this->ldapService->getUserDetails($username);
|
||||
|
||||
@@ -54,7 +54,7 @@ class Ldap
|
||||
*
|
||||
* @return \LDAP\Result|array|false
|
||||
*/
|
||||
public function search($ldapConnection, string $baseDn, string $filter, array $attributes = null)
|
||||
public function search($ldapConnection, string $baseDn, string $filter, array $attributes = [])
|
||||
{
|
||||
return ldap_search($ldapConnection, $baseDn, $filter, $attributes);
|
||||
}
|
||||
@@ -66,7 +66,7 @@ class Ldap
|
||||
*
|
||||
* @return \LDAP\Result|array|false
|
||||
*/
|
||||
public function read($ldapConnection, string $baseDn, string $filter, array $attributes = null)
|
||||
public function read($ldapConnection, string $baseDn, string $filter, array $attributes = [])
|
||||
{
|
||||
return ldap_read($ldapConnection, $baseDn, $filter, $attributes);
|
||||
}
|
||||
@@ -87,7 +87,7 @@ class Ldap
|
||||
*
|
||||
* @param resource|\LDAP\Connection $ldapConnection
|
||||
*/
|
||||
public function searchAndGetEntries($ldapConnection, string $baseDn, string $filter, array $attributes = null): array|false
|
||||
public function searchAndGetEntries($ldapConnection, string $baseDn, string $filter, array $attributes = []): array|false
|
||||
{
|
||||
$search = $this->search($ldapConnection, $baseDn, $filter, $attributes);
|
||||
|
||||
@@ -99,7 +99,7 @@ class Ldap
|
||||
*
|
||||
* @param resource|\LDAP\Connection $ldapConnection
|
||||
*/
|
||||
public function bind($ldapConnection, string $bindRdn = null, string $bindPassword = null): bool
|
||||
public function bind($ldapConnection, ?string $bindRdn = null, ?string $bindPassword = null): bool
|
||||
{
|
||||
return ldap_bind($ldapConnection, $bindRdn, $bindPassword);
|
||||
}
|
||||
|
||||
@@ -71,6 +71,26 @@ class LdapService
|
||||
return $users[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the user display name from the (potentially multiple) attributes defined by the configuration.
|
||||
*/
|
||||
protected function getUserDisplayName(array $userDetails, array $displayNameAttrs, string $defaultValue): string
|
||||
{
|
||||
$displayNameParts = [];
|
||||
foreach ($displayNameAttrs as $dnAttr) {
|
||||
$dnComponent = $this->getUserResponseProperty($userDetails, $dnAttr, null);
|
||||
if ($dnComponent) {
|
||||
$displayNameParts[] = $dnComponent;
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($displayNameParts)) {
|
||||
return $defaultValue;
|
||||
}
|
||||
|
||||
return implode(' ', $displayNameParts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the details of a user from LDAP using the given username.
|
||||
* User found via configurable user filter.
|
||||
@@ -81,21 +101,25 @@ class LdapService
|
||||
{
|
||||
$idAttr = $this->config['id_attribute'];
|
||||
$emailAttr = $this->config['email_attribute'];
|
||||
$displayNameAttr = $this->config['display_name_attribute'];
|
||||
$displayNameAttrs = explode('|', $this->config['display_name_attribute']);
|
||||
$thumbnailAttr = $this->config['thumbnail_attribute'];
|
||||
|
||||
$user = $this->getUserWithAttributes($userName, array_filter([
|
||||
'cn', 'dn', $idAttr, $emailAttr, $displayNameAttr, $thumbnailAttr,
|
||||
'cn', 'dn', $idAttr, $emailAttr, ...$displayNameAttrs, $thumbnailAttr,
|
||||
]));
|
||||
|
||||
if (is_null($user)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$userCn = $this->getUserResponseProperty($user, 'cn', null);
|
||||
$nameDefault = $this->getUserResponseProperty($user, 'cn', null);
|
||||
if (is_null($nameDefault)) {
|
||||
$nameDefault = ldap_explode_dn($user['dn'], 1)[0] ?? $user['dn'];
|
||||
}
|
||||
|
||||
$formatted = [
|
||||
'uid' => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
|
||||
'name' => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
|
||||
'name' => $this->getUserDisplayName($user, $displayNameAttrs, $nameDefault),
|
||||
'dn' => $user['dn'],
|
||||
'email' => $this->getUserResponseProperty($user, $emailAttr, null),
|
||||
'avatar' => $thumbnailAttr ? $this->getUserResponseProperty($user, $thumbnailAttr, null) : null,
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace BookStack\Access;
|
||||
use BookStack\Access\Mfa\MfaSession;
|
||||
use BookStack\Activity\ActivityType;
|
||||
use BookStack\Exceptions\LoginAttemptException;
|
||||
use BookStack\Exceptions\LoginAttemptInvalidUserException;
|
||||
use BookStack\Exceptions\StoppedAuthenticationException;
|
||||
use BookStack\Facades\Activity;
|
||||
use BookStack\Facades\Theme;
|
||||
@@ -29,10 +30,14 @@ class LoginService
|
||||
* a reason to (MFA or Unconfirmed Email).
|
||||
* Returns a boolean to indicate the current login result.
|
||||
*
|
||||
* @throws StoppedAuthenticationException
|
||||
* @throws StoppedAuthenticationException|LoginAttemptInvalidUserException
|
||||
*/
|
||||
public function login(User $user, string $method, bool $remember = false): void
|
||||
{
|
||||
if ($user->isGuest()) {
|
||||
throw new LoginAttemptInvalidUserException('Login not allowed for guest user');
|
||||
}
|
||||
|
||||
if ($this->awaitingEmailConfirmation($user) || $this->needsMfaVerification($user)) {
|
||||
$this->setLastLoginAttemptedForUser($user, $method, $remember);
|
||||
|
||||
@@ -58,7 +63,7 @@ class LoginService
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function reattemptLoginFor(User $user)
|
||||
public function reattemptLoginFor(User $user): void
|
||||
{
|
||||
if ($user->id !== ($this->getLastLoginAttemptUser()->id ?? null)) {
|
||||
throw new Exception('Login reattempt user does align with current session state');
|
||||
@@ -152,16 +157,40 @@ class LoginService
|
||||
*/
|
||||
public function attempt(array $credentials, string $method, bool $remember = false): bool
|
||||
{
|
||||
if ($this->areCredentialsForGuest($credentials)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$result = auth()->attempt($credentials, $remember);
|
||||
if ($result) {
|
||||
$user = auth()->user();
|
||||
auth()->logout();
|
||||
$this->login($user, $method, $remember);
|
||||
try {
|
||||
$this->login($user, $method, $remember);
|
||||
} catch (LoginAttemptInvalidUserException $e) {
|
||||
// Catch and return false for non-login accounts
|
||||
// so it looks like a normal invalid login.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given credentials are likely for the system guest account.
|
||||
*/
|
||||
protected function areCredentialsForGuest(array $credentials): bool
|
||||
{
|
||||
if (isset($credentials['email'])) {
|
||||
return User::query()->where('email', '=', $credentials['email'])
|
||||
->where('system_name', '=', 'public')
|
||||
->exists();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs the current user out of the application.
|
||||
* Returns an app post-redirect path.
|
||||
|
||||
@@ -11,6 +11,7 @@ use BookStack\Exceptions\UserRegistrationException;
|
||||
use BookStack\Facades\Theme;
|
||||
use BookStack\Http\HttpRequestService;
|
||||
use BookStack\Theming\ThemeEvents;
|
||||
use BookStack\Uploads\UserAvatars;
|
||||
use BookStack\Users\Models\User;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
|
||||
@@ -26,7 +27,8 @@ class OidcService
|
||||
protected RegistrationService $registrationService,
|
||||
protected LoginService $loginService,
|
||||
protected HttpRequestService $http,
|
||||
protected GroupSyncService $groupService
|
||||
protected GroupSyncService $groupService,
|
||||
protected UserAvatars $userAvatars
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -220,6 +222,10 @@ class OidcService
|
||||
throw new OidcException($exception->getMessage());
|
||||
}
|
||||
|
||||
if ($this->config()['fetch_avatar'] && !$user->avatar()->exists() && $userDetails->picture) {
|
||||
$this->userAvatars->assignToUserFromUrl($user, $userDetails->picture);
|
||||
}
|
||||
|
||||
if ($this->shouldSyncGroups()) {
|
||||
$detachExisting = $this->config()['remove_from_groups'];
|
||||
$this->groupService->syncUserWithFoundGroups($user, $userDetails->groups ?? [], $detachExisting);
|
||||
|
||||
@@ -11,6 +11,7 @@ class OidcUserDetails
|
||||
public ?string $email = null,
|
||||
public ?string $name = null,
|
||||
public ?array $groups = null,
|
||||
public ?string $picture = null,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -40,15 +41,16 @@ class OidcUserDetails
|
||||
$this->email = $claims->getClaim('email') ?? $this->email;
|
||||
$this->name = static::getUserDisplayName($displayNameClaims, $claims) ?? $this->name;
|
||||
$this->groups = static::getUserGroups($groupsClaim, $claims) ?? $this->groups;
|
||||
$this->picture = static::getPicture($claims) ?: $this->picture;
|
||||
}
|
||||
|
||||
protected static function getUserDisplayName(string $displayNameClaims, ProvidesClaims $token): string
|
||||
protected static function getUserDisplayName(string $displayNameClaims, ProvidesClaims $claims): string
|
||||
{
|
||||
$displayNameClaimParts = explode('|', $displayNameClaims);
|
||||
|
||||
$displayName = [];
|
||||
foreach ($displayNameClaimParts as $claim) {
|
||||
$component = $token->getClaim(trim($claim)) ?? '';
|
||||
$component = $claims->getClaim(trim($claim)) ?? '';
|
||||
if ($component !== '') {
|
||||
$displayName[] = $component;
|
||||
}
|
||||
@@ -57,13 +59,13 @@ class OidcUserDetails
|
||||
return implode(' ', $displayName);
|
||||
}
|
||||
|
||||
protected static function getUserGroups(string $groupsClaim, ProvidesClaims $token): ?array
|
||||
protected static function getUserGroups(string $groupsClaim, ProvidesClaims $claims): ?array
|
||||
{
|
||||
if (empty($groupsClaim)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$groupsList = Arr::get($token->getAllClaims(), $groupsClaim);
|
||||
$groupsList = Arr::get($claims->getAllClaims(), $groupsClaim);
|
||||
if (!is_array($groupsList)) {
|
||||
return null;
|
||||
}
|
||||
@@ -72,4 +74,14 @@ class OidcUserDetails
|
||||
return is_string($val);
|
||||
}));
|
||||
}
|
||||
|
||||
protected static function getPicture(ProvidesClaims $claims): ?string
|
||||
{
|
||||
$picture = $claims->getClaim('picture');
|
||||
if (is_string($picture) && str_starts_with($picture, 'http')) {
|
||||
return $picture;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ class OidcUserinfoResponse implements ProvidesClaims
|
||||
|
||||
public function __construct(ResponseInterface $response, string $issuer, array $keys)
|
||||
{
|
||||
$contentType = $response->getHeader('Content-Type')[0];
|
||||
$contentTypeHeaderValue = $response->getHeader('Content-Type')[0] ?? '';
|
||||
$contentType = strtolower(trim(explode(';', $contentTypeHeaderValue, 2)[0]));
|
||||
|
||||
if ($contentType === 'application/json') {
|
||||
$this->claims = json_decode($response->getBody()->getContents(), true);
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ class SocialDriverManager
|
||||
string $driverName,
|
||||
array $config,
|
||||
string $socialiteHandler,
|
||||
callable $configureForRedirect = null
|
||||
?callable $configureForRedirect = null
|
||||
) {
|
||||
$this->validDrivers[] = $driverName;
|
||||
config()->set('services.' . $driverName, $config);
|
||||
|
||||
@@ -11,6 +11,7 @@ use BookStack\Entities\Tools\MixedEntityListLoader;
|
||||
use BookStack\Permissions\PermissionApplicator;
|
||||
use BookStack\Users\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphTo;
|
||||
use Illuminate\Database\Eloquent\Relations\Relation;
|
||||
|
||||
class ActivityQueries
|
||||
@@ -67,6 +68,7 @@ class ActivityQueries
|
||||
|
||||
$activity = $query->orderBy('created_at', 'desc')
|
||||
->with(['loggable' => function (Relation $query) {
|
||||
/** @var MorphTo<Entity, Activity> $query */
|
||||
$query->withTrashed();
|
||||
}, 'user.avatar'])
|
||||
->skip($count * ($page - 1))
|
||||
|
||||
@@ -67,6 +67,14 @@ class ActivityType
|
||||
const WEBHOOK_UPDATE = 'webhook_update';
|
||||
const WEBHOOK_DELETE = 'webhook_delete';
|
||||
|
||||
const IMPORT_CREATE = 'import_create';
|
||||
const IMPORT_RUN = 'import_run';
|
||||
const IMPORT_DELETE = 'import_delete';
|
||||
|
||||
const SORT_RULE_CREATE = 'sort_rule_create';
|
||||
const SORT_RULE_UPDATE = 'sort_rule_update';
|
||||
const SORT_RULE_DELETE = 'sort_rule_delete';
|
||||
|
||||
/**
|
||||
* Get all the possible values.
|
||||
*/
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace BookStack\Activity;
|
||||
|
||||
use BookStack\Activity\Models\Comment;
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Exceptions\NotifyException;
|
||||
use BookStack\Exceptions\PrettyException;
|
||||
use BookStack\Facades\Activity as ActivityService;
|
||||
use BookStack\Util\HtmlDescriptionFilter;
|
||||
|
||||
@@ -20,7 +22,7 @@ class CommentRepo
|
||||
/**
|
||||
* Create a new comment on an entity.
|
||||
*/
|
||||
public function create(Entity $entity, string $html, ?int $parent_id): Comment
|
||||
public function create(Entity $entity, string $html, ?int $parentId, string $contentRef): Comment
|
||||
{
|
||||
$userId = user()->id;
|
||||
$comment = new Comment();
|
||||
@@ -29,7 +31,8 @@ class CommentRepo
|
||||
$comment->created_by = $userId;
|
||||
$comment->updated_by = $userId;
|
||||
$comment->local_id = $this->getNextLocalId($entity);
|
||||
$comment->parent_id = $parent_id;
|
||||
$comment->parent_id = $parentId;
|
||||
$comment->content_ref = preg_match('/^bkmrk-(.*?):\d+:(\d*-\d*)?$/', $contentRef) === 1 ? $contentRef : '';
|
||||
|
||||
$entity->comments()->save($comment);
|
||||
ActivityService::add(ActivityType::COMMENT_CREATE, $comment);
|
||||
@@ -52,6 +55,41 @@ class CommentRepo
|
||||
return $comment;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Archive an existing comment.
|
||||
*/
|
||||
public function archive(Comment $comment): Comment
|
||||
{
|
||||
if ($comment->parent_id) {
|
||||
throw new NotifyException('Only top-level comments can be archived.', '/', 400);
|
||||
}
|
||||
|
||||
$comment->archived = true;
|
||||
$comment->save();
|
||||
|
||||
ActivityService::add(ActivityType::COMMENT_UPDATE, $comment);
|
||||
|
||||
return $comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Un-archive an existing comment.
|
||||
*/
|
||||
public function unarchive(Comment $comment): Comment
|
||||
{
|
||||
if ($comment->parent_id) {
|
||||
throw new NotifyException('Only top-level comments can be un-archived.', '/', 400);
|
||||
}
|
||||
|
||||
$comment->archived = false;
|
||||
$comment->save();
|
||||
|
||||
ActivityService::add(ActivityType::COMMENT_UPDATE, $comment);
|
||||
|
||||
return $comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a comment from the system.
|
||||
*/
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace BookStack\Activity\Controllers;
|
||||
use BookStack\Activity\ActivityType;
|
||||
use BookStack\Activity\Models\Activity;
|
||||
use BookStack\Http\Controller;
|
||||
use BookStack\Sorting\SortUrl;
|
||||
use BookStack\Util\SimpleListOptions;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
@@ -65,6 +66,7 @@ class AuditLogController extends Controller
|
||||
'filters' => $filters,
|
||||
'listOptions' => $listOptions,
|
||||
'activityTypes' => $types,
|
||||
'filterSortUrl' => new SortUrl('settings/audit', array_filter($request->except('page')))
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace BookStack\Activity\Controllers;
|
||||
|
||||
use BookStack\Activity\CommentRepo;
|
||||
use BookStack\Activity\Tools\CommentTree;
|
||||
use BookStack\Activity\Tools\CommentTreeNode;
|
||||
use BookStack\Entities\Queries\PageQueries;
|
||||
use BookStack\Http\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -26,6 +28,7 @@ class CommentController extends Controller
|
||||
$input = $this->validate($request, [
|
||||
'html' => ['required', 'string'],
|
||||
'parent_id' => ['nullable', 'integer'],
|
||||
'content_ref' => ['string'],
|
||||
]);
|
||||
|
||||
$page = $this->pageQueries->findVisibleById($pageId);
|
||||
@@ -40,14 +43,12 @@ class CommentController extends Controller
|
||||
|
||||
// Create a new comment.
|
||||
$this->checkPermission('comment-create-all');
|
||||
$comment = $this->commentRepo->create($page, $input['html'], $input['parent_id'] ?? null);
|
||||
$contentRef = $input['content_ref'] ?? '';
|
||||
$comment = $this->commentRepo->create($page, $input['html'], $input['parent_id'] ?? null, $contentRef);
|
||||
|
||||
return view('comments.comment-branch', [
|
||||
'readOnly' => false,
|
||||
'branch' => [
|
||||
'comment' => $comment,
|
||||
'children' => [],
|
||||
]
|
||||
'branch' => new CommentTreeNode($comment, 0, []),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -74,6 +75,46 @@ class CommentController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a comment as archived.
|
||||
*/
|
||||
public function archive(int $id)
|
||||
{
|
||||
$comment = $this->commentRepo->getById($id);
|
||||
$this->checkOwnablePermission('page-view', $comment->entity);
|
||||
if (!userCan('comment-update', $comment) && !userCan('comment-delete', $comment)) {
|
||||
$this->showPermissionError();
|
||||
}
|
||||
|
||||
$this->commentRepo->archive($comment);
|
||||
|
||||
$tree = new CommentTree($comment->entity);
|
||||
return view('comments.comment-branch', [
|
||||
'readOnly' => false,
|
||||
'branch' => $tree->getCommentNodeForId($id),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unmark a comment as archived.
|
||||
*/
|
||||
public function unarchive(int $id)
|
||||
{
|
||||
$comment = $this->commentRepo->getById($id);
|
||||
$this->checkOwnablePermission('page-view', $comment->entity);
|
||||
if (!userCan('comment-update', $comment) && !userCan('comment-delete', $comment)) {
|
||||
$this->showPermissionError();
|
||||
}
|
||||
|
||||
$this->commentRepo->unarchive($comment);
|
||||
|
||||
$tree = new CommentTree($comment->entity);
|
||||
return view('comments.comment-branch', [
|
||||
'readOnly' => false,
|
||||
'branch' => $tree->getCommentNodeForId($id),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a comment from the system.
|
||||
*/
|
||||
|
||||
@@ -19,6 +19,8 @@ use Illuminate\Database\Eloquent\Relations\MorphTo;
|
||||
* @property int $entity_id
|
||||
* @property int $created_by
|
||||
* @property int $updated_by
|
||||
* @property string $content_ref
|
||||
* @property bool $archived
|
||||
*/
|
||||
class Comment extends Model implements Loggable
|
||||
{
|
||||
@@ -26,7 +28,6 @@ class Comment extends Model implements Loggable
|
||||
use HasCreatorAndUpdater;
|
||||
|
||||
protected $fillable = ['parent_id'];
|
||||
protected $appends = ['created', 'updated'];
|
||||
|
||||
/**
|
||||
* Get the entity that this comment belongs to.
|
||||
@@ -54,22 +55,6 @@ class Comment extends Model implements Loggable
|
||||
return $this->updated_at->timestamp > $this->created_at->timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get created date as a relative diff.
|
||||
*/
|
||||
public function getCreatedAttribute(): string
|
||||
{
|
||||
return $this->created_at->diffForHumans();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get updated date as a relative diff.
|
||||
*/
|
||||
public function getUpdatedAttribute(): string
|
||||
{
|
||||
return $this->updated_at->diffForHumans();
|
||||
}
|
||||
|
||||
public function logDescriptor(): string
|
||||
{
|
||||
return "Comment #{$this->local_id} (ID: {$this->id}) for {$this->entity_type} (ID: {$this->entity_id})";
|
||||
|
||||
@@ -12,6 +12,8 @@ use Illuminate\Database\Eloquent\Relations\MorphTo;
|
||||
* @property int $id
|
||||
* @property string $name
|
||||
* @property string $value
|
||||
* @property int $entity_id
|
||||
* @property string $entity_type
|
||||
* @property int $order
|
||||
*/
|
||||
class Tag extends Model
|
||||
|
||||
@@ -7,6 +7,7 @@ use BookStack\Activity\Notifications\Messages\BaseActivityNotification;
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Permissions\PermissionApplicator;
|
||||
use BookStack\Users\Models\User;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
abstract class BaseNotificationHandler implements NotificationHandler
|
||||
{
|
||||
@@ -36,7 +37,11 @@ abstract class BaseNotificationHandler implements NotificationHandler
|
||||
}
|
||||
|
||||
// Send the notification
|
||||
$user->notify(new $notification($detail, $initiator));
|
||||
try {
|
||||
$user->notify(new $notification($detail, $initiator));
|
||||
} catch (\Exception $exception) {
|
||||
Log::error("Failed to send email notification to user [id:{$user->id}] with error: {$exception->getMessage()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,8 @@ class PageUpdateNotificationHandler extends BaseNotificationHandler
|
||||
throw new \InvalidArgumentException("Detail for page update notifications must be a page");
|
||||
}
|
||||
|
||||
// Get last update from activity
|
||||
// Get the last update from activity
|
||||
/** @var ?Activity $lastUpdate */
|
||||
$lastUpdate = $detail->activity()
|
||||
->where('type', '=', ActivityType::PAGE_UPDATE)
|
||||
->where('id', '!=', $activity->id)
|
||||
|
||||
@@ -9,7 +9,7 @@ class CommentTree
|
||||
{
|
||||
/**
|
||||
* The built nested tree structure array.
|
||||
* @var array{comment: Comment, depth: int, children: array}[]
|
||||
* @var CommentTreeNode[]
|
||||
*/
|
||||
protected array $tree;
|
||||
protected array $comments;
|
||||
@@ -28,7 +28,7 @@ class CommentTree
|
||||
|
||||
public function empty(): bool
|
||||
{
|
||||
return count($this->tree) === 0;
|
||||
return count($this->getActive()) === 0;
|
||||
}
|
||||
|
||||
public function count(): int
|
||||
@@ -36,9 +36,35 @@ class CommentTree
|
||||
return count($this->comments);
|
||||
}
|
||||
|
||||
public function get(): array
|
||||
public function getActive(): array
|
||||
{
|
||||
return $this->tree;
|
||||
return array_filter($this->tree, fn (CommentTreeNode $node) => !$node->comment->archived);
|
||||
}
|
||||
|
||||
public function activeThreadCount(): int
|
||||
{
|
||||
return count($this->getActive());
|
||||
}
|
||||
|
||||
public function getArchived(): array
|
||||
{
|
||||
return array_filter($this->tree, fn (CommentTreeNode $node) => $node->comment->archived);
|
||||
}
|
||||
|
||||
public function archivedThreadCount(): int
|
||||
{
|
||||
return count($this->getArchived());
|
||||
}
|
||||
|
||||
public function getCommentNodeForId(int $commentId): ?CommentTreeNode
|
||||
{
|
||||
foreach ($this->tree as $node) {
|
||||
if ($node->comment->id === $commentId) {
|
||||
return $node;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function canUpdateAny(): bool
|
||||
@@ -54,6 +80,7 @@ class CommentTree
|
||||
|
||||
/**
|
||||
* @param Comment[] $comments
|
||||
* @return CommentTreeNode[]
|
||||
*/
|
||||
protected function createTree(array $comments): array
|
||||
{
|
||||
@@ -77,26 +104,22 @@ class CommentTree
|
||||
|
||||
$tree = [];
|
||||
foreach ($childMap[0] ?? [] as $childId) {
|
||||
$tree[] = $this->createTreeForId($childId, 0, $byId, $childMap);
|
||||
$tree[] = $this->createTreeNodeForId($childId, 0, $byId, $childMap);
|
||||
}
|
||||
|
||||
return $tree;
|
||||
}
|
||||
|
||||
protected function createTreeForId(int $id, int $depth, array &$byId, array &$childMap): array
|
||||
protected function createTreeNodeForId(int $id, int $depth, array &$byId, array &$childMap): CommentTreeNode
|
||||
{
|
||||
$childIds = $childMap[$id] ?? [];
|
||||
$children = [];
|
||||
|
||||
foreach ($childIds as $childId) {
|
||||
$children[] = $this->createTreeForId($childId, $depth + 1, $byId, $childMap);
|
||||
$children[] = $this->createTreeNodeForId($childId, $depth + 1, $byId, $childMap);
|
||||
}
|
||||
|
||||
return [
|
||||
'comment' => $byId[$id],
|
||||
'depth' => $depth,
|
||||
'children' => $children,
|
||||
];
|
||||
return new CommentTreeNode($byId[$id], $depth, $children);
|
||||
}
|
||||
|
||||
protected function loadComments(): array
|
||||
|
||||
23
app/Activity/Tools/CommentTreeNode.php
Normal file
23
app/Activity/Tools/CommentTreeNode.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Activity\Tools;
|
||||
|
||||
use BookStack\Activity\Models\Comment;
|
||||
|
||||
class CommentTreeNode
|
||||
{
|
||||
public Comment $comment;
|
||||
public int $depth;
|
||||
|
||||
/**
|
||||
* @var CommentTreeNode[]
|
||||
*/
|
||||
public array $children;
|
||||
|
||||
public function __construct(Comment $comment, int $depth, array $children)
|
||||
{
|
||||
$this->comment = $comment;
|
||||
$this->depth = $depth;
|
||||
$this->children = $children;
|
||||
}
|
||||
}
|
||||
@@ -3,17 +3,15 @@
|
||||
namespace BookStack\Activity\Tools;
|
||||
|
||||
use BookStack\Activity\Models\Tag;
|
||||
use BookStack\Entities\Models\BookChild;
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Entities\Models\Page;
|
||||
|
||||
class TagClassGenerator
|
||||
{
|
||||
protected array $tags;
|
||||
|
||||
/**
|
||||
* @param Tag[] $tags
|
||||
*/
|
||||
public function __construct(array $tags)
|
||||
{
|
||||
$this->tags = $tags;
|
||||
public function __construct(
|
||||
protected Entity $entity
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -22,14 +20,23 @@ class TagClassGenerator
|
||||
public function generate(): array
|
||||
{
|
||||
$classes = [];
|
||||
$tags = $this->entity->tags->all();
|
||||
|
||||
foreach ($this->tags as $tag) {
|
||||
$name = $this->normalizeTagClassString($tag->name);
|
||||
$value = $this->normalizeTagClassString($tag->value);
|
||||
$classes[] = 'tag-name-' . $name;
|
||||
if ($value) {
|
||||
$classes[] = 'tag-value-' . $value;
|
||||
$classes[] = 'tag-pair-' . $name . '-' . $value;
|
||||
foreach ($tags as $tag) {
|
||||
array_push($classes, ...$this->generateClassesForTag($tag));
|
||||
}
|
||||
|
||||
if ($this->entity instanceof BookChild && userCan('view', $this->entity->book)) {
|
||||
$bookTags = $this->entity->book->tags;
|
||||
foreach ($bookTags as $bookTag) {
|
||||
array_push($classes, ...$this->generateClassesForTag($bookTag, 'book-'));
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->entity instanceof Page && $this->entity->chapter && userCan('view', $this->entity->chapter)) {
|
||||
$chapterTags = $this->entity->chapter->tags;
|
||||
foreach ($chapterTags as $chapterTag) {
|
||||
array_push($classes, ...$this->generateClassesForTag($chapterTag, 'chapter-'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +48,22 @@ class TagClassGenerator
|
||||
return implode(' ', $this->generate());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
protected function generateClassesForTag(Tag $tag, string $prefix = ''): array
|
||||
{
|
||||
$classes = [];
|
||||
$name = $this->normalizeTagClassString($tag->name);
|
||||
$value = $this->normalizeTagClassString($tag->value);
|
||||
$classes[] = "{$prefix}tag-name-{$name}";
|
||||
if ($value) {
|
||||
$classes[] = "{$prefix}tag-value-{$value}";
|
||||
$classes[] = "{$prefix}tag-pair-{$name}-{$value}";
|
||||
}
|
||||
return $classes;
|
||||
}
|
||||
|
||||
protected function normalizeTagClassString(string $value): string
|
||||
{
|
||||
$value = str_replace(' ', '', strtolower($value));
|
||||
|
||||
@@ -50,7 +50,7 @@ class WebhookFormatter
|
||||
}
|
||||
|
||||
if ($this->detail instanceof Model) {
|
||||
$data['related_item'] = $this->formatModel();
|
||||
$data['related_item'] = $this->formatModel($this->detail);
|
||||
}
|
||||
|
||||
return $data;
|
||||
@@ -83,10 +83,8 @@ class WebhookFormatter
|
||||
);
|
||||
}
|
||||
|
||||
protected function formatModel(): array
|
||||
protected function formatModel(Model $model): array
|
||||
{
|
||||
/** @var Model $model */
|
||||
$model = $this->detail;
|
||||
$model->unsetRelations();
|
||||
|
||||
foreach ($this->modelFormatters as $formatter) {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace BookStack\Api;
|
||||
|
||||
use BookStack\App\AppVersion;
|
||||
use BookStack\Http\ApiController;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Container\BindingResolutionException;
|
||||
@@ -25,7 +26,7 @@ class ApiDocsGenerator
|
||||
*/
|
||||
public static function generateConsideringCache(): Collection
|
||||
{
|
||||
$appVersion = trim(file_get_contents(base_path('version')));
|
||||
$appVersion = AppVersion::get();
|
||||
$cacheKey = 'api-docs::' . $appVersion;
|
||||
$isProduction = config('app.env') === 'production';
|
||||
$cacheVal = $isProduction ? Cache::get($cacheKey) : null;
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
namespace BookStack\Api;
|
||||
|
||||
use BookStack\Entities\Models\BookChild;
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Entities\Models\Page;
|
||||
|
||||
class ApiEntityListFormatter
|
||||
{
|
||||
@@ -20,8 +22,16 @@ class ApiEntityListFormatter
|
||||
* @var array<string|int, string|callable>
|
||||
*/
|
||||
protected array $fields = [
|
||||
'id', 'name', 'slug', 'book_id', 'chapter_id', 'draft',
|
||||
'template', 'priority', 'created_at', 'updated_at',
|
||||
'id',
|
||||
'name',
|
||||
'slug',
|
||||
'book_id',
|
||||
'chapter_id',
|
||||
'draft',
|
||||
'template',
|
||||
'priority',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
];
|
||||
|
||||
public function __construct(array $list)
|
||||
@@ -62,6 +72,28 @@ class ApiEntityListFormatter
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Include parent book/chapter info in the formatted data.
|
||||
*/
|
||||
public function withParents(): self
|
||||
{
|
||||
$this->withField('book', function (Entity $entity) {
|
||||
if ($entity instanceof BookChild && $entity->book) {
|
||||
return $entity->book->only(['id', 'name', 'slug']);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
$this->withField('chapter', function (Entity $entity) {
|
||||
if ($entity instanceof Page && $entity->chapter) {
|
||||
return $entity->chapter->only(['id', 'name', 'slug']);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the data and return an array of formatted content.
|
||||
* @return array[]
|
||||
|
||||
24
app/App/AppVersion.php
Normal file
24
app/App/AppVersion.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\App;
|
||||
|
||||
class AppVersion
|
||||
{
|
||||
protected static string $version = '';
|
||||
|
||||
/**
|
||||
* Get the application's version number from its top-level `version` text file.
|
||||
*/
|
||||
public static function get(): string
|
||||
{
|
||||
if (!empty(static::$version)) {
|
||||
return static::$version;
|
||||
}
|
||||
|
||||
$versionFile = base_path('version');
|
||||
$version = trim(file_get_contents($versionFile));
|
||||
static::$version = $version;
|
||||
|
||||
return $version;
|
||||
}
|
||||
}
|
||||
@@ -42,4 +42,12 @@ class EventServiceProvider extends ServiceProvider
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides the registration of Laravel's default email verification system
|
||||
*/
|
||||
protected function configureEmailVerification(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,5 +85,12 @@ class RouteServiceProvider extends ServiceProvider
|
||||
RateLimiter::for('public', function (Request $request) {
|
||||
return Limit::perMinute(10)->by($request->ip());
|
||||
});
|
||||
|
||||
RateLimiter::for('exports', function (Request $request) {
|
||||
$user = user();
|
||||
$attempts = $user->isGuest() ? 4 : 10;
|
||||
$key = $user->isGuest() ? $request->ip() : $user->id;
|
||||
return Limit::perMinute($attempts)->by($key);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
31
app/App/SystemApiController.php
Normal file
31
app/App/SystemApiController.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\App;
|
||||
|
||||
use BookStack\Http\ApiController;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class SystemApiController extends ApiController
|
||||
{
|
||||
/**
|
||||
* Read details regarding the BookStack instance.
|
||||
* Some details may be null where not set, like the app logo for example.
|
||||
*/
|
||||
public function read(): JsonResponse
|
||||
{
|
||||
$logoSetting = setting('app-logo', '');
|
||||
if ($logoSetting === 'none') {
|
||||
$logo = null;
|
||||
} else {
|
||||
$logo = $logoSetting ? url($logoSetting) : url('/logo.png');
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'version' => AppVersion::get(),
|
||||
'instance_id' => setting('instance-id'),
|
||||
'app_name' => setting('app-name'),
|
||||
'app_logo' => $logo,
|
||||
'base_url' => url('/'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
<?php
|
||||
|
||||
use BookStack\App\AppVersion;
|
||||
use BookStack\App\Model;
|
||||
use BookStack\Facades\Theme;
|
||||
use BookStack\Permissions\PermissionApplicator;
|
||||
use BookStack\Settings\SettingService;
|
||||
use BookStack\Users\Models\User;
|
||||
@@ -12,12 +14,7 @@ use BookStack\Users\Models\User;
|
||||
*/
|
||||
function versioned_asset(string $file = ''): string
|
||||
{
|
||||
static $version = null;
|
||||
|
||||
if (is_null($version)) {
|
||||
$versionFile = base_path('version');
|
||||
$version = trim(file_get_contents($versionFile));
|
||||
}
|
||||
$version = AppVersion::get();
|
||||
|
||||
$additional = '';
|
||||
if (config('app.env') === 'development') {
|
||||
@@ -42,9 +39,9 @@ function user(): User
|
||||
* Check if the current user has a permission. If an ownable element
|
||||
* is passed in the jointPermissions are checked against that particular item.
|
||||
*/
|
||||
function userCan(string $permission, Model $ownable = null): bool
|
||||
function userCan(string $permission, ?Model $ownable = null): bool
|
||||
{
|
||||
if ($ownable === null) {
|
||||
if (is_null($ownable)) {
|
||||
return user()->can($permission);
|
||||
}
|
||||
|
||||
@@ -70,7 +67,7 @@ function userCanOnAny(string $action, string $entityClass = ''): bool
|
||||
*
|
||||
* @return mixed|SettingService
|
||||
*/
|
||||
function setting(string $key = null, $default = null)
|
||||
function setting(?string $key = null, mixed $default = null): mixed
|
||||
{
|
||||
$settingService = app()->make(SettingService::class);
|
||||
|
||||
@@ -88,43 +85,10 @@ function setting(string $key = null, $default = null)
|
||||
*/
|
||||
function theme_path(string $path = ''): ?string
|
||||
{
|
||||
$theme = config('view.theme');
|
||||
|
||||
$theme = Theme::getTheme();
|
||||
if (!$theme) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return base_path('themes/' . $theme . ($path ? DIRECTORY_SEPARATOR . $path : $path));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a URL with multiple parameters for sorting purposes.
|
||||
* Works out the logic to set the correct sorting direction
|
||||
* Discards empty parameters and allows overriding.
|
||||
*/
|
||||
function sortUrl(string $path, array $data, array $overrideData = []): string
|
||||
{
|
||||
$queryStringSections = [];
|
||||
$queryData = array_merge($data, $overrideData);
|
||||
|
||||
// Change sorting direction is already sorted on current attribute
|
||||
if (isset($overrideData['sort']) && $overrideData['sort'] === $data['sort']) {
|
||||
$queryData['order'] = ($data['order'] === 'asc') ? 'desc' : 'asc';
|
||||
} elseif (isset($overrideData['sort'])) {
|
||||
$queryData['order'] = 'asc';
|
||||
}
|
||||
|
||||
foreach ($queryData as $name => $value) {
|
||||
$trimmedVal = trim($value);
|
||||
if ($trimmedVal === '') {
|
||||
continue;
|
||||
}
|
||||
$queryStringSections[] = urlencode($name) . '=' . urlencode($trimmedVal);
|
||||
}
|
||||
|
||||
if (count($queryStringSections) === 0) {
|
||||
return url($path);
|
||||
}
|
||||
|
||||
return url($path . '?' . implode('&', $queryStringSections));
|
||||
}
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Broadcasting configuration options.
|
||||
*
|
||||
* Changes to these config files are not supported by BookStack and may break upon updates.
|
||||
* Configuration should be altered via the `.env` file or environment variables.
|
||||
* Do not edit this file unless you're happy to maintain any changes yourself.
|
||||
*/
|
||||
|
||||
return [
|
||||
|
||||
// Default Broadcaster
|
||||
// This option controls the default broadcaster that will be used by the
|
||||
// framework when an event needs to be broadcast. This can be set to
|
||||
// any of the connections defined in the "connections" array below.
|
||||
'default' => 'null',
|
||||
|
||||
// Broadcast Connections
|
||||
// Here you may define all of the broadcast connections that will be used
|
||||
// to broadcast events to other systems or over websockets. Samples of
|
||||
// each available type of connection are provided inside this array.
|
||||
'connections' => [
|
||||
|
||||
// Default options removed since we don't use broadcasting.
|
||||
|
||||
'log' => [
|
||||
'driver' => 'log',
|
||||
],
|
||||
|
||||
'null' => [
|
||||
'driver' => 'null',
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
];
|
||||
@@ -35,10 +35,6 @@ return [
|
||||
// Available caches stores
|
||||
'stores' => [
|
||||
|
||||
'apc' => [
|
||||
'driver' => 'apc',
|
||||
],
|
||||
|
||||
'array' => [
|
||||
'driver' => 'array',
|
||||
'serialize' => false,
|
||||
@@ -49,6 +45,7 @@ return [
|
||||
'table' => 'cache',
|
||||
'connection' => null,
|
||||
'lock_connection' => null,
|
||||
'lock_table' => null,
|
||||
],
|
||||
|
||||
'file' => [
|
||||
|
||||
@@ -40,12 +40,16 @@ if (env('REDIS_SERVERS', false)) {
|
||||
|
||||
// MYSQL
|
||||
// Split out port from host if set
|
||||
$mysql_host = env('DB_HOST', 'localhost');
|
||||
$mysql_host_exploded = explode(':', $mysql_host);
|
||||
$mysql_port = env('DB_PORT', 3306);
|
||||
if (count($mysql_host_exploded) > 1) {
|
||||
$mysql_host = $mysql_host_exploded[0];
|
||||
$mysql_port = intval($mysql_host_exploded[1]);
|
||||
$mysqlHost = env('DB_HOST', 'localhost');
|
||||
$mysqlHostExploded = explode(':', $mysqlHost);
|
||||
$mysqlPort = env('DB_PORT', 3306);
|
||||
$mysqlHostIpv6 = str_starts_with($mysqlHost, '[');
|
||||
if ($mysqlHostIpv6 && str_contains($mysqlHost, ']:')) {
|
||||
$mysqlHost = implode(':', array_slice($mysqlHostExploded, 0, -1));
|
||||
$mysqlPort = intval(end($mysqlHostExploded));
|
||||
} else if (!$mysqlHostIpv6 && count($mysqlHostExploded) > 1) {
|
||||
$mysqlHost = $mysqlHostExploded[0];
|
||||
$mysqlPort = intval($mysqlHostExploded[1]);
|
||||
}
|
||||
|
||||
return [
|
||||
@@ -61,12 +65,12 @@ return [
|
||||
'mysql' => [
|
||||
'driver' => 'mysql',
|
||||
'url' => env('DATABASE_URL'),
|
||||
'host' => $mysql_host,
|
||||
'host' => $mysqlHost,
|
||||
'database' => env('DB_DATABASE', 'forge'),
|
||||
'username' => env('DB_USERNAME', 'forge'),
|
||||
'password' => env('DB_PASSWORD', ''),
|
||||
'unix_socket' => env('DB_SOCKET', ''),
|
||||
'port' => $mysql_port,
|
||||
'port' => $mysqlPort,
|
||||
'charset' => 'utf8mb4',
|
||||
'collation' => 'utf8mb4_unicode_ci',
|
||||
// Prefixes are only semi-supported and may be unstable
|
||||
@@ -88,7 +92,7 @@ return [
|
||||
'database' => 'bookstack-test',
|
||||
'username' => env('MYSQL_USER', 'bookstack-test'),
|
||||
'password' => env('MYSQL_PASSWORD', 'bookstack-test'),
|
||||
'port' => $mysql_port,
|
||||
'port' => $mysqlPort,
|
||||
'charset' => 'utf8mb4',
|
||||
'collation' => 'utf8mb4_unicode_ci',
|
||||
'prefix' => '',
|
||||
|
||||
@@ -114,6 +114,7 @@ return [
|
||||
* @var array
|
||||
*/
|
||||
'allowed_protocols' => [
|
||||
"data://" => ["rules" => []],
|
||||
'file://' => ['rules' => []],
|
||||
'http://' => ['rules' => []],
|
||||
'https://' => ['rules' => []],
|
||||
|
||||
@@ -32,20 +32,22 @@ return [
|
||||
'local' => [
|
||||
'driver' => 'local',
|
||||
'root' => public_path(),
|
||||
'visibility' => 'public',
|
||||
'serve' => false,
|
||||
'throw' => true,
|
||||
'directory_visibility' => 'public',
|
||||
],
|
||||
|
||||
'local_secure_attachments' => [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('uploads/files/'),
|
||||
'serve' => false,
|
||||
'throw' => true,
|
||||
],
|
||||
|
||||
'local_secure_images' => [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('uploads/images/'),
|
||||
'visibility' => 'public',
|
||||
'serve' => false,
|
||||
'throw' => true,
|
||||
],
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
// Configured mail encryption method.
|
||||
// STARTTLS should still be attempted, but tls/ssl forces TLS usage.
|
||||
$mailEncryption = env('MAIL_ENCRYPTION', null);
|
||||
$mailPort = intval(env('MAIL_PORT', 587));
|
||||
|
||||
return [
|
||||
|
||||
@@ -33,13 +34,13 @@ return [
|
||||
'transport' => 'smtp',
|
||||
'scheme' => null,
|
||||
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
|
||||
'port' => env('MAIL_PORT', 587),
|
||||
'port' => $mailPort,
|
||||
'username' => env('MAIL_USERNAME'),
|
||||
'password' => env('MAIL_PASSWORD'),
|
||||
'verify_peer' => env('MAIL_VERIFY_SSL', true),
|
||||
'timeout' => null,
|
||||
'local_domain' => env('MAIL_EHLO_DOMAIN'),
|
||||
'tls_required' => ($mailEncryption === 'tls' || $mailEncryption === 'ssl'),
|
||||
'local_domain' => null,
|
||||
'require_tls' => ($mailEncryption === 'tls' || $mailEncryption === 'ssl' || $mailPort === 465),
|
||||
],
|
||||
|
||||
'sendmail' => [
|
||||
@@ -64,12 +65,4 @@ return [
|
||||
],
|
||||
],
|
||||
],
|
||||
|
||||
// Email markdown configuration
|
||||
'markdown' => [
|
||||
'theme' => 'default',
|
||||
'paths' => [
|
||||
resource_path('views/vendor/mail'),
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
@@ -47,6 +47,12 @@ return [
|
||||
// Multiple values can be provided comma seperated.
|
||||
'additional_scopes' => env('OIDC_ADDITIONAL_SCOPES', null),
|
||||
|
||||
// Enable fetching of the user's avatar from the 'picture' claim on login.
|
||||
// Will only be fetched if the user doesn't already have an avatar image assigned.
|
||||
// This can be a security risk due to performing server-side fetching (with up to 3 redirects) of
|
||||
// data from external URLs. Only enable if you trust the OIDC auth provider to provide safe URLs for user images.
|
||||
'fetch_avatar' => env('OIDC_FETCH_AVATAR', false),
|
||||
|
||||
// Group sync options
|
||||
// Enable syncing, upon login, of OIDC groups to BookStack roles
|
||||
'user_to_groups' => env('OIDC_USER_TO_GROUPS', false),
|
||||
|
||||
@@ -23,6 +23,7 @@ return [
|
||||
|
||||
'database' => [
|
||||
'driver' => 'database',
|
||||
'connection' => null,
|
||||
'table' => 'jobs',
|
||||
'queue' => 'default',
|
||||
'retry_after' => 90,
|
||||
|
||||
99
app/Console/Commands/AssignSortRuleCommand.php
Normal file
99
app/Console/Commands/AssignSortRuleCommand.php
Normal file
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Console\Commands;
|
||||
|
||||
use BookStack\Entities\Models\Book;
|
||||
use BookStack\Sorting\BookSorter;
|
||||
use BookStack\Sorting\SortRule;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class AssignSortRuleCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'bookstack:assign-sort-rule
|
||||
{sort-rule=0: ID of the sort rule to apply}
|
||||
{--all-books : Apply to all books in the system}
|
||||
{--books-without-sort : Apply to only books without a sort rule already assigned}
|
||||
{--books-with-sort= : Apply to only books with the sort rule of given id}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Assign a sort rule to content in the system';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(BookSorter $sorter): int
|
||||
{
|
||||
$sortRuleId = intval($this->argument('sort-rule')) ?? 0;
|
||||
if ($sortRuleId === 0) {
|
||||
return $this->listSortRules();
|
||||
}
|
||||
|
||||
$rule = SortRule::query()->find($sortRuleId);
|
||||
if ($this->option('all-books')) {
|
||||
$query = Book::query();
|
||||
} else if ($this->option('books-without-sort')) {
|
||||
$query = Book::query()->whereNull('sort_rule_id');
|
||||
} else if ($this->option('books-with-sort')) {
|
||||
$sortId = intval($this->option('books-with-sort')) ?: 0;
|
||||
if (!$sortId) {
|
||||
$this->error("Provided --books-with-sort option value is invalid");
|
||||
return 1;
|
||||
}
|
||||
$query = Book::query()->where('sort_rule_id', $sortId);
|
||||
} else {
|
||||
$this->error("No option provided to specify target. Run with the -h option to see all available options.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!$rule) {
|
||||
$this->error("Sort rule of provided id {$sortRuleId} not found!");
|
||||
return 1;
|
||||
}
|
||||
|
||||
$count = $query->clone()->count();
|
||||
$this->warn("This will apply sort rule [{$rule->id}: {$rule->name}] to {$count} book(s) and run the sort on each.");
|
||||
$confirmed = $this->confirm("Are you sure you want to continue?");
|
||||
|
||||
if (!$confirmed) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
$processed = 0;
|
||||
$query->chunkById(10, function ($books) use ($rule, $sorter, $count, &$processed) {
|
||||
$max = min($count, ($processed + 10));
|
||||
$this->info("Applying to {$processed}-{$max} of {$count} books");
|
||||
foreach ($books as $book) {
|
||||
$book->sort_rule_id = $rule->id;
|
||||
$book->save();
|
||||
$sorter->runBookAutoSort($book);
|
||||
}
|
||||
$processed = $max;
|
||||
});
|
||||
|
||||
$this->info("Sort applied to {$processed} book(s)!");
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected function listSortRules(): int
|
||||
{
|
||||
|
||||
$rules = SortRule::query()->orderBy('id', 'asc')->get();
|
||||
$this->error("Sort rule ID required!");
|
||||
$this->warn("\nAvailable sort rules:");
|
||||
foreach ($rules as $rule) {
|
||||
$this->info("{$rule->id}: {$rule->name}");
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ class BookApiController extends ApiController
|
||||
{
|
||||
$books = $this->queries
|
||||
->visibleForList()
|
||||
->with(['cover:id,name,url'])
|
||||
->addSelect(['created_by', 'updated_by']);
|
||||
|
||||
return $this->apiListingResponse($books, [
|
||||
|
||||
@@ -18,6 +18,7 @@ use BookStack\Exceptions\NotFoundException;
|
||||
use BookStack\Facades\Activity;
|
||||
use BookStack\Http\Controller;
|
||||
use BookStack\References\ReferenceFetcher;
|
||||
use BookStack\Util\DatabaseTransaction;
|
||||
use BookStack\Util\SimpleListOptions;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -70,7 +71,7 @@ class BookController extends Controller
|
||||
/**
|
||||
* Show the form for creating a new book.
|
||||
*/
|
||||
public function create(string $shelfSlug = null)
|
||||
public function create(?string $shelfSlug = null)
|
||||
{
|
||||
$this->checkPermission('book-create-all');
|
||||
|
||||
@@ -93,7 +94,7 @@ class BookController extends Controller
|
||||
* @throws ImageUploadException
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function store(Request $request, string $shelfSlug = null)
|
||||
public function store(Request $request, ?string $shelfSlug = null)
|
||||
{
|
||||
$this->checkPermission('book-create-all');
|
||||
$validated = $this->validate($request, [
|
||||
@@ -263,7 +264,9 @@ class BookController extends Controller
|
||||
$this->checkPermission('bookshelf-create-all');
|
||||
$this->checkPermission('book-create-all');
|
||||
|
||||
$shelf = $transformer->transformBookToShelf($book);
|
||||
$shelf = (new DatabaseTransaction(function () use ($book, $transformer) {
|
||||
return $transformer->transformBookToShelf($book);
|
||||
}))->run();
|
||||
|
||||
return redirect($shelf->getUrl());
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ class BookshelfApiController extends ApiController
|
||||
{
|
||||
$shelves = $this->queries
|
||||
->visibleForList()
|
||||
->with(['cover:id,name,url'])
|
||||
->addSelect(['created_by', 'updated_by']);
|
||||
|
||||
return $this->apiListingResponse($shelves, [
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace BookStack\Entities\Controllers;
|
||||
|
||||
use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Models\Chapter;
|
||||
use BookStack\Entities\Queries\ChapterQueries;
|
||||
use BookStack\Entities\Queries\EntityQueries;
|
||||
@@ -9,12 +10,11 @@ use BookStack\Entities\Repos\ChapterRepo;
|
||||
use BookStack\Exceptions\PermissionsException;
|
||||
use BookStack\Http\ApiController;
|
||||
use Exception;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ChapterApiController extends ApiController
|
||||
{
|
||||
protected $rules = [
|
||||
protected array $rules = [
|
||||
'create' => [
|
||||
'book_id' => ['required', 'integer'],
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
@@ -144,7 +144,10 @@ class ChapterApiController extends ApiController
|
||||
$chapter->load(['tags']);
|
||||
$chapter->makeVisible('description_html');
|
||||
$chapter->setAttribute('description_html', $chapter->descriptionHtml());
|
||||
$chapter->setAttribute('book_slug', $chapter->book()->first()->slug);
|
||||
|
||||
/** @var Book $book */
|
||||
$book = $chapter->book()->first();
|
||||
$chapter->setAttribute('book_slug', $book->slug);
|
||||
|
||||
return $chapter;
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ use BookStack\Exceptions\NotifyException;
|
||||
use BookStack\Exceptions\PermissionsException;
|
||||
use BookStack\Http\Controller;
|
||||
use BookStack\References\ReferenceFetcher;
|
||||
use BookStack\Util\DatabaseTransaction;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Throwable;
|
||||
@@ -269,7 +270,9 @@ class ChapterController extends Controller
|
||||
$this->checkOwnablePermission('chapter-delete', $chapter);
|
||||
$this->checkPermission('book-create-all');
|
||||
|
||||
$book = $transformer->transformChapterToBook($chapter);
|
||||
$book = (new DatabaseTransaction(function () use ($chapter, $transformer) {
|
||||
return $transformer->transformChapterToBook($chapter);
|
||||
}))->run();
|
||||
|
||||
return redirect($book->getUrl());
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use Illuminate\Http\Request;
|
||||
|
||||
class PageApiController extends ApiController
|
||||
{
|
||||
protected $rules = [
|
||||
protected array $rules = [
|
||||
'create' => [
|
||||
'book_id' => ['required_without:chapter_id', 'integer'],
|
||||
'chapter_id' => ['required_without:book_id', 'integer'],
|
||||
|
||||
@@ -17,6 +17,7 @@ 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\References\ReferenceFetcher;
|
||||
@@ -41,7 +42,7 @@ class PageController extends Controller
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function create(string $bookSlug, string $chapterSlug = null)
|
||||
public function create(string $bookSlug, ?string $chapterSlug = null)
|
||||
{
|
||||
if ($chapterSlug) {
|
||||
$parent = $this->entityQueries->chapters->findVisibleBySlugsOrFail($bookSlug, $chapterSlug);
|
||||
@@ -69,7 +70,7 @@ class PageController extends Controller
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function createAsGuest(Request $request, string $bookSlug, string $chapterSlug = null)
|
||||
public function createAsGuest(Request $request, string $bookSlug, ?string $chapterSlug = null)
|
||||
{
|
||||
$this->validate($request, [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
@@ -196,7 +197,7 @@ class PageController extends Controller
|
||||
public function edit(Request $request, string $bookSlug, string $pageSlug)
|
||||
{
|
||||
$page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
|
||||
$this->checkOwnablePermission('page-update', $page);
|
||||
$this->checkOwnablePermission('page-update', $page, $page->getUrl());
|
||||
|
||||
$editorData = new PageEditorData($page, $this->entityQueries, $request->query('editor', ''));
|
||||
if ($editorData->getWarnings()) {
|
||||
|
||||
@@ -43,7 +43,6 @@ class PageRevisionController extends Controller
|
||||
->selectRaw("IF(markdown = '', false, true) as is_markdown")
|
||||
->with(['page.book', 'createdBy'])
|
||||
->reorder('id', $listOptions->getOrder())
|
||||
->reorder('created_at', $listOptions->getOrder())
|
||||
->paginate(50);
|
||||
|
||||
$this->setPageTitle(trans('entities.pages_revisions_named', ['pageName' => $page->getShortName()]));
|
||||
@@ -52,6 +51,7 @@ class PageRevisionController extends Controller
|
||||
'revisions' => $revisions,
|
||||
'page' => $page,
|
||||
'listOptions' => $listOptions,
|
||||
'oldestRevisionId' => $page->revisions()->min('id'),
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace BookStack\Entities\Models;
|
||||
|
||||
use BookStack\Sorting\SortRule;
|
||||
use BookStack\Uploads\Image;
|
||||
use Exception;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -16,12 +17,14 @@ use Illuminate\Support\Collection;
|
||||
* @property string $description
|
||||
* @property int $image_id
|
||||
* @property ?int $default_template_id
|
||||
* @property ?int $sort_rule_id
|
||||
* @property Image|null $cover
|
||||
* @property \Illuminate\Database\Eloquent\Collection $chapters
|
||||
* @property \Illuminate\Database\Eloquent\Collection $pages
|
||||
* @property \Illuminate\Database\Eloquent\Collection $directPages
|
||||
* @property \Illuminate\Database\Eloquent\Collection $shelves
|
||||
* @property ?Page $defaultTemplate
|
||||
* @property ?SortRule $sortRule
|
||||
*/
|
||||
class Book extends Entity implements HasCoverImage
|
||||
{
|
||||
@@ -82,6 +85,14 @@ class Book extends Entity implements HasCoverImage
|
||||
return $this->belongsTo(Page::class, 'default_template_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the sort set assigned to this book, if existing.
|
||||
*/
|
||||
public function sortRule(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(SortRule::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all pages within this book.
|
||||
*/
|
||||
|
||||
@@ -60,6 +60,7 @@ class Chapter extends BookChild
|
||||
|
||||
/**
|
||||
* Get the visible pages in this chapter.
|
||||
* @returns Collection<Page>
|
||||
*/
|
||||
public function getVisiblePages(): Collection
|
||||
{
|
||||
|
||||
@@ -26,6 +26,7 @@ use BookStack\Users\Models\HasOwner;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
@@ -283,10 +284,14 @@ abstract class Entity extends Model implements Sluggable, Favouritable, Viewable
|
||||
public function getParent(): ?self
|
||||
{
|
||||
if ($this instanceof Page) {
|
||||
return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
|
||||
/** @var BelongsTo<Chapter|Book, Page> $builder */
|
||||
$builder = $this->chapter_id ? $this->chapter() : $this->book();
|
||||
return $builder->withTrashed()->first();
|
||||
}
|
||||
if ($this instanceof Chapter) {
|
||||
return $this->book()->withTrashed()->first();
|
||||
/** @var BelongsTo<Book, Page> $builder */
|
||||
$builder = $this->book();
|
||||
return $builder->withTrashed()->first();
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -295,7 +300,7 @@ abstract class Entity extends Model implements Sluggable, Favouritable, Viewable
|
||||
/**
|
||||
* Rebuild the permissions for this entity.
|
||||
*/
|
||||
public function rebuildPermissions()
|
||||
public function rebuildPermissions(): void
|
||||
{
|
||||
app()->make(JointPermissionBuilder::class)->rebuildForEntity(clone $this);
|
||||
}
|
||||
@@ -303,7 +308,7 @@ abstract class Entity extends Model implements Sluggable, Favouritable, Viewable
|
||||
/**
|
||||
* Index the current entity for search.
|
||||
*/
|
||||
public function indexForSearch()
|
||||
public function indexForSearch(): void
|
||||
{
|
||||
app()->make(SearchIndex::class)->indexEntity(clone $this);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ class QueryPopular
|
||||
) {
|
||||
}
|
||||
|
||||
public function run(int $count, int $page, array $filterModels = null): Collection
|
||||
public function run(int $count, int $page, array $filterModels): Collection
|
||||
{
|
||||
$query = $this->permissions
|
||||
->restrictEntityRelationQuery(View::query(), 'views', 'viewable_id', 'viewable_type')
|
||||
@@ -26,7 +26,7 @@ class QueryPopular
|
||||
->groupBy('viewable_id', 'viewable_type')
|
||||
->orderBy('view_count', 'desc');
|
||||
|
||||
if ($filterModels) {
|
||||
if (!empty($filterModels)) {
|
||||
$query->whereIn('viewable_type', $this->entityProvider->getMorphClasses($filterModels));
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace BookStack\Entities\Repos;
|
||||
|
||||
use BookStack\Activity\TagRepo;
|
||||
use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Models\BookChild;
|
||||
use BookStack\Entities\Models\Chapter;
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Entities\Models\HasCoverImage;
|
||||
@@ -12,6 +13,7 @@ use BookStack\Entities\Queries\PageQueries;
|
||||
use BookStack\Exceptions\ImageUploadException;
|
||||
use BookStack\References\ReferenceStore;
|
||||
use BookStack\References\ReferenceUpdater;
|
||||
use BookStack\Sorting\BookSorter;
|
||||
use BookStack\Uploads\ImageRepo;
|
||||
use BookStack\Util\HtmlDescriptionFilter;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
@@ -24,6 +26,7 @@ class BaseRepo
|
||||
protected ReferenceUpdater $referenceUpdater,
|
||||
protected ReferenceStore $referenceStore,
|
||||
protected PageQueries $pageQueries,
|
||||
protected BookSorter $bookSorter,
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -74,7 +77,6 @@ class BaseRepo
|
||||
$entity->touch();
|
||||
}
|
||||
|
||||
$entity->rebuildPermissions();
|
||||
$entity->indexForSearch();
|
||||
$this->referenceStore->updateForEntity($entity);
|
||||
|
||||
@@ -134,6 +136,18 @@ class BaseRepo
|
||||
$entity->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort the parent of the given entity, if any auto sort actions are set for it.
|
||||
* Typically ran during create/update/insert events.
|
||||
*/
|
||||
public function sortParent(Entity $entity): void
|
||||
{
|
||||
if ($entity instanceof BookChild) {
|
||||
$book = $entity->book;
|
||||
$this->bookSorter->runBookAutoSort($book);
|
||||
}
|
||||
}
|
||||
|
||||
protected function updateDescription(Entity $entity, array $input): void
|
||||
{
|
||||
if (!in_array(HasHtmlDescription::class, class_uses($entity))) {
|
||||
|
||||
@@ -8,7 +8,9 @@ use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Tools\TrashCan;
|
||||
use BookStack\Exceptions\ImageUploadException;
|
||||
use BookStack\Facades\Activity;
|
||||
use BookStack\Sorting\SortRule;
|
||||
use BookStack\Uploads\ImageRepo;
|
||||
use BookStack\Util\DatabaseTransaction;
|
||||
use Exception;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
|
||||
@@ -27,13 +29,22 @@ class BookRepo
|
||||
*/
|
||||
public function create(array $input): Book
|
||||
{
|
||||
$book = new Book();
|
||||
$this->baseRepo->create($book, $input);
|
||||
$this->baseRepo->updateCoverImage($book, $input['image'] ?? null);
|
||||
$this->baseRepo->updateDefaultTemplate($book, intval($input['default_template_id'] ?? null));
|
||||
Activity::add(ActivityType::BOOK_CREATE, $book);
|
||||
return (new DatabaseTransaction(function () use ($input) {
|
||||
$book = new Book();
|
||||
|
||||
return $book;
|
||||
$this->baseRepo->create($book, $input);
|
||||
$this->baseRepo->updateCoverImage($book, $input['image'] ?? null);
|
||||
$this->baseRepo->updateDefaultTemplate($book, intval($input['default_template_id'] ?? null));
|
||||
Activity::add(ActivityType::BOOK_CREATE, $book);
|
||||
|
||||
$defaultBookSortSetting = intval(setting('sorting-book-default', '0'));
|
||||
if ($defaultBookSortSetting && SortRule::query()->find($defaultBookSortSetting)) {
|
||||
$book->sort_rule_id = $defaultBookSortSetting;
|
||||
$book->save();
|
||||
}
|
||||
|
||||
return $book;
|
||||
}))->run();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,6 +7,7 @@ use BookStack\Entities\Models\Bookshelf;
|
||||
use BookStack\Entities\Queries\BookQueries;
|
||||
use BookStack\Entities\Tools\TrashCan;
|
||||
use BookStack\Facades\Activity;
|
||||
use BookStack\Util\DatabaseTransaction;
|
||||
use Exception;
|
||||
|
||||
class BookshelfRepo
|
||||
@@ -23,13 +24,14 @@ class BookshelfRepo
|
||||
*/
|
||||
public function create(array $input, array $bookIds): Bookshelf
|
||||
{
|
||||
$shelf = new Bookshelf();
|
||||
$this->baseRepo->create($shelf, $input);
|
||||
$this->baseRepo->updateCoverImage($shelf, $input['image'] ?? null);
|
||||
$this->updateBooks($shelf, $bookIds);
|
||||
Activity::add(ActivityType::BOOKSHELF_CREATE, $shelf);
|
||||
|
||||
return $shelf;
|
||||
return (new DatabaseTransaction(function () use ($input, $bookIds) {
|
||||
$shelf = new Bookshelf();
|
||||
$this->baseRepo->create($shelf, $input);
|
||||
$this->baseRepo->updateCoverImage($shelf, $input['image'] ?? null);
|
||||
$this->updateBooks($shelf, $bookIds);
|
||||
Activity::add(ActivityType::BOOKSHELF_CREATE, $shelf);
|
||||
return $shelf;
|
||||
}))->run();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -54,20 +56,37 @@ class BookshelfRepo
|
||||
|
||||
/**
|
||||
* Update which books are assigned to this shelf by syncing the given book ids.
|
||||
* Function ensures the books are visible to the current user and existing.
|
||||
* Function ensures the managed books are visible to the current user and existing,
|
||||
* and that the user does not alter the assignment of books that are not visible to them.
|
||||
*/
|
||||
protected function updateBooks(Bookshelf $shelf, array $bookIds)
|
||||
protected function updateBooks(Bookshelf $shelf, array $bookIds): void
|
||||
{
|
||||
$numericIDs = collect($bookIds)->map(function ($id) {
|
||||
return intval($id);
|
||||
});
|
||||
|
||||
$syncData = $this->bookQueries->visibleForList()
|
||||
$existingBookIds = $shelf->books()->pluck('id')->toArray();
|
||||
$visibleExistingBookIds = $this->bookQueries->visibleForList()
|
||||
->whereIn('id', $existingBookIds)
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
$nonVisibleExistingBookIds = array_values(array_diff($existingBookIds, $visibleExistingBookIds));
|
||||
|
||||
$newIdsToAssign = $this->bookQueries->visibleForList()
|
||||
->whereIn('id', $bookIds)
|
||||
->pluck('id')
|
||||
->mapWithKeys(function ($bookId) use ($numericIDs) {
|
||||
return [$bookId => ['order' => $numericIDs->search($bookId)]];
|
||||
});
|
||||
->toArray();
|
||||
|
||||
$maxNewIndex = max($numericIDs->keys()->toArray() ?: [0]);
|
||||
|
||||
$syncData = [];
|
||||
foreach ($newIdsToAssign as $id) {
|
||||
$syncData[$id] = ['order' => $numericIDs->search($id)];
|
||||
}
|
||||
|
||||
foreach ($nonVisibleExistingBookIds as $index => $id) {
|
||||
$syncData[$id] = ['order' => $maxNewIndex + ($index + 1)];
|
||||
}
|
||||
|
||||
$shelf->books()->sync($syncData);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ use BookStack\Entities\Tools\TrashCan;
|
||||
use BookStack\Exceptions\MoveOperationException;
|
||||
use BookStack\Exceptions\PermissionsException;
|
||||
use BookStack\Facades\Activity;
|
||||
use BookStack\Util\DatabaseTransaction;
|
||||
use Exception;
|
||||
|
||||
class ChapterRepo
|
||||
@@ -27,14 +28,18 @@ class ChapterRepo
|
||||
*/
|
||||
public function create(array $input, Book $parentBook): Chapter
|
||||
{
|
||||
$chapter = new Chapter();
|
||||
$chapter->book_id = $parentBook->id;
|
||||
$chapter->priority = (new BookContents($parentBook))->getLastPriority() + 1;
|
||||
$this->baseRepo->create($chapter, $input);
|
||||
$this->baseRepo->updateDefaultTemplate($chapter, intval($input['default_template_id'] ?? null));
|
||||
Activity::add(ActivityType::CHAPTER_CREATE, $chapter);
|
||||
return (new DatabaseTransaction(function () use ($input, $parentBook) {
|
||||
$chapter = new Chapter();
|
||||
$chapter->book_id = $parentBook->id;
|
||||
$chapter->priority = (new BookContents($parentBook))->getLastPriority() + 1;
|
||||
$this->baseRepo->create($chapter, $input);
|
||||
$this->baseRepo->updateDefaultTemplate($chapter, intval($input['default_template_id'] ?? null));
|
||||
Activity::add(ActivityType::CHAPTER_CREATE, $chapter);
|
||||
|
||||
return $chapter;
|
||||
$this->baseRepo->sortParent($chapter);
|
||||
|
||||
return $chapter;
|
||||
}))->run();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,6 +55,8 @@ class ChapterRepo
|
||||
|
||||
Activity::add(ActivityType::CHAPTER_UPDATE, $chapter);
|
||||
|
||||
$this->baseRepo->sortParent($chapter);
|
||||
|
||||
return $chapter;
|
||||
}
|
||||
|
||||
@@ -84,10 +91,14 @@ class ChapterRepo
|
||||
throw new PermissionsException('User does not have permission to create a chapter within the chosen book');
|
||||
}
|
||||
|
||||
$chapter->changeBook($parent->id);
|
||||
$chapter->rebuildPermissions();
|
||||
Activity::add(ActivityType::CHAPTER_MOVE, $chapter);
|
||||
return (new DatabaseTransaction(function () use ($chapter, $parent) {
|
||||
$chapter->changeBook($parent->id);
|
||||
$chapter->rebuildPermissions();
|
||||
Activity::add(ActivityType::CHAPTER_MOVE, $chapter);
|
||||
|
||||
return $parent;
|
||||
$this->baseRepo->sortParent($chapter);
|
||||
|
||||
return $parent;
|
||||
}))->run();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ use BookStack\Exceptions\PermissionsException;
|
||||
use BookStack\Facades\Activity;
|
||||
use BookStack\References\ReferenceStore;
|
||||
use BookStack\References\ReferenceUpdater;
|
||||
use BookStack\Util\DatabaseTransaction;
|
||||
use Exception;
|
||||
|
||||
class PageRepo
|
||||
@@ -61,8 +62,10 @@ class PageRepo
|
||||
]);
|
||||
}
|
||||
|
||||
$page->save();
|
||||
$page->refresh()->rebuildPermissions();
|
||||
(new DatabaseTransaction(function () use ($page) {
|
||||
$page->save();
|
||||
$page->refresh()->rebuildPermissions();
|
||||
}))->run();
|
||||
|
||||
return $page;
|
||||
}
|
||||
@@ -72,19 +75,34 @@ class PageRepo
|
||||
*/
|
||||
public function publishDraft(Page $draft, array $input): Page
|
||||
{
|
||||
$draft->draft = false;
|
||||
$draft->revision_count = 1;
|
||||
$draft->priority = $this->getNewPriority($draft);
|
||||
$this->updateTemplateStatusAndContentFromInput($draft, $input);
|
||||
$this->baseRepo->update($draft, $input);
|
||||
return (new DatabaseTransaction(function () use ($draft, $input) {
|
||||
$draft->draft = false;
|
||||
$draft->revision_count = 1;
|
||||
$draft->priority = $this->getNewPriority($draft);
|
||||
$this->updateTemplateStatusAndContentFromInput($draft, $input);
|
||||
$this->baseRepo->update($draft, $input);
|
||||
$draft->rebuildPermissions();
|
||||
|
||||
$summary = trim($input['summary'] ?? '') ?: trans('entities.pages_initial_revision');
|
||||
$this->revisionRepo->storeNewForPage($draft, $summary);
|
||||
$draft->refresh();
|
||||
$summary = trim($input['summary'] ?? '') ?: trans('entities.pages_initial_revision');
|
||||
$this->revisionRepo->storeNewForPage($draft, $summary);
|
||||
$draft->refresh();
|
||||
|
||||
Activity::add(ActivityType::PAGE_CREATE, $draft);
|
||||
Activity::add(ActivityType::PAGE_CREATE, $draft);
|
||||
$this->baseRepo->sortParent($draft);
|
||||
|
||||
return $draft;
|
||||
return $draft;
|
||||
}))->run();
|
||||
}
|
||||
|
||||
/**
|
||||
* Directly update the content for the given page from the provided input.
|
||||
* Used for direct content access in a way that performs required changes
|
||||
* (Search index and reference regen) without performing an official update.
|
||||
*/
|
||||
public function setContentFromInput(Page $page, array $input): void
|
||||
{
|
||||
$this->updateTemplateStatusAndContentFromInput($page, $input);
|
||||
$this->baseRepo->update($page, []);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -104,7 +122,7 @@ class PageRepo
|
||||
$page->revision_count++;
|
||||
$page->save();
|
||||
|
||||
// Remove all update drafts for this user & page.
|
||||
// Remove all update drafts for this user and page.
|
||||
$this->revisionRepo->deleteDraftsForCurrentUser($page);
|
||||
|
||||
// Save a revision after updating
|
||||
@@ -117,11 +135,12 @@ class PageRepo
|
||||
}
|
||||
|
||||
Activity::add(ActivityType::PAGE_UPDATE, $page);
|
||||
$this->baseRepo->sortParent($page);
|
||||
|
||||
return $page;
|
||||
}
|
||||
|
||||
protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
|
||||
protected function updateTemplateStatusAndContentFromInput(Page $page, array $input): void
|
||||
{
|
||||
if (isset($input['template']) && userCan('templates-manage')) {
|
||||
$page->template = ($input['template'] === 'true');
|
||||
@@ -232,6 +251,8 @@ class PageRepo
|
||||
Activity::add(ActivityType::PAGE_RESTORE, $page);
|
||||
Activity::add(ActivityType::REVISION_RESTORE, $revision);
|
||||
|
||||
$this->baseRepo->sortParent($page);
|
||||
|
||||
return $page;
|
||||
}
|
||||
|
||||
@@ -254,14 +275,18 @@ class PageRepo
|
||||
throw new PermissionsException('User does not have permission to create a page within the new parent');
|
||||
}
|
||||
|
||||
$page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
|
||||
$newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
|
||||
$page->changeBook($newBookId);
|
||||
$page->rebuildPermissions();
|
||||
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->changeBook($newBookId);
|
||||
$page->rebuildPermissions();
|
||||
|
||||
Activity::add(ActivityType::PAGE_MOVE, $page);
|
||||
Activity::add(ActivityType::PAGE_MOVE, $page);
|
||||
|
||||
return $parent;
|
||||
$this->baseRepo->sortParent($page);
|
||||
|
||||
return $parent;
|
||||
}))->run();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -46,7 +46,7 @@ class RevisionRepo
|
||||
/**
|
||||
* Store a new revision in the system for the given page.
|
||||
*/
|
||||
public function storeNewForPage(Page $page, string $summary = null): PageRevision
|
||||
public function storeNewForPage(Page $page, ?string $summary = null): PageRevision
|
||||
{
|
||||
$revision = new PageRevision();
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ use BookStack\Entities\Models\Chapter;
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Entities\Queries\EntityQueries;
|
||||
use BookStack\Sorting\BookSortMap;
|
||||
use BookStack\Sorting\BookSortMapItem;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class BookContents
|
||||
@@ -103,211 +105,4 @@ class BookContents
|
||||
|
||||
return $query->where('book_id', '=', $this->book->id)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort the books content using the given sort map.
|
||||
* Returns a list of books that were involved in the operation.
|
||||
*
|
||||
* @returns Book[]
|
||||
*/
|
||||
public function sortUsingMap(BookSortMap $sortMap): array
|
||||
{
|
||||
// Load models into map
|
||||
$modelMap = $this->loadModelsFromSortMap($sortMap);
|
||||
|
||||
// Sort our changes from our map to be chapters first
|
||||
// Since they need to be process to ensure book alignment for child page changes.
|
||||
$sortMapItems = $sortMap->all();
|
||||
usort($sortMapItems, function (BookSortMapItem $itemA, BookSortMapItem $itemB) {
|
||||
$aScore = $itemA->type === 'page' ? 2 : 1;
|
||||
$bScore = $itemB->type === 'page' ? 2 : 1;
|
||||
|
||||
return $aScore - $bScore;
|
||||
});
|
||||
|
||||
// Perform the sort
|
||||
foreach ($sortMapItems as $item) {
|
||||
$this->applySortUpdates($item, $modelMap);
|
||||
}
|
||||
|
||||
/** @var Book[] $booksInvolved */
|
||||
$booksInvolved = array_values(array_filter($modelMap, function (string $key) {
|
||||
return str_starts_with($key, 'book:');
|
||||
}, ARRAY_FILTER_USE_KEY));
|
||||
|
||||
// Update permissions of books involved
|
||||
foreach ($booksInvolved as $book) {
|
||||
$book->rebuildPermissions();
|
||||
}
|
||||
|
||||
return $booksInvolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Using the given sort map item, detect changes for the related model
|
||||
* and update it if required. Changes where permissions are lacking will
|
||||
* be skipped and not throw an error.
|
||||
*
|
||||
* @param array<string, Entity> $modelMap
|
||||
*/
|
||||
protected function applySortUpdates(BookSortMapItem $sortMapItem, array $modelMap): void
|
||||
{
|
||||
/** @var BookChild $model */
|
||||
$model = $modelMap[$sortMapItem->type . ':' . $sortMapItem->id] ?? null;
|
||||
if (!$model) {
|
||||
return;
|
||||
}
|
||||
|
||||
$priorityChanged = $model->priority !== $sortMapItem->sort;
|
||||
$bookChanged = $model->book_id !== $sortMapItem->parentBookId;
|
||||
$chapterChanged = ($model instanceof Page) && $model->chapter_id !== $sortMapItem->parentChapterId;
|
||||
|
||||
// Stop if there's no change
|
||||
if (!$priorityChanged && !$bookChanged && !$chapterChanged) {
|
||||
return;
|
||||
}
|
||||
|
||||
$currentParentKey = 'book:' . $model->book_id;
|
||||
if ($model instanceof Page && $model->chapter_id) {
|
||||
$currentParentKey = 'chapter:' . $model->chapter_id;
|
||||
}
|
||||
|
||||
$currentParent = $modelMap[$currentParentKey] ?? null;
|
||||
/** @var Book $newBook */
|
||||
$newBook = $modelMap['book:' . $sortMapItem->parentBookId] ?? null;
|
||||
/** @var ?Chapter $newChapter */
|
||||
$newChapter = $sortMapItem->parentChapterId ? ($modelMap['chapter:' . $sortMapItem->parentChapterId] ?? null) : null;
|
||||
|
||||
if (!$this->isSortChangePermissible($sortMapItem, $model, $currentParent, $newBook, $newChapter)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Action the required changes
|
||||
if ($bookChanged) {
|
||||
$model->changeBook($newBook->id);
|
||||
}
|
||||
|
||||
if ($model instanceof Page && $chapterChanged) {
|
||||
$model->chapter_id = $newChapter->id ?? 0;
|
||||
}
|
||||
|
||||
if ($priorityChanged) {
|
||||
$model->priority = $sortMapItem->sort;
|
||||
}
|
||||
|
||||
if ($chapterChanged || $priorityChanged) {
|
||||
$model->save();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current user has permissions to apply the given sorting change.
|
||||
* Is quite complex since items can gain a different parent change. Acts as a:
|
||||
* - Update of old parent element (Change of content/order).
|
||||
* - Update of sorted/moved element.
|
||||
* - Deletion of element (Relative to parent upon move).
|
||||
* - Creation of element within parent (Upon move to new parent).
|
||||
*/
|
||||
protected function isSortChangePermissible(BookSortMapItem $sortMapItem, BookChild $model, ?Entity $currentParent, ?Entity $newBook, ?Entity $newChapter): bool
|
||||
{
|
||||
// Stop if we can't see the current parent or new book.
|
||||
if (!$currentParent || !$newBook) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$hasNewParent = $newBook->id !== $model->book_id || ($model instanceof Page && $model->chapter_id !== ($sortMapItem->parentChapterId ?? 0));
|
||||
if ($model instanceof Chapter) {
|
||||
$hasPermission = userCan('book-update', $currentParent)
|
||||
&& userCan('book-update', $newBook)
|
||||
&& userCan('chapter-update', $model)
|
||||
&& (!$hasNewParent || userCan('chapter-create', $newBook))
|
||||
&& (!$hasNewParent || userCan('chapter-delete', $model));
|
||||
|
||||
if (!$hasPermission) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if ($model instanceof Page) {
|
||||
$parentPermission = ($currentParent instanceof Chapter) ? 'chapter-update' : 'book-update';
|
||||
$hasCurrentParentPermission = userCan($parentPermission, $currentParent);
|
||||
|
||||
// This needs to check if there was an intended chapter location in the original sort map
|
||||
// rather than inferring from the $newChapter since that variable may be null
|
||||
// due to other reasons (Visibility).
|
||||
$newParent = $sortMapItem->parentChapterId ? $newChapter : $newBook;
|
||||
if (!$newParent) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$hasPageEditPermission = userCan('page-update', $model);
|
||||
$newParentInRightLocation = ($newParent instanceof Book || ($newParent instanceof Chapter && $newParent->book_id === $newBook->id));
|
||||
$newParentPermission = ($newParent instanceof Chapter) ? 'chapter-update' : 'book-update';
|
||||
$hasNewParentPermission = userCan($newParentPermission, $newParent);
|
||||
|
||||
$hasDeletePermissionIfMoving = (!$hasNewParent || userCan('page-delete', $model));
|
||||
$hasCreatePermissionIfMoving = (!$hasNewParent || userCan('page-create', $newParent));
|
||||
|
||||
$hasPermission = $hasCurrentParentPermission
|
||||
&& $newParentInRightLocation
|
||||
&& $hasNewParentPermission
|
||||
&& $hasPageEditPermission
|
||||
&& $hasDeletePermissionIfMoving
|
||||
&& $hasCreatePermissionIfMoving;
|
||||
|
||||
if (!$hasPermission) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load models from the database into the given sort map.
|
||||
*
|
||||
* @return array<string, Entity>
|
||||
*/
|
||||
protected function loadModelsFromSortMap(BookSortMap $sortMap): array
|
||||
{
|
||||
$modelMap = [];
|
||||
$ids = [
|
||||
'chapter' => [],
|
||||
'page' => [],
|
||||
'book' => [],
|
||||
];
|
||||
|
||||
foreach ($sortMap->all() as $sortMapItem) {
|
||||
$ids[$sortMapItem->type][] = $sortMapItem->id;
|
||||
$ids['book'][] = $sortMapItem->parentBookId;
|
||||
if ($sortMapItem->parentChapterId) {
|
||||
$ids['chapter'][] = $sortMapItem->parentChapterId;
|
||||
}
|
||||
}
|
||||
|
||||
$pages = $this->queries->pages->visibleForList()->whereIn('id', array_unique($ids['page']))->get();
|
||||
/** @var Page $page */
|
||||
foreach ($pages as $page) {
|
||||
$modelMap['page:' . $page->id] = $page;
|
||||
$ids['book'][] = $page->book_id;
|
||||
if ($page->chapter_id) {
|
||||
$ids['chapter'][] = $page->chapter_id;
|
||||
}
|
||||
}
|
||||
|
||||
$chapters = $this->queries->chapters->visibleForList()->whereIn('id', array_unique($ids['chapter']))->get();
|
||||
/** @var Chapter $chapter */
|
||||
foreach ($chapters as $chapter) {
|
||||
$modelMap['chapter:' . $chapter->id] = $chapter;
|
||||
$ids['book'][] = $chapter->book_id;
|
||||
}
|
||||
|
||||
$books = $this->queries->books->visibleForList()->whereIn('id', array_unique($ids['book']))->get();
|
||||
/** @var Book $book */
|
||||
foreach ($books as $book) {
|
||||
$modelMap['book:' . $book->id] = $book;
|
||||
}
|
||||
|
||||
return $modelMap;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,17 +18,12 @@ use Illuminate\Http\UploadedFile;
|
||||
|
||||
class Cloner
|
||||
{
|
||||
protected PageRepo $pageRepo;
|
||||
protected ChapterRepo $chapterRepo;
|
||||
protected BookRepo $bookRepo;
|
||||
protected ImageService $imageService;
|
||||
|
||||
public function __construct(PageRepo $pageRepo, ChapterRepo $chapterRepo, BookRepo $bookRepo, ImageService $imageService)
|
||||
{
|
||||
$this->pageRepo = $pageRepo;
|
||||
$this->chapterRepo = $chapterRepo;
|
||||
$this->bookRepo = $bookRepo;
|
||||
$this->imageService = $imageService;
|
||||
public function __construct(
|
||||
protected PageRepo $pageRepo,
|
||||
protected ChapterRepo $chapterRepo,
|
||||
protected BookRepo $bookRepo,
|
||||
protected ImageService $imageService,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,17 +13,12 @@ use BookStack\Facades\Activity;
|
||||
|
||||
class HierarchyTransformer
|
||||
{
|
||||
protected BookRepo $bookRepo;
|
||||
protected BookshelfRepo $shelfRepo;
|
||||
protected Cloner $cloner;
|
||||
protected TrashCan $trashCan;
|
||||
|
||||
public function __construct(BookRepo $bookRepo, BookshelfRepo $shelfRepo, Cloner $cloner, TrashCan $trashCan)
|
||||
{
|
||||
$this->bookRepo = $bookRepo;
|
||||
$this->shelfRepo = $shelfRepo;
|
||||
$this->cloner = $cloner;
|
||||
$this->trashCan = $trashCan;
|
||||
public function __construct(
|
||||
protected BookRepo $bookRepo,
|
||||
protected BookshelfRepo $shelfRepo,
|
||||
protected Cloner $cloner,
|
||||
protected TrashCan $trashCan
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -104,10 +104,10 @@ class PageIncludeParser
|
||||
|
||||
if ($currentOffset < $tagStartOffset) {
|
||||
$previousText = substr($text, $currentOffset, $tagStartOffset - $currentOffset);
|
||||
$textNode->parentNode->insertBefore(new DOMText($previousText), $textNode);
|
||||
$textNode->parentNode->insertBefore($this->doc->createTextNode($previousText), $textNode);
|
||||
}
|
||||
|
||||
$node = $textNode->parentNode->insertBefore(new DOMText($tagOuterContent), $textNode);
|
||||
$node = $textNode->parentNode->insertBefore($this->doc->createTextNode($tagOuterContent), $textNode);
|
||||
$includeTags[] = new PageIncludeTag($tagInnerContent, $node);
|
||||
$currentOffset = $tagStartOffset + strlen($tagOuterContent);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ use BookStack\Exceptions\NotifyException;
|
||||
use BookStack\Facades\Activity;
|
||||
use BookStack\Uploads\AttachmentService;
|
||||
use BookStack\Uploads\ImageService;
|
||||
use BookStack\Util\DatabaseTransaction;
|
||||
use Exception;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
@@ -357,25 +358,26 @@ class TrashCan
|
||||
|
||||
/**
|
||||
* Destroy the given entity.
|
||||
* Returns the number of total entities destroyed in the operation.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function destroyEntity(Entity $entity): int
|
||||
{
|
||||
if ($entity instanceof Page) {
|
||||
return $this->destroyPage($entity);
|
||||
}
|
||||
if ($entity instanceof Chapter) {
|
||||
return $this->destroyChapter($entity);
|
||||
}
|
||||
if ($entity instanceof Book) {
|
||||
return $this->destroyBook($entity);
|
||||
}
|
||||
if ($entity instanceof Bookshelf) {
|
||||
return $this->destroyShelf($entity);
|
||||
}
|
||||
$result = (new DatabaseTransaction(function () use ($entity) {
|
||||
if ($entity instanceof Page) {
|
||||
return $this->destroyPage($entity);
|
||||
} else if ($entity instanceof Chapter) {
|
||||
return $this->destroyChapter($entity);
|
||||
} else if ($entity instanceof Book) {
|
||||
return $this->destroyBook($entity);
|
||||
} else if ($entity instanceof Bookshelf) {
|
||||
return $this->destroyShelf($entity);
|
||||
}
|
||||
return null;
|
||||
}))->run();
|
||||
|
||||
return 0;
|
||||
return $result ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace BookStack\Exceptions;
|
||||
|
||||
use BookStack\App\AppVersion;
|
||||
use Illuminate\Contracts\Foundation\ExceptionRenderer;
|
||||
|
||||
class BookStackExceptionHandlerPage implements ExceptionRenderer
|
||||
@@ -30,9 +31,7 @@ class BookStackExceptionHandlerPage implements ExceptionRenderer
|
||||
return [
|
||||
'PHP Version' => phpversion(),
|
||||
'BookStack Version' => $this->safeReturn(function () {
|
||||
$versionFile = base_path('version');
|
||||
|
||||
return trim(file_get_contents($versionFile));
|
||||
return AppVersion::get();
|
||||
}, 'unknown'),
|
||||
'Theme Configured' => $this->safeReturn(function () {
|
||||
return config('view.theme');
|
||||
|
||||
7
app/Exceptions/LoginAttemptInvalidUserException.php
Normal file
7
app/Exceptions/LoginAttemptInvalidUserException.php
Normal file
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exceptions;
|
||||
|
||||
class LoginAttemptInvalidUserException extends LoginAttemptException
|
||||
{
|
||||
}
|
||||
7
app/Exceptions/ZipExportException.php
Normal file
7
app/Exceptions/ZipExportException.php
Normal file
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exceptions;
|
||||
|
||||
class ZipExportException extends \Exception
|
||||
{
|
||||
}
|
||||
13
app/Exceptions/ZipImportException.php
Normal file
13
app/Exceptions/ZipImportException.php
Normal file
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exceptions;
|
||||
|
||||
class ZipImportException extends \Exception
|
||||
{
|
||||
public function __construct(
|
||||
public array $errors
|
||||
) {
|
||||
$message = "Import failed with errors:" . implode("\n", $this->errors);
|
||||
parent::__construct($message);
|
||||
}
|
||||
}
|
||||
12
app/Exceptions/ZipValidationException.php
Normal file
12
app/Exceptions/ZipValidationException.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exceptions;
|
||||
|
||||
class ZipValidationException extends \Exception
|
||||
{
|
||||
public function __construct(
|
||||
public array $errors
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Entities\Controllers;
|
||||
namespace BookStack\Exports\Controllers;
|
||||
|
||||
use BookStack\Entities\Queries\BookQueries;
|
||||
use BookStack\Entities\Tools\ExportFormatter;
|
||||
use BookStack\Exports\ExportFormatter;
|
||||
use BookStack\Exports\ZipExports\ZipExportBuilder;
|
||||
use BookStack\Http\ApiController;
|
||||
use Throwable;
|
||||
|
||||
@@ -63,4 +64,15 @@ class BookExportApiController extends ApiController
|
||||
|
||||
return $this->download()->directly($markdown, $book->slug . '.md');
|
||||
}
|
||||
|
||||
/**
|
||||
* Export a book as a contained ZIP export file.
|
||||
*/
|
||||
public function exportZip(int $id, ZipExportBuilder $builder)
|
||||
{
|
||||
$book = $this->queries->findVisibleByIdOrFail($id);
|
||||
$zip = $builder->buildForBook($book);
|
||||
|
||||
return $this->download()->streamedFileDirectly($zip, $book->slug . '.zip', true);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Entities\Controllers;
|
||||
namespace BookStack\Exports\Controllers;
|
||||
|
||||
use BookStack\Entities\Queries\BookQueries;
|
||||
use BookStack\Entities\Tools\ExportFormatter;
|
||||
use BookStack\Exceptions\NotFoundException;
|
||||
use BookStack\Exports\ExportFormatter;
|
||||
use BookStack\Exports\ZipExports\ZipExportBuilder;
|
||||
use BookStack\Http\Controller;
|
||||
use Throwable;
|
||||
|
||||
@@ -14,6 +16,7 @@ class BookExportController extends Controller
|
||||
protected ExportFormatter $exportFormatter,
|
||||
) {
|
||||
$this->middleware('can:content-export');
|
||||
$this->middleware('throttle:exports');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,4 +66,16 @@ class BookExportController extends Controller
|
||||
|
||||
return $this->download()->directly($textContent, $bookSlug . '.md');
|
||||
}
|
||||
|
||||
/**
|
||||
* Export a book to a contained ZIP export file.
|
||||
* @throws NotFoundException
|
||||
*/
|
||||
public function zip(string $bookSlug, ZipExportBuilder $builder)
|
||||
{
|
||||
$book = $this->queries->findVisibleBySlugOrFail($bookSlug);
|
||||
$zip = $builder->buildForBook($book);
|
||||
|
||||
return $this->download()->streamedFileDirectly($zip, $bookSlug . '.zip', true);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Entities\Controllers;
|
||||
namespace BookStack\Exports\Controllers;
|
||||
|
||||
use BookStack\Entities\Queries\ChapterQueries;
|
||||
use BookStack\Entities\Tools\ExportFormatter;
|
||||
use BookStack\Exports\ExportFormatter;
|
||||
use BookStack\Exports\ZipExports\ZipExportBuilder;
|
||||
use BookStack\Http\ApiController;
|
||||
use Throwable;
|
||||
|
||||
@@ -63,4 +64,15 @@ class ChapterExportApiController extends ApiController
|
||||
|
||||
return $this->download()->directly($markdown, $chapter->slug . '.md');
|
||||
}
|
||||
|
||||
/**
|
||||
* Export a chapter as a contained ZIP file.
|
||||
*/
|
||||
public function exportZip(int $id, ZipExportBuilder $builder)
|
||||
{
|
||||
$chapter = $this->queries->findVisibleByIdOrFail($id);
|
||||
$zip = $builder->buildForChapter($chapter);
|
||||
|
||||
return $this->download()->streamedFileDirectly($zip, $chapter->slug . '.zip', true);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Entities\Controllers;
|
||||
namespace BookStack\Exports\Controllers;
|
||||
|
||||
use BookStack\Entities\Queries\ChapterQueries;
|
||||
use BookStack\Entities\Tools\ExportFormatter;
|
||||
use BookStack\Exceptions\NotFoundException;
|
||||
use BookStack\Exports\ExportFormatter;
|
||||
use BookStack\Exports\ZipExports\ZipExportBuilder;
|
||||
use BookStack\Http\Controller;
|
||||
use Throwable;
|
||||
|
||||
@@ -15,6 +16,7 @@ class ChapterExportController extends Controller
|
||||
protected ExportFormatter $exportFormatter,
|
||||
) {
|
||||
$this->middleware('can:content-export');
|
||||
$this->middleware('throttle:exports');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -70,4 +72,16 @@ class ChapterExportController extends Controller
|
||||
|
||||
return $this->download()->directly($chapterText, $chapterSlug . '.md');
|
||||
}
|
||||
|
||||
/**
|
||||
* Export a book to a contained ZIP export file.
|
||||
* @throws NotFoundException
|
||||
*/
|
||||
public function zip(string $bookSlug, string $chapterSlug, ZipExportBuilder $builder)
|
||||
{
|
||||
$chapter = $this->queries->findVisibleBySlugsOrFail($bookSlug, $chapterSlug);
|
||||
$zip = $builder->buildForChapter($chapter);
|
||||
|
||||
return $this->download()->streamedFileDirectly($zip, $chapterSlug . '.zip', true);
|
||||
}
|
||||
}
|
||||
144
app/Exports/Controllers/ImportApiController.php
Normal file
144
app/Exports/Controllers/ImportApiController.php
Normal file
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BookStack\Exports\Controllers;
|
||||
|
||||
use BookStack\Exceptions\ZipImportException;
|
||||
use BookStack\Exceptions\ZipValidationException;
|
||||
use BookStack\Exports\ImportRepo;
|
||||
use BookStack\Http\ApiController;
|
||||
use BookStack\Uploads\AttachmentService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
class ImportApiController extends ApiController
|
||||
{
|
||||
public function __construct(
|
||||
protected ImportRepo $imports,
|
||||
) {
|
||||
$this->middleware('can:content-import');
|
||||
}
|
||||
|
||||
/**
|
||||
* List existing ZIP imports visible to the user.
|
||||
* Requires permission to import content.
|
||||
*/
|
||||
public function list(): JsonResponse
|
||||
{
|
||||
$query = $this->imports->queryVisible();
|
||||
|
||||
return $this->apiListingResponse($query, [
|
||||
'id', 'name', 'size', 'type', 'created_by', 'created_at', 'updated_at'
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new import from a ZIP file.
|
||||
* This does not actually run the import since that is performed via the "run" endpoint.
|
||||
* This uploads, validates and stores the ZIP file so it's ready to be imported.
|
||||
*
|
||||
* This "file" parameter must be a BookStack-compatible ZIP file, and this must be
|
||||
* sent via a 'multipart/form-data' type request.
|
||||
*
|
||||
* Requires permission to import content.
|
||||
*/
|
||||
public function create(Request $request): JsonResponse
|
||||
{
|
||||
$this->validate($request, $this->rules()['create']);
|
||||
|
||||
$file = $request->file('file');
|
||||
|
||||
try {
|
||||
$import = $this->imports->storeFromUpload($file);
|
||||
} catch (ZipValidationException $exception) {
|
||||
$message = "ZIP upload failed with the following validation errors: \n" . $this->formatErrors($exception->errors);
|
||||
return $this->jsonError($message, 422);
|
||||
}
|
||||
|
||||
return response()->json($import);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read details of a pending ZIP import.
|
||||
* The "details" property contains high-level metadata regarding the ZIP import content,
|
||||
* and the structure of this will change depending on import "type".
|
||||
* Requires permission to import content.
|
||||
*/
|
||||
public function read(int $id): JsonResponse
|
||||
{
|
||||
$import = $this->imports->findVisible($id);
|
||||
|
||||
$import->setAttribute('details', $import->decodeMetadata());
|
||||
|
||||
return response()->json($import);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the import process for an uploaded ZIP import.
|
||||
* The "parent_id" and "parent_type" parameters are required when the import type is "chapter" or "page".
|
||||
* On success, this endpoint returns the imported item.
|
||||
* Requires permission to import content.
|
||||
*/
|
||||
public function run(int $id, Request $request): JsonResponse
|
||||
{
|
||||
$import = $this->imports->findVisible($id);
|
||||
$parent = null;
|
||||
$rules = $this->rules()['run'];
|
||||
|
||||
if ($import->type === 'page' || $import->type === 'chapter') {
|
||||
$rules['parent_type'][] = 'required';
|
||||
$rules['parent_id'][] = 'required';
|
||||
$data = $this->validate($request, $rules);
|
||||
$parent = "{$data['parent_type']}:{$data['parent_id']}";
|
||||
}
|
||||
|
||||
try {
|
||||
$entity = $this->imports->runImport($import, $parent);
|
||||
} catch (ZipImportException $exception) {
|
||||
$message = "ZIP import failed with the following errors: \n" . $this->formatErrors($exception->errors);
|
||||
return $this->jsonError($message);
|
||||
}
|
||||
|
||||
return response()->json($entity->withoutRelations());
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a pending ZIP import from the system.
|
||||
* Requires permission to import content.
|
||||
*/
|
||||
public function delete(int $id): Response
|
||||
{
|
||||
$import = $this->imports->findVisible($id);
|
||||
$this->imports->deleteImport($import);
|
||||
|
||||
return response('', 204);
|
||||
}
|
||||
|
||||
protected function rules(): array
|
||||
{
|
||||
return [
|
||||
'create' => [
|
||||
'file' => ['required', ...AttachmentService::getFileValidationRules()],
|
||||
],
|
||||
'run' => [
|
||||
'parent_type' => ['string', 'in:book,chapter'],
|
||||
'parent_id' => ['int'],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
protected function formatErrors(array $errors): string
|
||||
{
|
||||
$parts = [];
|
||||
foreach ($errors as $key => $error) {
|
||||
if (is_string($key)) {
|
||||
$parts[] = "[{$key}] {$error}";
|
||||
} else {
|
||||
$parts[] = $error;
|
||||
}
|
||||
}
|
||||
return implode("\n", $parts);
|
||||
}
|
||||
}
|
||||
110
app/Exports/Controllers/ImportController.php
Normal file
110
app/Exports/Controllers/ImportController.php
Normal file
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace BookStack\Exports\Controllers;
|
||||
|
||||
use BookStack\Exceptions\ZipImportException;
|
||||
use BookStack\Exceptions\ZipValidationException;
|
||||
use BookStack\Exports\ImportRepo;
|
||||
use BookStack\Http\Controller;
|
||||
use BookStack\Uploads\AttachmentService;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ImportController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
protected ImportRepo $imports,
|
||||
) {
|
||||
$this->middleware('can:content-import');
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the view to start a new import, and also list out the existing
|
||||
* in progress imports that are visible to the user.
|
||||
*/
|
||||
public function start()
|
||||
{
|
||||
$imports = $this->imports->getVisibleImports();
|
||||
|
||||
$this->setPageTitle(trans('entities.import'));
|
||||
|
||||
return view('exports.import', [
|
||||
'imports' => $imports,
|
||||
'zipErrors' => session()->pull('validation_errors') ?? [],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload, validate and store an import file.
|
||||
*/
|
||||
public function upload(Request $request)
|
||||
{
|
||||
$this->validate($request, [
|
||||
'file' => ['required', ...AttachmentService::getFileValidationRules()]
|
||||
]);
|
||||
|
||||
$file = $request->file('file');
|
||||
try {
|
||||
$import = $this->imports->storeFromUpload($file);
|
||||
} catch (ZipValidationException $exception) {
|
||||
return redirect('/import')->with('validation_errors', $exception->errors);
|
||||
}
|
||||
|
||||
return redirect($import->getUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a pending import, with a form to allow progressing
|
||||
* with the import process.
|
||||
*/
|
||||
public function show(int $id)
|
||||
{
|
||||
$import = $this->imports->findVisible($id);
|
||||
|
||||
$this->setPageTitle(trans('entities.import_continue'));
|
||||
|
||||
return view('exports.import-show', [
|
||||
'import' => $import,
|
||||
'data' => $import->decodeMetadata(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the import process against an uploaded import ZIP.
|
||||
*/
|
||||
public function run(int $id, Request $request)
|
||||
{
|
||||
$import = $this->imports->findVisible($id);
|
||||
$parent = null;
|
||||
|
||||
if ($import->type === 'page' || $import->type === 'chapter') {
|
||||
session()->setPreviousUrl($import->getUrl());
|
||||
$data = $this->validate($request, [
|
||||
'parent' => ['required', 'string'],
|
||||
]);
|
||||
$parent = $data['parent'];
|
||||
}
|
||||
|
||||
try {
|
||||
$entity = $this->imports->runImport($import, $parent);
|
||||
} catch (ZipImportException $exception) {
|
||||
session()->forget(['success', 'warning']);
|
||||
$this->showErrorNotification(trans('errors.import_zip_failed_notification'));
|
||||
return redirect($import->getUrl())->with('import_errors', $exception->errors);
|
||||
}
|
||||
|
||||
return redirect($entity->getUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an active pending import from the filesystem and database.
|
||||
*/
|
||||
public function delete(int $id)
|
||||
{
|
||||
$import = $this->imports->findVisible($id);
|
||||
$this->imports->deleteImport($import);
|
||||
|
||||
return redirect('/import');
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Entities\Controllers;
|
||||
namespace BookStack\Exports\Controllers;
|
||||
|
||||
use BookStack\Entities\Queries\PageQueries;
|
||||
use BookStack\Entities\Tools\ExportFormatter;
|
||||
use BookStack\Exports\ExportFormatter;
|
||||
use BookStack\Exports\ZipExports\ZipExportBuilder;
|
||||
use BookStack\Http\ApiController;
|
||||
use Throwable;
|
||||
|
||||
@@ -63,4 +64,15 @@ class PageExportApiController extends ApiController
|
||||
|
||||
return $this->download()->directly($markdown, $page->slug . '.md');
|
||||
}
|
||||
|
||||
/**
|
||||
* Export a page as a contained ZIP file.
|
||||
*/
|
||||
public function exportZip(int $id, ZipExportBuilder $builder)
|
||||
{
|
||||
$page = $this->queries->findVisibleByIdOrFail($id);
|
||||
$zip = $builder->buildForPage($page);
|
||||
|
||||
return $this->download()->streamedFileDirectly($zip, $page->slug . '.zip', true);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Entities\Controllers;
|
||||
namespace BookStack\Exports\Controllers;
|
||||
|
||||
use BookStack\Entities\Queries\PageQueries;
|
||||
use BookStack\Entities\Tools\ExportFormatter;
|
||||
use BookStack\Entities\Tools\PageContent;
|
||||
use BookStack\Exceptions\NotFoundException;
|
||||
use BookStack\Exports\ExportFormatter;
|
||||
use BookStack\Exports\ZipExports\ZipExportBuilder;
|
||||
use BookStack\Http\Controller;
|
||||
use Throwable;
|
||||
|
||||
@@ -16,6 +17,7 @@ class PageExportController extends Controller
|
||||
protected ExportFormatter $exportFormatter,
|
||||
) {
|
||||
$this->middleware('can:content-export');
|
||||
$this->middleware('throttle:exports');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -74,4 +76,16 @@ class PageExportController extends Controller
|
||||
|
||||
return $this->download()->directly($pageText, $pageSlug . '.md');
|
||||
}
|
||||
|
||||
/**
|
||||
* Export a page to a contained ZIP export file.
|
||||
* @throws NotFoundException
|
||||
*/
|
||||
public function zip(string $bookSlug, string $pageSlug, ZipExportBuilder $builder)
|
||||
{
|
||||
$page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
|
||||
$zip = $builder->buildForPage($page);
|
||||
|
||||
return $this->download()->streamedFileDirectly($zip, $pageSlug . '.zip', true);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Entities\Tools;
|
||||
namespace BookStack\Exports;
|
||||
|
||||
use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Models\Chapter;
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Entities\Tools\BookContents;
|
||||
use BookStack\Entities\Tools\Markdown\HtmlToMarkdown;
|
||||
use BookStack\Entities\Tools\PageContent;
|
||||
use BookStack\Uploads\ImageService;
|
||||
use BookStack\Util\CspService;
|
||||
use BookStack\Util\HtmlDocument;
|
||||
@@ -315,7 +317,12 @@ class ExportFormatter
|
||||
public function chapterToMarkdown(Chapter $chapter): string
|
||||
{
|
||||
$text = '# ' . $chapter->name . "\n\n";
|
||||
$text .= $chapter->description . "\n\n";
|
||||
|
||||
$description = (new HtmlToMarkdown($chapter->descriptionHtml()))->convert();
|
||||
if ($description) {
|
||||
$text .= $description . "\n\n";
|
||||
}
|
||||
|
||||
foreach ($chapter->pages as $page) {
|
||||
$text .= $this->pageToMarkdown($page) . "\n\n";
|
||||
}
|
||||
@@ -330,6 +337,12 @@ class ExportFormatter
|
||||
{
|
||||
$bookTree = (new BookContents($book))->getTree(false, true);
|
||||
$text = '# ' . $book->name . "\n\n";
|
||||
|
||||
$description = (new HtmlToMarkdown($book->descriptionHtml()))->convert();
|
||||
if ($description) {
|
||||
$text .= $description . "\n\n";
|
||||
}
|
||||
|
||||
foreach ($bookTree as $bookChild) {
|
||||
if ($bookChild instanceof Chapter) {
|
||||
$text .= $this->chapterToMarkdown($bookChild) . "\n\n";
|
||||
68
app/Exports/Import.php
Normal file
68
app/Exports/Import.php
Normal file
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports;
|
||||
|
||||
use BookStack\Activity\Models\Loggable;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportBook;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportChapter;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportPage;
|
||||
use BookStack\Users\Models\User;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* @property int $id
|
||||
* @property string $path
|
||||
* @property string $name
|
||||
* @property int $size - ZIP size in bytes
|
||||
* @property string $type
|
||||
* @property string $metadata
|
||||
* @property int $created_by
|
||||
* @property Carbon $created_at
|
||||
* @property Carbon $updated_at
|
||||
* @property User $createdBy
|
||||
*/
|
||||
class Import extends Model implements Loggable
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $hidden = ['metadata'];
|
||||
|
||||
public function getSizeString(): string
|
||||
{
|
||||
$mb = round($this->size / 1000000, 2);
|
||||
return "{$mb} MB";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the URL to view/continue this import.
|
||||
*/
|
||||
public function getUrl(string $path = ''): string
|
||||
{
|
||||
$path = ltrim($path, '/');
|
||||
return url("/import/{$this->id}" . ($path ? '/' . $path : ''));
|
||||
}
|
||||
|
||||
public function logDescriptor(): string
|
||||
{
|
||||
return "({$this->id}) {$this->name}";
|
||||
}
|
||||
|
||||
public function createdBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'created_by');
|
||||
}
|
||||
|
||||
public function decodeMetadata(): ZipExportBook|ZipExportChapter|ZipExportPage|null
|
||||
{
|
||||
$metadataArray = json_decode($this->metadata, true);
|
||||
return match ($this->type) {
|
||||
'book' => ZipExportBook::fromArray($metadataArray),
|
||||
'chapter' => ZipExportChapter::fromArray($metadataArray),
|
||||
'page' => ZipExportPage::fromArray($metadataArray),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
143
app/Exports/ImportRepo.php
Normal file
143
app/Exports/ImportRepo.php
Normal file
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports;
|
||||
|
||||
use BookStack\Activity\ActivityType;
|
||||
use BookStack\Entities\Models\Entity;
|
||||
use BookStack\Entities\Queries\EntityQueries;
|
||||
use BookStack\Exceptions\FileUploadException;
|
||||
use BookStack\Exceptions\ZipExportException;
|
||||
use BookStack\Exceptions\ZipImportException;
|
||||
use BookStack\Exceptions\ZipValidationException;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportBook;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportChapter;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportPage;
|
||||
use BookStack\Exports\ZipExports\ZipExportReader;
|
||||
use BookStack\Exports\ZipExports\ZipExportValidator;
|
||||
use BookStack\Exports\ZipExports\ZipImportRunner;
|
||||
use BookStack\Facades\Activity;
|
||||
use BookStack\Uploads\FileStorage;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpFoundation\File\UploadedFile;
|
||||
|
||||
class ImportRepo
|
||||
{
|
||||
public function __construct(
|
||||
protected FileStorage $storage,
|
||||
protected ZipImportRunner $importer,
|
||||
protected EntityQueries $entityQueries,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<Import>
|
||||
*/
|
||||
public function getVisibleImports(): Collection
|
||||
{
|
||||
return $this->queryVisible()->get();
|
||||
}
|
||||
|
||||
public function queryVisible(): Builder
|
||||
{
|
||||
$query = Import::query();
|
||||
|
||||
if (!userCan('settings-manage')) {
|
||||
$query->where('created_by', user()->id);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
public function findVisible(int $id): Import
|
||||
{
|
||||
$query = Import::query();
|
||||
|
||||
if (!userCan('settings-manage')) {
|
||||
$query->where('created_by', user()->id);
|
||||
}
|
||||
|
||||
return $query->findOrFail($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws FileUploadException
|
||||
* @throws ZipValidationException
|
||||
* @throws ZipExportException
|
||||
*/
|
||||
public function storeFromUpload(UploadedFile $file): Import
|
||||
{
|
||||
$zipPath = $file->getRealPath();
|
||||
$reader = new ZipExportReader($zipPath);
|
||||
|
||||
$errors = (new ZipExportValidator($reader))->validate();
|
||||
if ($errors) {
|
||||
throw new ZipValidationException($errors);
|
||||
}
|
||||
|
||||
$exportModel = $reader->decodeDataToExportModel();
|
||||
|
||||
$import = new Import();
|
||||
$import->type = match (get_class($exportModel)) {
|
||||
ZipExportPage::class => 'page',
|
||||
ZipExportChapter::class => 'chapter',
|
||||
ZipExportBook::class => 'book',
|
||||
};
|
||||
|
||||
$import->name = $exportModel->name;
|
||||
$import->created_by = user()->id;
|
||||
$import->size = filesize($zipPath);
|
||||
|
||||
$exportModel->metadataOnly();
|
||||
$import->metadata = json_encode($exportModel);
|
||||
|
||||
$path = $this->storage->uploadFile(
|
||||
$file,
|
||||
'uploads/files/imports/',
|
||||
'',
|
||||
'zip'
|
||||
);
|
||||
|
||||
$import->path = $path;
|
||||
$import->save();
|
||||
|
||||
Activity::add(ActivityType::IMPORT_CREATE, $import);
|
||||
|
||||
return $import;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ZipImportException
|
||||
*/
|
||||
public function runImport(Import $import, ?string $parent = null): Entity
|
||||
{
|
||||
$parentModel = null;
|
||||
if ($import->type === 'page' || $import->type === 'chapter') {
|
||||
$parentModel = $parent ? $this->entityQueries->findVisibleByStringIdentifier($parent) : null;
|
||||
}
|
||||
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
$model = $this->importer->run($import, $parentModel);
|
||||
} catch (ZipImportException $e) {
|
||||
DB::rollBack();
|
||||
$this->importer->revertStoredFiles();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
$this->deleteImport($import);
|
||||
Activity::add(ActivityType::IMPORT_RUN, $import);
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
public function deleteImport(Import $import): void
|
||||
{
|
||||
$this->storage->delete($import->path);
|
||||
$import->delete();
|
||||
|
||||
Activity::add(ActivityType::IMPORT_DELETE, $import);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Entities\Tools;
|
||||
namespace BookStack\Exports;
|
||||
|
||||
use BookStack\Exceptions\PdfExportException;
|
||||
use Knp\Snappy\Pdf as SnappyPdf;
|
||||
use Dompdf\Dompdf;
|
||||
use Knp\Snappy\Pdf as SnappyPdf;
|
||||
use Symfony\Component\Process\Exception\ProcessTimedOutException;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
@@ -90,18 +90,28 @@ class PdfGenerator
|
||||
$process = Process::fromShellCommandline($command);
|
||||
$process->setTimeout($timeout);
|
||||
|
||||
$cleanup = function () use ($inputHtml, $outputPdf) {
|
||||
foreach ([$inputHtml, $outputPdf] as $file) {
|
||||
if (file_exists($file)) {
|
||||
unlink($file);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
$process->run();
|
||||
} catch (ProcessTimedOutException $e) {
|
||||
$cleanup();
|
||||
throw new PdfExportException("PDF Export via command failed due to timeout at {$timeout} second(s)");
|
||||
}
|
||||
|
||||
if (!$process->isSuccessful()) {
|
||||
$cleanup();
|
||||
throw new PdfExportException("PDF Export via command failed with exit code {$process->getExitCode()}, stdout: {$process->getOutput()}, stderr: {$process->getErrorOutput()}");
|
||||
}
|
||||
|
||||
$pdfContents = file_get_contents($outputPdf);
|
||||
unlink($outputPdf);
|
||||
$cleanup();
|
||||
|
||||
if ($pdfContents === false) {
|
||||
throw new PdfExportException("PDF Export via command failed, unable to read PDF output file");
|
||||
66
app/Exports/ZipExports/Models/ZipExportAttachment.php
Normal file
66
app/Exports/ZipExports/Models/ZipExportAttachment.php
Normal file
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports\ZipExports\Models;
|
||||
|
||||
use BookStack\Exports\ZipExports\ZipExportFiles;
|
||||
use BookStack\Exports\ZipExports\ZipValidationHelper;
|
||||
use BookStack\Uploads\Attachment;
|
||||
|
||||
class ZipExportAttachment extends ZipExportModel
|
||||
{
|
||||
public ?int $id = null;
|
||||
public string $name;
|
||||
public ?string $link = null;
|
||||
public ?string $file = null;
|
||||
|
||||
public function metadataOnly(): void
|
||||
{
|
||||
$this->link = $this->file = null;
|
||||
}
|
||||
|
||||
public static function fromModel(Attachment $model, ZipExportFiles $files): self
|
||||
{
|
||||
$instance = new self();
|
||||
$instance->id = $model->id;
|
||||
$instance->name = $model->name;
|
||||
|
||||
if ($model->external) {
|
||||
$instance->link = $model->path;
|
||||
} else {
|
||||
$instance->file = $files->referenceForAttachment($model);
|
||||
}
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
public static function fromModelArray(array $attachmentArray, ZipExportFiles $files): array
|
||||
{
|
||||
return array_values(array_map(function (Attachment $attachment) use ($files) {
|
||||
return self::fromModel($attachment, $files);
|
||||
}, $attachmentArray));
|
||||
}
|
||||
|
||||
public static function validate(ZipValidationHelper $context, array $data): array
|
||||
{
|
||||
$rules = [
|
||||
'id' => ['nullable', 'int', $context->uniqueIdRule('attachment')],
|
||||
'name' => ['required', 'string', 'min:1'],
|
||||
'link' => ['required_without:file', 'nullable', 'string'],
|
||||
'file' => ['required_without:link', 'nullable', 'string', $context->fileReferenceRule()],
|
||||
];
|
||||
|
||||
return $context->validateData($data, $rules);
|
||||
}
|
||||
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
$model = new self();
|
||||
|
||||
$model->id = $data['id'] ?? null;
|
||||
$model->name = $data['name'];
|
||||
$model->link = $data['link'] ?? null;
|
||||
$model->file = $data['file'] ?? null;
|
||||
|
||||
return $model;
|
||||
}
|
||||
}
|
||||
118
app/Exports/ZipExports/Models/ZipExportBook.php
Normal file
118
app/Exports/ZipExports/Models/ZipExportBook.php
Normal file
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports\ZipExports\Models;
|
||||
|
||||
use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Models\Chapter;
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Exports\ZipExports\ZipExportFiles;
|
||||
use BookStack\Exports\ZipExports\ZipValidationHelper;
|
||||
|
||||
class ZipExportBook extends ZipExportModel
|
||||
{
|
||||
public ?int $id = null;
|
||||
public string $name;
|
||||
public ?string $description_html = null;
|
||||
public ?string $cover = null;
|
||||
/** @var ZipExportChapter[] */
|
||||
public array $chapters = [];
|
||||
/** @var ZipExportPage[] */
|
||||
public array $pages = [];
|
||||
/** @var ZipExportTag[] */
|
||||
public array $tags = [];
|
||||
|
||||
public function metadataOnly(): void
|
||||
{
|
||||
$this->description_html = $this->cover = null;
|
||||
|
||||
foreach ($this->chapters as $chapter) {
|
||||
$chapter->metadataOnly();
|
||||
}
|
||||
foreach ($this->pages as $page) {
|
||||
$page->metadataOnly();
|
||||
}
|
||||
foreach ($this->tags as $tag) {
|
||||
$tag->metadataOnly();
|
||||
}
|
||||
}
|
||||
|
||||
public function children(): array
|
||||
{
|
||||
$children = [
|
||||
...$this->pages,
|
||||
...$this->chapters,
|
||||
];
|
||||
|
||||
usort($children, function ($a, $b) {
|
||||
return ($a->priority ?? 0) - ($b->priority ?? 0);
|
||||
});
|
||||
|
||||
return $children;
|
||||
}
|
||||
|
||||
public static function fromModel(Book $model, ZipExportFiles $files): self
|
||||
{
|
||||
$instance = new self();
|
||||
$instance->id = $model->id;
|
||||
$instance->name = $model->name;
|
||||
$instance->description_html = $model->descriptionHtml();
|
||||
|
||||
if ($model->cover) {
|
||||
$instance->cover = $files->referenceForImage($model->cover);
|
||||
}
|
||||
|
||||
$instance->tags = ZipExportTag::fromModelArray($model->tags()->get()->all());
|
||||
|
||||
$chapters = [];
|
||||
$pages = [];
|
||||
|
||||
$children = $model->getDirectVisibleChildren()->all();
|
||||
foreach ($children as $child) {
|
||||
if ($child instanceof Chapter) {
|
||||
$chapters[] = $child;
|
||||
} else if ($child instanceof Page && !$child->draft) {
|
||||
$pages[] = $child;
|
||||
}
|
||||
}
|
||||
|
||||
$instance->pages = ZipExportPage::fromModelArray($pages, $files);
|
||||
$instance->chapters = ZipExportChapter::fromModelArray($chapters, $files);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
public static function validate(ZipValidationHelper $context, array $data): array
|
||||
{
|
||||
$rules = [
|
||||
'id' => ['nullable', 'int', $context->uniqueIdRule('book')],
|
||||
'name' => ['required', 'string', 'min:1'],
|
||||
'description_html' => ['nullable', 'string'],
|
||||
'cover' => ['nullable', 'string', $context->fileReferenceRule()],
|
||||
'tags' => ['array'],
|
||||
'pages' => ['array'],
|
||||
'chapters' => ['array'],
|
||||
];
|
||||
|
||||
$errors = $context->validateData($data, $rules);
|
||||
$errors['tags'] = $context->validateRelations($data['tags'] ?? [], ZipExportTag::class);
|
||||
$errors['pages'] = $context->validateRelations($data['pages'] ?? [], ZipExportPage::class);
|
||||
$errors['chapters'] = $context->validateRelations($data['chapters'] ?? [], ZipExportChapter::class);
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
$model = new self();
|
||||
|
||||
$model->id = $data['id'] ?? null;
|
||||
$model->name = $data['name'];
|
||||
$model->description_html = $data['description_html'] ?? null;
|
||||
$model->cover = $data['cover'] ?? null;
|
||||
$model->tags = ZipExportTag::fromManyArray($data['tags'] ?? []);
|
||||
$model->pages = ZipExportPage::fromManyArray($data['pages'] ?? []);
|
||||
$model->chapters = ZipExportChapter::fromManyArray($data['chapters'] ?? []);
|
||||
|
||||
return $model;
|
||||
}
|
||||
}
|
||||
95
app/Exports/ZipExports/Models/ZipExportChapter.php
Normal file
95
app/Exports/ZipExports/Models/ZipExportChapter.php
Normal file
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports\ZipExports\Models;
|
||||
|
||||
use BookStack\Entities\Models\Chapter;
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Exports\ZipExports\ZipExportFiles;
|
||||
use BookStack\Exports\ZipExports\ZipValidationHelper;
|
||||
|
||||
class ZipExportChapter extends ZipExportModel
|
||||
{
|
||||
public ?int $id = null;
|
||||
public string $name;
|
||||
public ?string $description_html = null;
|
||||
public ?int $priority = null;
|
||||
/** @var ZipExportPage[] */
|
||||
public array $pages = [];
|
||||
/** @var ZipExportTag[] */
|
||||
public array $tags = [];
|
||||
|
||||
public function metadataOnly(): void
|
||||
{
|
||||
$this->description_html = null;
|
||||
|
||||
foreach ($this->pages as $page) {
|
||||
$page->metadataOnly();
|
||||
}
|
||||
foreach ($this->tags as $tag) {
|
||||
$tag->metadataOnly();
|
||||
}
|
||||
}
|
||||
|
||||
public function children(): array
|
||||
{
|
||||
return $this->pages;
|
||||
}
|
||||
|
||||
public static function fromModel(Chapter $model, ZipExportFiles $files): self
|
||||
{
|
||||
$instance = new self();
|
||||
$instance->id = $model->id;
|
||||
$instance->name = $model->name;
|
||||
$instance->description_html = $model->descriptionHtml();
|
||||
$instance->priority = $model->priority;
|
||||
$instance->tags = ZipExportTag::fromModelArray($model->tags()->get()->all());
|
||||
|
||||
$pages = $model->getVisiblePages()->filter(fn (Page $page) => !$page->draft)->all();
|
||||
$instance->pages = ZipExportPage::fromModelArray($pages, $files);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Chapter[] $chapterArray
|
||||
* @return self[]
|
||||
*/
|
||||
public static function fromModelArray(array $chapterArray, ZipExportFiles $files): array
|
||||
{
|
||||
return array_values(array_map(function (Chapter $chapter) use ($files) {
|
||||
return self::fromModel($chapter, $files);
|
||||
}, $chapterArray));
|
||||
}
|
||||
|
||||
public static function validate(ZipValidationHelper $context, array $data): array
|
||||
{
|
||||
$rules = [
|
||||
'id' => ['nullable', 'int', $context->uniqueIdRule('chapter')],
|
||||
'name' => ['required', 'string', 'min:1'],
|
||||
'description_html' => ['nullable', 'string'],
|
||||
'priority' => ['nullable', 'int'],
|
||||
'tags' => ['array'],
|
||||
'pages' => ['array'],
|
||||
];
|
||||
|
||||
$errors = $context->validateData($data, $rules);
|
||||
$errors['tags'] = $context->validateRelations($data['tags'] ?? [], ZipExportTag::class);
|
||||
$errors['pages'] = $context->validateRelations($data['pages'] ?? [], ZipExportPage::class);
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
$model = new self();
|
||||
|
||||
$model->id = $data['id'] ?? null;
|
||||
$model->name = $data['name'];
|
||||
$model->description_html = $data['description_html'] ?? null;
|
||||
$model->priority = isset($data['priority']) ? intval($data['priority']) : null;
|
||||
$model->tags = ZipExportTag::fromManyArray($data['tags'] ?? []);
|
||||
$model->pages = ZipExportPage::fromManyArray($data['pages'] ?? []);
|
||||
|
||||
return $model;
|
||||
}
|
||||
}
|
||||
57
app/Exports/ZipExports/Models/ZipExportImage.php
Normal file
57
app/Exports/ZipExports/Models/ZipExportImage.php
Normal file
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports\ZipExports\Models;
|
||||
|
||||
use BookStack\Exports\ZipExports\ZipExportFiles;
|
||||
use BookStack\Exports\ZipExports\ZipValidationHelper;
|
||||
use BookStack\Uploads\Image;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class ZipExportImage extends ZipExportModel
|
||||
{
|
||||
public ?int $id = null;
|
||||
public string $name;
|
||||
public string $file;
|
||||
public string $type;
|
||||
|
||||
public static function fromModel(Image $model, ZipExportFiles $files): self
|
||||
{
|
||||
$instance = new self();
|
||||
$instance->id = $model->id;
|
||||
$instance->name = $model->name;
|
||||
$instance->type = $model->type;
|
||||
$instance->file = $files->referenceForImage($model);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
public function metadataOnly(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
public static function validate(ZipValidationHelper $context, array $data): array
|
||||
{
|
||||
$acceptedImageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
|
||||
$rules = [
|
||||
'id' => ['nullable', 'int', $context->uniqueIdRule('image')],
|
||||
'name' => ['required', 'string', 'min:1'],
|
||||
'file' => ['required', 'string', $context->fileReferenceRule($acceptedImageTypes)],
|
||||
'type' => ['required', 'string', Rule::in(['gallery', 'drawio'])],
|
||||
];
|
||||
|
||||
return $context->validateData($data, $rules);
|
||||
}
|
||||
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
$model = new self();
|
||||
|
||||
$model->id = $data['id'] ?? null;
|
||||
$model->name = $data['name'];
|
||||
$model->file = $data['file'];
|
||||
$model->type = $data['type'];
|
||||
|
||||
return $model;
|
||||
}
|
||||
}
|
||||
57
app/Exports/ZipExports/Models/ZipExportModel.php
Normal file
57
app/Exports/ZipExports/Models/ZipExportModel.php
Normal file
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports\ZipExports\Models;
|
||||
|
||||
use BookStack\Exports\ZipExports\ZipValidationHelper;
|
||||
use JsonSerializable;
|
||||
|
||||
abstract class ZipExportModel implements JsonSerializable
|
||||
{
|
||||
/**
|
||||
* Handle the serialization to JSON.
|
||||
* For these exports, we filter out optional (represented as nullable) fields
|
||||
* just to clean things up and prevent confusion to avoid null states in the
|
||||
* resulting export format itself.
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
$publicProps = get_object_vars(...)->__invoke($this);
|
||||
return array_filter($publicProps, fn ($value) => $value !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the given array of data intended for this model.
|
||||
* Return an array of validation errors messages.
|
||||
* Child items can be considered in the validation result by returning a keyed
|
||||
* item in the array for its own validation messages.
|
||||
*/
|
||||
abstract public static function validate(ZipValidationHelper $context, array $data): array;
|
||||
|
||||
/**
|
||||
* Decode the array of data into this export model.
|
||||
*/
|
||||
abstract public static function fromArray(array $data): self;
|
||||
|
||||
/**
|
||||
* Decode an array of array data into an array of export models.
|
||||
* @param array[] $data
|
||||
* @return self[]
|
||||
*/
|
||||
public static function fromManyArray(array $data): array
|
||||
{
|
||||
$results = [];
|
||||
foreach ($data as $item) {
|
||||
$results[] = static::fromArray($item);
|
||||
}
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove additional content in this model to reduce it down
|
||||
* to just essential id/name values for identification.
|
||||
*
|
||||
* The result of this may be something that does not pass validation, but is
|
||||
* simple for the purpose of creating a contents.
|
||||
*/
|
||||
abstract public function metadataOnly(): void;
|
||||
}
|
||||
104
app/Exports/ZipExports/Models/ZipExportPage.php
Normal file
104
app/Exports/ZipExports/Models/ZipExportPage.php
Normal file
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports\ZipExports\Models;
|
||||
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Entities\Tools\PageContent;
|
||||
use BookStack\Exports\ZipExports\ZipExportFiles;
|
||||
use BookStack\Exports\ZipExports\ZipValidationHelper;
|
||||
|
||||
class ZipExportPage extends ZipExportModel
|
||||
{
|
||||
public ?int $id = null;
|
||||
public string $name;
|
||||
public ?string $html = null;
|
||||
public ?string $markdown = null;
|
||||
public ?int $priority = null;
|
||||
/** @var ZipExportAttachment[] */
|
||||
public array $attachments = [];
|
||||
/** @var ZipExportImage[] */
|
||||
public array $images = [];
|
||||
/** @var ZipExportTag[] */
|
||||
public array $tags = [];
|
||||
|
||||
public function metadataOnly(): void
|
||||
{
|
||||
$this->html = $this->markdown = null;
|
||||
|
||||
foreach ($this->attachments as $attachment) {
|
||||
$attachment->metadataOnly();
|
||||
}
|
||||
foreach ($this->images as $image) {
|
||||
$image->metadataOnly();
|
||||
}
|
||||
foreach ($this->tags as $tag) {
|
||||
$tag->metadataOnly();
|
||||
}
|
||||
}
|
||||
|
||||
public static function fromModel(Page $model, ZipExportFiles $files): self
|
||||
{
|
||||
$instance = new self();
|
||||
$instance->id = $model->id;
|
||||
$instance->name = $model->name;
|
||||
$instance->html = (new PageContent($model))->render();
|
||||
$instance->priority = $model->priority;
|
||||
|
||||
if (!empty($model->markdown)) {
|
||||
$instance->markdown = $model->markdown;
|
||||
}
|
||||
|
||||
$instance->tags = ZipExportTag::fromModelArray($model->tags()->get()->all());
|
||||
$instance->attachments = ZipExportAttachment::fromModelArray($model->attachments()->get()->all(), $files);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Page[] $pageArray
|
||||
* @return self[]
|
||||
*/
|
||||
public static function fromModelArray(array $pageArray, ZipExportFiles $files): array
|
||||
{
|
||||
return array_values(array_map(function (Page $page) use ($files) {
|
||||
return self::fromModel($page, $files);
|
||||
}, $pageArray));
|
||||
}
|
||||
|
||||
public static function validate(ZipValidationHelper $context, array $data): array
|
||||
{
|
||||
$rules = [
|
||||
'id' => ['nullable', 'int', $context->uniqueIdRule('page')],
|
||||
'name' => ['required', 'string', 'min:1'],
|
||||
'html' => ['nullable', 'string'],
|
||||
'markdown' => ['nullable', 'string'],
|
||||
'priority' => ['nullable', 'int'],
|
||||
'attachments' => ['array'],
|
||||
'images' => ['array'],
|
||||
'tags' => ['array'],
|
||||
];
|
||||
|
||||
$errors = $context->validateData($data, $rules);
|
||||
$errors['attachments'] = $context->validateRelations($data['attachments'] ?? [], ZipExportAttachment::class);
|
||||
$errors['images'] = $context->validateRelations($data['images'] ?? [], ZipExportImage::class);
|
||||
$errors['tags'] = $context->validateRelations($data['tags'] ?? [], ZipExportTag::class);
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
$model = new self();
|
||||
|
||||
$model->id = $data['id'] ?? null;
|
||||
$model->name = $data['name'];
|
||||
$model->html = $data['html'] ?? null;
|
||||
$model->markdown = $data['markdown'] ?? null;
|
||||
$model->priority = isset($data['priority']) ? intval($data['priority']) : null;
|
||||
$model->attachments = ZipExportAttachment::fromManyArray($data['attachments'] ?? []);
|
||||
$model->images = ZipExportImage::fromManyArray($data['images'] ?? []);
|
||||
$model->tags = ZipExportTag::fromManyArray($data['tags'] ?? []);
|
||||
|
||||
return $model;
|
||||
}
|
||||
}
|
||||
51
app/Exports/ZipExports/Models/ZipExportTag.php
Normal file
51
app/Exports/ZipExports/Models/ZipExportTag.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports\ZipExports\Models;
|
||||
|
||||
use BookStack\Activity\Models\Tag;
|
||||
use BookStack\Exports\ZipExports\ZipValidationHelper;
|
||||
|
||||
class ZipExportTag extends ZipExportModel
|
||||
{
|
||||
public string $name;
|
||||
public ?string $value = null;
|
||||
|
||||
public function metadataOnly(): void
|
||||
{
|
||||
$this->value = null;
|
||||
}
|
||||
|
||||
public static function fromModel(Tag $model): self
|
||||
{
|
||||
$instance = new self();
|
||||
$instance->name = $model->name;
|
||||
$instance->value = $model->value;
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
public static function fromModelArray(array $tagArray): array
|
||||
{
|
||||
return array_values(array_map(self::fromModel(...), $tagArray));
|
||||
}
|
||||
|
||||
public static function validate(ZipValidationHelper $context, array $data): array
|
||||
{
|
||||
$rules = [
|
||||
'name' => ['required', 'string', 'min:1'],
|
||||
'value' => ['nullable', 'string'],
|
||||
];
|
||||
|
||||
return $context->validateData($data, $rules);
|
||||
}
|
||||
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
$model = new self();
|
||||
|
||||
$model->name = $data['name'];
|
||||
$model->value = $data['value'] ?? null;
|
||||
|
||||
return $model;
|
||||
}
|
||||
}
|
||||
118
app/Exports/ZipExports/ZipExportBuilder.php
Normal file
118
app/Exports/ZipExports/ZipExportBuilder.php
Normal file
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports\ZipExports;
|
||||
|
||||
use BookStack\App\AppVersion;
|
||||
use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Models\Chapter;
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Exceptions\ZipExportException;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportBook;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportChapter;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportPage;
|
||||
use ZipArchive;
|
||||
|
||||
class ZipExportBuilder
|
||||
{
|
||||
protected array $data = [];
|
||||
|
||||
public function __construct(
|
||||
protected ZipExportFiles $files,
|
||||
protected ZipExportReferences $references,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ZipExportException
|
||||
*/
|
||||
public function buildForPage(Page $page): string
|
||||
{
|
||||
$exportPage = ZipExportPage::fromModel($page, $this->files);
|
||||
$this->data['page'] = $exportPage;
|
||||
|
||||
$this->references->addPage($exportPage);
|
||||
|
||||
return $this->build();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ZipExportException
|
||||
*/
|
||||
public function buildForChapter(Chapter $chapter): string
|
||||
{
|
||||
$exportChapter = ZipExportChapter::fromModel($chapter, $this->files);
|
||||
$this->data['chapter'] = $exportChapter;
|
||||
|
||||
$this->references->addChapter($exportChapter);
|
||||
|
||||
return $this->build();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ZipExportException
|
||||
*/
|
||||
public function buildForBook(Book $book): string
|
||||
{
|
||||
$exportBook = ZipExportBook::fromModel($book, $this->files);
|
||||
$this->data['book'] = $exportBook;
|
||||
|
||||
$this->references->addBook($exportBook);
|
||||
|
||||
return $this->build();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ZipExportException
|
||||
*/
|
||||
protected function build(): string
|
||||
{
|
||||
$this->references->buildReferences($this->files);
|
||||
|
||||
$this->data['exported_at'] = date(DATE_ATOM);
|
||||
$this->data['instance'] = [
|
||||
'id' => setting('instance-id', ''),
|
||||
'version' => AppVersion::get(),
|
||||
];
|
||||
|
||||
$zipFile = tempnam(sys_get_temp_dir(), 'bszip-');
|
||||
$zip = new ZipArchive();
|
||||
$opened = $zip->open($zipFile, ZipArchive::OVERWRITE);
|
||||
if ($opened !== true) {
|
||||
throw new ZipExportException('Failed to create zip file for export.');
|
||||
}
|
||||
|
||||
$zip->addFromString('data.json', json_encode($this->data));
|
||||
$zip->addEmptyDir('files');
|
||||
|
||||
$toRemove = [];
|
||||
$addedNames = [];
|
||||
|
||||
try {
|
||||
$this->files->extractEach(function ($filePath, $fileRef) use ($zip, &$toRemove, &$addedNames) {
|
||||
$entryName = "files/$fileRef";
|
||||
$zip->addFile($filePath, $entryName);
|
||||
$toRemove[] = $filePath;
|
||||
$addedNames[] = $entryName;
|
||||
});
|
||||
} catch (\Exception $exception) {
|
||||
// Cleanup the files we've processed so far and respond back with error
|
||||
foreach ($toRemove as $file) {
|
||||
unlink($file);
|
||||
}
|
||||
foreach ($addedNames as $name) {
|
||||
$zip->deleteName($name);
|
||||
}
|
||||
$zip->close();
|
||||
unlink($zipFile);
|
||||
throw new ZipExportException("Failed to add files for ZIP export, received error: " . $exception->getMessage());
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
|
||||
foreach ($toRemove as $file) {
|
||||
unlink($file);
|
||||
}
|
||||
|
||||
return $zipFile;
|
||||
}
|
||||
}
|
||||
107
app/Exports/ZipExports/ZipExportFiles.php
Normal file
107
app/Exports/ZipExports/ZipExportFiles.php
Normal file
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports\ZipExports;
|
||||
|
||||
use BookStack\Uploads\Attachment;
|
||||
use BookStack\Uploads\AttachmentService;
|
||||
use BookStack\Uploads\Image;
|
||||
use BookStack\Uploads\ImageService;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ZipExportFiles
|
||||
{
|
||||
/**
|
||||
* References for attachments by attachment ID.
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected array $attachmentRefsById = [];
|
||||
|
||||
/**
|
||||
* References for images by image ID.
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected array $imageRefsById = [];
|
||||
|
||||
public function __construct(
|
||||
protected AttachmentService $attachmentService,
|
||||
protected ImageService $imageService,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gain a reference to the given attachment instance.
|
||||
* This is expected to be a file-based attachment that the user
|
||||
* has visibility of, no permission/access checks are performed here.
|
||||
*/
|
||||
public function referenceForAttachment(Attachment $attachment): string
|
||||
{
|
||||
if (isset($this->attachmentRefsById[$attachment->id])) {
|
||||
return $this->attachmentRefsById[$attachment->id];
|
||||
}
|
||||
|
||||
$existingFiles = $this->getAllFileNames();
|
||||
do {
|
||||
$fileName = Str::random(20) . '.' . $attachment->extension;
|
||||
} while (in_array($fileName, $existingFiles));
|
||||
|
||||
$this->attachmentRefsById[$attachment->id] = $fileName;
|
||||
|
||||
return $fileName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gain a reference to the given image instance.
|
||||
* This is expected to be an image that the user has visibility of,
|
||||
* no permission/access checks are performed here.
|
||||
*/
|
||||
public function referenceForImage(Image $image): string
|
||||
{
|
||||
if (isset($this->imageRefsById[$image->id])) {
|
||||
return $this->imageRefsById[$image->id];
|
||||
}
|
||||
|
||||
$existingFiles = $this->getAllFileNames();
|
||||
$extension = pathinfo($image->path, PATHINFO_EXTENSION);
|
||||
do {
|
||||
$fileName = Str::random(20) . '.' . $extension;
|
||||
} while (in_array($fileName, $existingFiles));
|
||||
|
||||
$this->imageRefsById[$image->id] = $fileName;
|
||||
|
||||
return $fileName;
|
||||
}
|
||||
|
||||
protected function getAllFileNames(): array
|
||||
{
|
||||
return array_merge(
|
||||
array_values($this->attachmentRefsById),
|
||||
array_values($this->imageRefsById),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract each of the ZIP export tracked files.
|
||||
* Calls the given callback for each tracked file, passing a temporary
|
||||
* file reference of the file contents, and the zip-local tracked reference.
|
||||
*/
|
||||
public function extractEach(callable $callback): void
|
||||
{
|
||||
foreach ($this->attachmentRefsById as $attachmentId => $ref) {
|
||||
$attachment = Attachment::query()->find($attachmentId);
|
||||
$stream = $this->attachmentService->streamAttachmentFromStorage($attachment);
|
||||
$tmpFile = tempnam(sys_get_temp_dir(), 'bszipfile-');
|
||||
$tmpFileStream = fopen($tmpFile, 'w');
|
||||
stream_copy_to_stream($stream, $tmpFileStream);
|
||||
$callback($tmpFile, $ref);
|
||||
}
|
||||
|
||||
foreach ($this->imageRefsById as $imageId => $ref) {
|
||||
$image = Image::query()->find($imageId);
|
||||
$stream = $this->imageService->getImageStream($image);
|
||||
$tmpFile = tempnam(sys_get_temp_dir(), 'bszipimage-');
|
||||
$tmpFileStream = fopen($tmpFile, 'w');
|
||||
stream_copy_to_stream($stream, $tmpFileStream);
|
||||
$callback($tmpFile, $ref);
|
||||
}
|
||||
}
|
||||
}
|
||||
111
app/Exports/ZipExports/ZipExportReader.php
Normal file
111
app/Exports/ZipExports/ZipExportReader.php
Normal file
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports\ZipExports;
|
||||
|
||||
use BookStack\Exceptions\ZipExportException;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportBook;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportChapter;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportPage;
|
||||
use BookStack\Util\WebSafeMimeSniffer;
|
||||
use ZipArchive;
|
||||
|
||||
class ZipExportReader
|
||||
{
|
||||
protected ZipArchive $zip;
|
||||
protected bool $open = false;
|
||||
|
||||
public function __construct(
|
||||
protected string $zipPath,
|
||||
) {
|
||||
$this->zip = new ZipArchive();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ZipExportException
|
||||
*/
|
||||
protected function open(): void
|
||||
{
|
||||
if ($this->open) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate file exists
|
||||
if (!file_exists($this->zipPath) || !is_readable($this->zipPath)) {
|
||||
throw new ZipExportException(trans('errors.import_zip_cant_read'));
|
||||
}
|
||||
|
||||
// Validate file is valid zip
|
||||
$opened = $this->zip->open($this->zipPath, ZipArchive::RDONLY);
|
||||
if ($opened !== true) {
|
||||
throw new ZipExportException(trans('errors.import_zip_cant_read'));
|
||||
}
|
||||
|
||||
$this->open = true;
|
||||
}
|
||||
|
||||
public function close(): void
|
||||
{
|
||||
if ($this->open) {
|
||||
$this->zip->close();
|
||||
$this->open = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ZipExportException
|
||||
*/
|
||||
public function readData(): array
|
||||
{
|
||||
$this->open();
|
||||
|
||||
// Validate json data exists, including metadata
|
||||
$jsonData = $this->zip->getFromName('data.json') ?: '';
|
||||
$importData = json_decode($jsonData, true);
|
||||
if (!$importData) {
|
||||
throw new ZipExportException(trans('errors.import_zip_cant_decode_data'));
|
||||
}
|
||||
|
||||
return $importData;
|
||||
}
|
||||
|
||||
public function fileExists(string $fileName): bool
|
||||
{
|
||||
return $this->zip->statName("files/{$fileName}") !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return false|resource
|
||||
*/
|
||||
public function streamFile(string $fileName)
|
||||
{
|
||||
return $this->zip->getStream("files/{$fileName}");
|
||||
}
|
||||
|
||||
/**
|
||||
* Sniff the mime type from the file of given name.
|
||||
*/
|
||||
public function sniffFileMime(string $fileName): string
|
||||
{
|
||||
$stream = $this->streamFile($fileName);
|
||||
$sniffContent = fread($stream, 2000);
|
||||
|
||||
return (new WebSafeMimeSniffer())->sniff($sniffContent);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ZipExportException
|
||||
*/
|
||||
public function decodeDataToExportModel(): ZipExportBook|ZipExportChapter|ZipExportPage
|
||||
{
|
||||
$data = $this->readData();
|
||||
if (isset($data['book'])) {
|
||||
return ZipExportBook::fromArray($data['book']);
|
||||
} else if (isset($data['chapter'])) {
|
||||
return ZipExportChapter::fromArray($data['chapter']);
|
||||
} else if (isset($data['page'])) {
|
||||
return ZipExportPage::fromArray($data['page']);
|
||||
}
|
||||
|
||||
throw new ZipExportException("Could not identify content in ZIP file data.");
|
||||
}
|
||||
}
|
||||
160
app/Exports/ZipExports/ZipExportReferences.php
Normal file
160
app/Exports/ZipExports/ZipExportReferences.php
Normal file
@@ -0,0 +1,160 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports\ZipExports;
|
||||
|
||||
use BookStack\App\Model;
|
||||
use BookStack\Entities\Models\Book;
|
||||
use BookStack\Entities\Models\Chapter;
|
||||
use BookStack\Entities\Models\Page;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportAttachment;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportBook;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportChapter;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportImage;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportModel;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportPage;
|
||||
use BookStack\Uploads\Attachment;
|
||||
use BookStack\Uploads\Image;
|
||||
|
||||
class ZipExportReferences
|
||||
{
|
||||
/** @var array<int, ZipExportPage> */
|
||||
protected array $pages = [];
|
||||
/** @var array<int, ZipExportChapter> */
|
||||
protected array $chapters = [];
|
||||
/** @var array<int, ZipExportBook> */
|
||||
protected array $books = [];
|
||||
|
||||
/** @var array<int, ZipExportAttachment> */
|
||||
protected array $attachments = [];
|
||||
|
||||
/** @var array<int, ZipExportImage> */
|
||||
protected array $images = [];
|
||||
|
||||
public function __construct(
|
||||
protected ZipReferenceParser $parser,
|
||||
) {
|
||||
}
|
||||
|
||||
public function addPage(ZipExportPage $page): void
|
||||
{
|
||||
if ($page->id) {
|
||||
$this->pages[$page->id] = $page;
|
||||
}
|
||||
|
||||
foreach ($page->attachments as $attachment) {
|
||||
if ($attachment->id) {
|
||||
$this->attachments[$attachment->id] = $attachment;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function addChapter(ZipExportChapter $chapter): void
|
||||
{
|
||||
if ($chapter->id) {
|
||||
$this->chapters[$chapter->id] = $chapter;
|
||||
}
|
||||
|
||||
foreach ($chapter->pages as $page) {
|
||||
$this->addPage($page);
|
||||
}
|
||||
}
|
||||
|
||||
public function addBook(ZipExportBook $book): void
|
||||
{
|
||||
if ($book->id) {
|
||||
$this->books[$book->id] = $book;
|
||||
}
|
||||
|
||||
foreach ($book->pages as $page) {
|
||||
$this->addPage($page);
|
||||
}
|
||||
|
||||
foreach ($book->chapters as $chapter) {
|
||||
$this->addChapter($chapter);
|
||||
}
|
||||
}
|
||||
|
||||
public function buildReferences(ZipExportFiles $files): void
|
||||
{
|
||||
$createHandler = function (ZipExportModel $zipModel) use ($files) {
|
||||
return function (Model $model) use ($files, $zipModel) {
|
||||
return $this->handleModelReference($model, $zipModel, $files);
|
||||
};
|
||||
};
|
||||
|
||||
// Parse page content first
|
||||
foreach ($this->pages as $page) {
|
||||
$handler = $createHandler($page);
|
||||
$page->html = $this->parser->parseLinks($page->html ?? '', $handler);
|
||||
if ($page->markdown) {
|
||||
$page->markdown = $this->parser->parseLinks($page->markdown, $handler);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse chapter description HTML
|
||||
foreach ($this->chapters as $chapter) {
|
||||
if ($chapter->description_html) {
|
||||
$handler = $createHandler($chapter);
|
||||
$chapter->description_html = $this->parser->parseLinks($chapter->description_html, $handler);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse book description HTML
|
||||
foreach ($this->books as $book) {
|
||||
if ($book->description_html) {
|
||||
$handler = $createHandler($book);
|
||||
$book->description_html = $this->parser->parseLinks($book->description_html, $handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected function handleModelReference(Model $model, ZipExportModel $exportModel, ZipExportFiles $files): ?string
|
||||
{
|
||||
// Handle attachment references
|
||||
// No permission check needed here since they would only already exist in this
|
||||
// reference context if already allowed via their entity access.
|
||||
if ($model instanceof Attachment) {
|
||||
if (isset($this->attachments[$model->id])) {
|
||||
return "[[bsexport:attachment:{$model->id}]]";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Handle image references
|
||||
if ($model instanceof Image) {
|
||||
// Only handle gallery and drawio images
|
||||
if ($model->type !== 'gallery' && $model->type !== 'drawio') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Handle simple links outside of page content
|
||||
if (!($exportModel instanceof ZipExportPage) && isset($this->images[$model->id])) {
|
||||
return "[[bsexport:image:{$model->id}]]";
|
||||
}
|
||||
|
||||
// Find and include images if in visibility
|
||||
$page = $model->getPage();
|
||||
$pageExportModel = $this->pages[$page->id] ?? ($exportModel instanceof ZipExportPage ? $exportModel : null);
|
||||
if (isset($this->images[$model->id]) || ($page && $pageExportModel && userCan('view', $page))) {
|
||||
if (!isset($this->images[$model->id])) {
|
||||
$exportImage = ZipExportImage::fromModel($model, $files);
|
||||
$this->images[$model->id] = $exportImage;
|
||||
$pageExportModel->images[] = $exportImage;
|
||||
}
|
||||
return "[[bsexport:image:{$model->id}]]";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Handle entity references
|
||||
if ($model instanceof Book && isset($this->books[$model->id])) {
|
||||
return "[[bsexport:book:{$model->id}]]";
|
||||
} else if ($model instanceof Chapter && isset($this->chapters[$model->id])) {
|
||||
return "[[bsexport:chapter:{$model->id}]]";
|
||||
} else if ($model instanceof Page && isset($this->pages[$model->id])) {
|
||||
return "[[bsexport:page:{$model->id}]]";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
57
app/Exports/ZipExports/ZipExportValidator.php
Normal file
57
app/Exports/ZipExports/ZipExportValidator.php
Normal file
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Exports\ZipExports;
|
||||
|
||||
use BookStack\Exceptions\ZipExportException;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportBook;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportChapter;
|
||||
use BookStack\Exports\ZipExports\Models\ZipExportPage;
|
||||
|
||||
class ZipExportValidator
|
||||
{
|
||||
public function __construct(
|
||||
protected ZipExportReader $reader,
|
||||
) {
|
||||
}
|
||||
|
||||
public function validate(): array
|
||||
{
|
||||
try {
|
||||
$importData = $this->reader->readData();
|
||||
} catch (ZipExportException $exception) {
|
||||
return ['format' => $exception->getMessage()];
|
||||
}
|
||||
|
||||
$helper = new ZipValidationHelper($this->reader);
|
||||
|
||||
if (isset($importData['book'])) {
|
||||
$modelErrors = ZipExportBook::validate($helper, $importData['book']);
|
||||
$keyPrefix = 'book';
|
||||
} else if (isset($importData['chapter'])) {
|
||||
$modelErrors = ZipExportChapter::validate($helper, $importData['chapter']);
|
||||
$keyPrefix = 'chapter';
|
||||
} else if (isset($importData['page'])) {
|
||||
$modelErrors = ZipExportPage::validate($helper, $importData['page']);
|
||||
$keyPrefix = 'page';
|
||||
} else {
|
||||
return ['format' => trans('errors.import_zip_no_data')];
|
||||
}
|
||||
|
||||
return $this->flattenModelErrors($modelErrors, $keyPrefix);
|
||||
}
|
||||
|
||||
protected function flattenModelErrors(array $errors, string $keyPrefix): array
|
||||
{
|
||||
$flattened = [];
|
||||
|
||||
foreach ($errors as $key => $error) {
|
||||
if (is_array($error)) {
|
||||
$flattened = array_merge($flattened, $this->flattenModelErrors($error, $keyPrefix . '.' . $key));
|
||||
} else {
|
||||
$flattened[$keyPrefix . '.' . $key] = $error;
|
||||
}
|
||||
}
|
||||
|
||||
return $flattened;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user