Compare commits

...

215 Commits

Author SHA1 Message Date
Dan Brown
7e44b195c5 Updated version and assets for release v23.10 2023-10-30 12:15:59 +00:00
Dan Brown
5b45eac5e1 Merge branch 'development' into release 2023-10-30 12:14:23 +00:00
Dan Brown
49b286cd34 Demo mode: Updated my account access to be more selective 2023-10-30 12:07:18 +00:00
Dan Brown
e006f9674f Langs: Updated translators and locale list pre v23.10 2023-10-30 11:41:36 +00:00
Dan Brown
8bffcebd64 Updated translations with latest Crowdin changes (#4523) 2023-10-30 11:16:19 +00:00
Dan Brown
7c4dc981cd Middlware: Prevented caching of all app requests
Previously we'd prevent caching of authed responses for security
(prevent back cache or proxy caching) but caching could still be an
issue in non-auth scenarios due to CSRF (eg. returning to login screen after
session expiry).

For #4600
2023-10-23 13:32:15 +01:00
Dan Brown
9b4f1fb981 Styles: Aligned empty state alignment & consistency
- Fixed inital empty state margins/paddings to be aligned and not differ
when lists are empty.
- Aligned button/action display when viewing empty entities.
- Fixed use of non-existing permission in books for book empty state
  button.

Fixes #4563
2023-10-23 11:53:19 +01:00
Dan Brown
d42af4affc Shortcuts: Prevented help shown when in inputs
For #4606
2023-10-23 11:04:09 +01:00
Dan Brown
8375d341ea Deps: Updated npm and composer packages 2023-10-20 16:39:40 +01:00
Dan Brown
f5756ff28a Security: Swapped twitter for mastodon link 2023-10-19 16:53:02 +01:00
Dan Brown
c513cdaebe Merge pull request #4618 from radiantwave/patch-1
Remove huntr from SECURITY.md
2023-10-19 16:50:30 +01:00
Dan Brown
995b7d61e9 Merge pull request #4615 from BookStackApp/user_account
User preferences/options cleanup
2023-10-19 16:49:06 +01:00
Dan Brown
02bfaffeb4 My Acount: Updated old preference url reference for watches 2023-10-19 16:37:55 +01:00
Daniel
38fe40809b Update SECURITY.md
Remove huntr
2023-10-19 17:12:18 +02:00
Dan Brown
ce53f641ad My Account: Covered profile and auth pages with tests 2023-10-19 16:06:59 +01:00
Dan Brown
f55e7ca3c9 User Account: Ensured page titles for pages and api tokens 2023-10-19 15:24:48 +01:00
Dan Brown
fabc854390 My Account: Updated and started adding to tests
- Updated existing tests now affected by my-account changes.
- Updated some existing tests to more accuractly check the scenario.
- Updated some code styling in SocialController.
- Fixed redirects for social account flows to fit my-account.
- Added test for social account attaching.
- Added test for api token redirect handling.
2023-10-19 14:18:42 +01:00
Dan Brown
12946414b0 API Tokens: Updated interfaces to return to correct location
Since management of API tokens can be accessed via two routes, this adds
tracking and handling to reutrn the user to the correct place.
2023-10-19 11:31:45 +01:00
Dan Brown
f9422dff18 My Account: Added self-delete flow 2023-10-19 10:48:27 +01:00
Dan Brown
cf72e48d2a User form: Always show external auth field, update access control
Updated old user management routes to only be accessible with permission
to manage users, so also removed old content controls checking for that
permission.
2023-10-19 10:20:04 +01:00
Dan Brown
e4ea73ee25 My Account: Cleaned-up/reorganised user header dropdown 2023-10-18 17:57:14 +01:00
Dan Brown
03c44b3992 My Account: Extracted/tweaked profile text, removed old index 2023-10-18 17:53:58 +01:00
Dan Brown
c1b01639c1 My Account: Built out profile page & endpoints
Text currently hard-coded, needs finalising and extracting.
2023-10-18 12:39:57 +01:00
Dan Brown
a868012048 Users: Built out auth page for my-account section 2023-10-17 17:38:07 +01:00
Dan Brown
a9d0f36766 User: Started cleanup of user self-management
- Moved preference views to more general "my-account" area.
- Started new layout for my-account with sidebar.
- Added MFA to prefeences view (to be moved).
2023-10-17 13:11:10 +01:00
Dan Brown
3274181e14 Merge pull request #4604 from BookStackApp/editor_trim_enhancement
Editor design update
2023-10-14 17:30:04 +01:00
Dan Brown
8166e27f2b Editors: Properly aligned edit area border radius 2023-10-14 17:18:09 +01:00
Dan Brown
8ffa436f3d Editors: Adjusted new design for mobile and dark mode
Tested new design across FF, Chrome, and Gnome web (webkit)
2023-10-14 17:10:29 +01:00
Dan Brown
8c10959339 Editors: Tightened up new design, adjusted for MD editor 2023-10-14 16:33:48 +01:00
Dan Brown
45c7409092 Editor: Started toying with more singificant design update 2023-10-13 17:33:11 +01:00
Dan Brown
a12b60e1ad Editor: Started attempts to improve design elements 2023-10-08 15:04:07 +01:00
Dan Brown
ccb3c2516a Homepage: Made much nicer at ipad-like widths
Updated default homepage layout to be much nicer at ipad-like widths by
switching to css-column approach at those breakpoints.
Also neated top actions by switching to simpler flexbox layout.

Fixes #4596
2023-10-07 12:38:54 +01:00
Dan Brown
2e2272343b Merge branch 'LawssssCat/development' into development 2023-10-06 12:03:38 +01:00
Dan Brown
031067745b Layout: Restructured tri-layout for sidebar control
Restructured tri-layout grid system, so the sidebars are contained in
their own child grid system, mimicking the parent grid, so we can treat
them as part of the same parent scroll container at smaller screen
sizes for consistent scroll/sticky behavior.

Tested on Firefox, Chromium, Gnome Web and Safari (MacOS).

For #4394
Changes made during review of #4562
2023-10-06 12:03:38 +01:00
Dan Brown
1267068d9c CI: Added path filtering to actions
In the hope we can make the CI runs a bit more efficient and energy
conscious, by only running when relevant files have changed.
2023-10-04 09:18:24 +01:00
Dan Brown
0241032f06 Tags: Fixed enter press clearing field
For #4570
2023-10-04 09:08:10 +01:00
Dan Brown
bd7c7eb8d6 Print Styles: Removed use of seperate style sheet
Seemed a bit redundant and complicated, since we're only adding a few
extra styles. Just merged into main styles instead.
2023-10-03 15:14:21 +01:00
Dan Brown
c5d5b6e3c1 Print Styles: Fixed header/footer content showing
Extra bits were showing due to recent changes.
Done a quick pass through major display views.

Fixes #4594
2023-10-03 14:59:35 +01:00
Dan Brown
1005f4bd7a Testing: Added favicon cleanup
Was leaving a changed favicon leaving other test to fail.
2023-10-03 14:50:54 +01:00
Dan Brown
b24296e0c9 Added NETWAYS to readme sponsor list
Related to:
edceda5342
2023-10-03 12:10:45 +01:00
Dan Brown
d1f28ed245 Merge branch 'basic-pwa-support' into development 2023-10-02 15:58:07 +01:00
Dan Brown
1d91b4d8a6 PWA Manifest: Tweaks during review of PR #4430
- Updated to go through HomeController with the builder as a helper
  class.
- Extracted some reapeated items into variables in manifest.
- Updated background color to match those used by BookStack.
- Removed reference of icon.ico since its not intended to be used.
- Added tests to cover functionality.

Review of #4430
2023-10-02 15:54:39 +01:00
Dan Brown
8bba5dd5a0 Merge pull request #4578 from BookStackApp/upload_handling
Improvements to file/image upload handling UX
2023-10-01 17:20:10 +00:00
Dan Brown
ffb04a8be6 JS: Fixed ESLint issues 2023-10-01 18:13:54 +01:00
Dan Brown
b2d48d9a7f Images: Rolled out image memory handling to image actions
- Moved thumnbail loading out of repo into ImageResizer.
- Updated gallery and editor image handling to show errors where
  possible to indicate memory issues for resizing/thumbs.
- Updated gallery to load image data in a per-image basis via edit form
  for more resiliant thumb/data fetching. Data was previously provided
  via gallery listing, which could be affected by failing generation
  of other images.
- Updated image manager double click handling to be more pleasant and
  not flash away the edit form.
- Updated editor handlers to use main URL when thumbs fail to load.
2023-10-01 13:05:18 +01:00
Dan Brown
20bcbd76ef Images: Extracted out image resizing to its own class 2023-09-30 20:00:48 +01:00
Dan Brown
e703009d7f Images: Added thin wrapper around image filesystem instances
Extracts duplicated required handling (Like path adjustment) out to
simpler storage disk instance which can be passed around.
2023-09-30 19:12:22 +01:00
Dan Brown
7247e31936 Images: Started refactor of image service
To break it up.
Also added better memory handling to other parts of the app.
2023-09-30 18:28:42 +01:00
Dan Brown
40721433f7 Image manager: Tweaked grid sizing to prevent massive items 2023-09-30 12:43:51 +01:00
Dan Brown
97274a8140 Images: Added test to cover thubmnail regen endpoint 2023-09-30 12:29:49 +01:00
Dan Brown
5c318a45b8 Images: Reverted some thumbnails to be on-demand generated
Added since we can't always be sure of future image usage, and in many
cases we don't generate ahead-of-time.
Also:
- Simplified image handling on certain models.
- Updated various string handling operations to use newer functions.
2023-09-30 12:09:29 +01:00
Dan Brown
5af3041b9b Thumbnails: Added OOM handling and regen endpoint
- Added some level of app out-of-memory handling so we can show a proper
  error message upon OOM events.
- Added endpoint and image-manager button/action for regenerating
  thumbnails for an image so they can be re-created upon failure.
2023-09-29 13:54:08 +01:00
Dan Brown
cc0827ff28 Images: Updated to create thumbnails at specific events 2023-09-29 11:46:32 +01:00
Dan Brown
59da7666b5 Uploads: Added user-facing message for Laravel post limit handling
Uploads over the post max size Would previously error without a
clean user facing message. This catches that error to provide a
user friendly message, compatible with our common error handling.

Tested on image manager handling.
Added test to cover.
2023-09-25 13:48:23 +01:00
JonatanRek
287ed4ff3b Remove Dumps 2023-09-24 20:19:53 +02:00
Dan Brown
21badde4ef Editors: Updated entity link select to pre-fill with selection
Updated all uses across both editors, so the entity link selector popup
now initates a search with the selection text if existing.

For #4571
2023-09-24 18:33:33 +01:00
Dan Brown
e9664dc678 Exports: Fixed issues with book text export format
- Fixed missing page content for direct page children
- Fixed lack of book description.
- Fixed inconsistent spacing between items.
- Fixed lack of spacing between HTML items when HTML on same line.

For #4557
2023-09-24 18:03:37 +01:00
Dan Brown
d5a3bdb7aa Header: Simplified, split and re-orgranised view file(s)
- Moved "common" template partials, that are only used in layouts, to
  layouts/parts folder.
- Simplified HTML structure of header template.
- Extracted logo and links from header template to simplify.
- Added header-links-start template for easier extension/customization
  without needing to override full list of links.
  - Added test to cover usage of this.

For #4564
2023-09-24 10:29:51 +01:00
Dan Brown
c3b4128a38 Homepage: Added tags button to non-default home views
For #4558
2023-09-24 09:31:44 +01:00
Dan Brown
f77bb01b51 Search: Added further backslash handling
Added due to now not being able to perform an exact search where
contains a trailing backslash.
Now all backslashes in exact terms are consided escape chars
and require escaping themselves.
Potential breaking change due to search syntax handling change.

Related to #4535.
2023-09-23 13:41:10 +01:00
Dan Brown
fb417828a4 Readme: Updated badges, sponsors and top links 2023-09-23 12:47:24 +01:00
JonatanRek
57791c1466 Fix Reloading changes on dark mode switch 2023-09-22 11:31:24 +02:00
JonatanRek
46e3b2ceb3 Merge branch 'basic-pwa-support' of https://github.com/GamerClassN7/BookStack into basic-pwa-support 2023-09-22 11:19:38 +02:00
JonatanRek
10e8e1a88d New line fix 2023-09-22 11:19:34 +02:00
JonatanRek
7e09c9a147 Update HomeController.php 2023-09-22 11:19:17 +02:00
JonatanRek
2a2f893fcc Formating Fixes 2023-09-22 11:18:10 +02:00
JonatanRek
9b99664bff Additional Tweaks and FIxes 2023-09-22 11:15:13 +02:00
JonatanRek
f910424fa3 Implementation of required changes 2023-09-22 11:00:41 +02:00
JonatanRek
6e19a8a4bb Merge branch 'basic-pwa-support' of https://github.com/GamerClassN7/BookStack into basic-pwa-support 2023-09-22 10:49:53 +02:00
JonatanRek
cb9c3fc9f5 Fix Dark theme 2023-09-22 10:49:37 +02:00
JonatanRek
effc03e99e Merge branch 'BookStackApp:development' into basic-pwa-support 2023-09-22 10:48:48 +02:00
Dan Brown
8964575973 Search: Added support for escaped exact terms
Also prevented use of empty exact matches.
Prevents issues when attempting to use exact search terms in inputs for
just search terms, and use of single " chars within search terms since
these would get auto-promoted to exacts.

For #4535
2023-09-19 20:09:33 +01:00
Dan Brown
4b4d8ba2a1 Avatar Commend: Simplified and updated during review
During review of #4560.

- Simplified command to share as much log as possible across different
  run options.
- Extracted out user handling to share with MFA command.
- Added specific handling for disabled avatar fetching.
- Added mention of avatar endpoint, to make it clear where these avatars
  are coming from (Protect against user expectation of LDAP avatar sync).
- Simplified a range of the testing.
- Tweaked wording and code formatting.
2023-09-19 15:53:01 +01:00
lawsssscat
588ed785d2 fix Sidebar scrolling at mid-range sceen 2023-09-19 22:12:33 +08:00
Marc Hagen
ca98155373 fix: Actually check if we have correct data 2023-09-18 20:04:59 +02:00
Marc Hagen
ea7592509f feat: Artisan command for updating avatars for existing users 2023-09-18 20:04:28 +02:00
Dan Brown
95b9ea1a21 Dev: Reviewed and expanded on PHP testing docs 2023-09-17 23:41:02 +01:00
Dan Brown
684a9dee8e Merge branch 'tusharnain4578/development' into development 2023-09-17 22:29:06 +01:00
Dan Brown
c42cd29ed3 Notifications: Updated comment notif. prefs. test
Combined testcases, updated to use actual text strings, and set comments
setting via correct method.

Made during review of #4552
2023-09-17 22:26:51 +01:00
Dan Brown
35813e818d Merge pull request #4555 from BookStackApp/language_cleanup
Language cleanup
2023-09-17 22:15:38 +01:00
Dan Brown
78bf11cf65 Locales: Removed a lot of existing locale handling
There was a lot of locale handling to get correct/expected date
formatting within the app.
Carbon now has built-in locale content rather than us needing to target
specific system locales.

This also removes setting locale via Carbon directly.
Carbon registers its own Laravel service provider which seems to
accurately pull the correct locale from the app.

For #4555
2023-09-17 22:02:12 +01:00
Tushar Nain
baa957d980 Update UserPreferencesTest.php
Added Testcases for preferences menu of Comment Notifications visibility when comments are enabled/disabled.
2023-09-17 23:31:01 +05:30
Dan Brown
b42e8cdb63 Locales: Fixed errors occuring for PHP < 8.2 2023-09-17 17:35:00 +01:00
Dan Brown
8994c1b9d9 Locales: More use of locale objects, Addressed failing tests 2023-09-17 16:20:21 +01:00
Dan Brown
ac9a65945f Locales: Performed cleanup and alignment of locale handling
- Reduced app settings down to what's required.
- Used new view-shared $locale object instead of using globals via
  config.
- Aligned language used to default on "locale" instead of mixing
  locale/language.

For #4501
2023-09-17 13:31:38 +01:00
Dan Brown
b292cf7090 Extracted icon helper, aligned container resolution
Also updated breadcrumb view composer to current standards.
Closes #4553
2023-09-16 18:26:28 +01:00
Dan Brown
54791c8627 Merge pull request #4554 from BookStackApp/guest_user_cleanup
Guest control: Cleaned methods involved in fetching/handling
2023-09-16 13:59:16 +01:00
Dan Brown
e16bdf443c Removed redundant null check 2023-09-16 13:49:03 +01:00
Dan Brown
b90033a730 Guest control: Cleaned methods involved in fetching/handling
- Moves guest user caching from User class to app container for
  simplicity.
- Updates test to use simpler $this->users->guest() method for
  consistency.
- Streamlined helpers to avoid function overlap for simplicity.
- Extracted user profile dropdown while doing changes.
2023-09-16 13:18:35 +01:00
Dan Brown
9ac932fc28 Merge branch 'v23-08' into development 2023-09-16 11:55:57 +01:00
Tushar Nain
6a5361d853 Fixed : Comment notification settings are visible even if comments are disabled
Added a UX condition to display comment notification settings, only if the user has enabled the comment notifications.
2023-09-16 14:00:08 +05:30
Dan Brown
c1d30341e7 Updated version and assets for release v23.08.3 2023-09-15 13:49:40 +01:00
Dan Brown
80d2b4913b Merge branch 'v23-08' into release 2023-09-15 13:49:12 +01:00
Dan Brown
45b8d6cd0c Comments: Fixed wrong identification of parent comment
Would cause comment reply notifications to not be sent to expected user.
Updated test to cover problem case.

For #4548
2023-09-15 13:38:02 +01:00
Dan Brown
dfaf6f7c13 Cleanup Command: Allowed running non-interactively
For #4541
2023-09-14 14:17:20 +01:00
Dan Brown
417705651c Dark Mode: Fixed not toggle action when dark by default
Added test to cover.
For #4543.
2023-09-14 13:53:24 +01:00
Dan Brown
4ec600adfa Langs: Added Uzbek, Updated translator attribution
For #4527
2023-09-13 10:52:12 +01:00
Dan Brown
709c182bda Merge branch 'Bajszi97/development' into development 2023-09-13 10:12:49 +01:00
Dan Brown
a452092e40 Reviewed #4533, formatting and tweaks
- Updating formatting.
- Tweaked truncation to roughly match elipsis char to width used.
- Updated testing to use existing helpers, and ran check as admin user
  to avoid name conflicts.
2023-09-13 10:09:33 +01:00
Bajszi
83028f3fbe Test comment creator name truncation 2023-09-12 21:10:25 +02:00
Bajszi
f4deb13301 Truncate with three dots 2023-09-12 21:10:25 +02:00
Dan Brown
6e098905d4 Theme: Added handling for functions.php file load error
This adds specific handling for functions.php error loading to re-throw
errors wrapped in a more descriptive message, to make it clear the error
is due to an issue in their functions.php file.

Decided to throw and stop, rather than ignore & continue, to be on the
safe side in the event auth-level (or other security level) customizations
have been made via functions.php.

Adds test to cover.
Closes #4504
2023-09-12 12:34:02 +01:00
Bajszi
f997d3e0bb Trimmed name last resort 2023-09-11 21:27:15 +02:00
Dan Brown
8e3f8de627 Notifications: Reorgranised classes into domain specific folders
Closes #4500
2023-09-11 19:27:36 +01:00
Dan Brown
18f396c21b Views: Rolled out ID to similar recent activity lists
To allow for easier customization.
Related to #4530
2023-09-11 18:50:39 +01:00
Dan Brown
ec86576e1e Merge branch 'v23-08' into development 2023-09-11 18:43:23 +01:00
Dan Brown
99eb3e5f71 Comments: Fixed JS error when lacking commenting permissions
The page comments component would throw an error due to references to
form elements/content, when form elements may not exist due to
permisisons.

For #4531
2023-09-11 18:40:40 +01:00
Dan Brown
4985e39db4 Slack auth: Switched from community to laravel library
Tested locally before & after change, and looked at code to compare.
Nothing seen or experienced that should affect things, from testing all
is working as expected with no difference from before.
- Update composer requirement of socialite to that which included slack.
- Updated PHP depds while there.
- Updated format of socialite events to align with current documentation
  and to use class references instead of strings.
2023-09-11 15:26:04 +01:00
Dan Brown
05f2ec40cc OIDC: Moved name claim option handling from config to service
Closes #4494
2023-09-11 11:50:58 +01:00
Dan Brown
564dc70ac4 Fixed php8 compat issue, updated readme & templates
- Changed use of array spread since it was not supported in PHP8.0.
- Updated issue templates based to reduce less valueable fields, update
  some details, and try to help bug reports be more focused on bugs.
- Updated readme with peertube link and attribution advistory for
  translations PRs.
2023-09-11 11:37:07 +01:00
Dan Brown
2fbf5527c7 Simplified and aligned handling of mixed entity endpoints
Fixes #4444
2023-09-10 15:19:23 +01:00
Dan Brown
3928cbac18 Mail: changed default "MAIL_FROM" address
Used an "example.com" address so we're using a propoer reserved domain,
and to avoid these trying to be delivered to the main bookstackapp
domain.

Closes #4518
2023-09-09 12:41:37 +01:00
Dan Brown
8659ee0936 Merge pull request #4525 from BookStackApp/http_alignment
HTTP calling logic alignment
2023-09-08 17:30:44 +01:00
Dan Brown
06490f624c Removed use of HttpFetcher
- Fixed some existing issues in new aligned process.
- Manually tested each external call scenario.
2023-09-08 17:16:57 +01:00
Dan Brown
a8b5652210 Started aligning app-wide outbound http calling behaviour 2023-09-08 14:16:09 +01:00
Dan Brown
15da4b98ef Updated translations with latest Crowdin changes (#4512)
Last translation merge for possible continued v23.08 branch
2023-09-07 15:57:59 +01:00
Dan Brown
21cd2d17f6 Updated sponsors and dev version 2023-09-07 14:43:29 +01:00
Dan Brown
3f473528b1 Updated version and assets for release v23.08.2 2023-09-04 12:06:50 +01:00
Dan Brown
d0dcd4f61b Merge branch 'development' into release 2023-09-04 12:06:15 +01:00
Dan Brown
ad60517536 Updated translations with latest Crowdin changes (#4506) 2023-09-04 11:48:25 +01:00
Dan Brown
2c20abc872 WYSIWYG: Fixed filtering issue causing broken page edits
Could error upon div elements without classes, including drawings.

Related to #4510 and #4509
2023-09-04 11:25:05 +01:00
Dan Brown
bde66a1396 Updated version and assets for release v23.08.1 2023-09-03 17:40:19 +01:00
Dan Brown
4de5a2d9bf Merge branch 'development' into release 2023-09-03 17:39:56 +01:00
Dan Brown
2abbcf5c0f Updated translator attribution before release v23.08.1 2023-09-03 17:35:57 +01:00
Dan Brown
7a48516bf4 Updated translations with latest Crowdin changes (#4481) 2023-09-03 17:23:40 +01:00
Dan Brown
e31b50dabd Preferences: Fixed section screen flexibility
Improved wrapping and flex control to prevent button text force wrapping
to newlines.

For #4502
2023-09-03 16:58:29 +01:00
Dan Brown
817581aa0c Watching: Prevent issues when watchable or user is deleted
- Adds filtering to the watched items list in notification preferences
  so that deleted (recycle bin) items are removed via query.
- Adds relations and logic to properly remove watches upon user and
  entity delete events, to old watches in database do not linger.
- Adds testing to cover the above.

Did not add migration for existing data, since patch will be close to
introduction, and lingering DB entries don't open a security concern,
just some potential confusion in specific potential scenarios.
Probably not work extra migration risk, although could add in future if
concerns/issues are found.

Related to #4499
2023-09-03 14:19:43 +01:00
Dan Brown
1cd19c76ba Merge pull request #4497 from BookStackApp/notification_language
Notifications: User language for notification text
2023-09-02 15:47:26 +01:00
Dan Brown
5d38ae3c97 Merge pull request #4484 from omahs/patch-1
Fix typos
2023-09-02 15:44:01 +01:00
Dan Brown
a720b3725d Testing: Added entity decode flag and phpunit env option
- Passed decode flags to provide consistent behaviour across PHP
  versions during testing.
- Added env option to prevent local option taking action in PHPunit
  tests.
2023-09-02 15:39:45 +01:00
Dan Brown
3847a76134 Notifications: Aligned how user language is used
- This ensures content notifications are not translated to receiver
  language.
- This adds actual plaintext support for content notifications (Was
  previously just HTML as text view).
- Shares same base class across all mail notifications.
- Also cleaned up existing notification classes.

Future cleanup requested via #4501
2023-09-02 15:11:42 +01:00
Dan Brown
f91049a3f2 Notifications: Add test to check notification language 2023-09-01 16:30:37 +01:00
Dan Brown
4e6b74f2a1 WYSIWYG: Added filtering of page pointer elements
For #4474
2023-09-01 13:50:55 +01:00
omahs
976f241ae0 fix typo 2023-08-31 10:01:56 +02:00
omahs
415dab9936 fix typos 2023-08-31 10:00:45 +02:00
omahs
54715d40ef fix typo 2023-08-31 09:58:59 +02:00
Dan Brown
27bf4299cf Updated version and assets for release v23.08 2023-08-30 12:38:48 +01:00
Dan Brown
164f01bb25 Merge branch 'development' into release 2023-08-30 12:38:22 +01:00
Dan Brown
c6d0e690f9 Updated translations with latest Crowdin changes (#4462) 2023-08-30 12:35:10 +01:00
Dan Brown
77d65d1ca1 Updated translator attribution before v23.08 2023-08-30 11:49:45 +01:00
Dan Brown
dc77233ec3 MD Editor: Fixed scroll on mobile widths
Added min-height to flex elements to ensure they properly flex within
the container rathen than adjust to content.

For #4466
2023-08-30 02:41:51 +01:00
Dan Brown
3622c440d7 SSR: Added new option to complete env example file 2023-08-30 02:31:36 +01:00
Dan Brown
642210ab4c Merge branch 'srr_host_allowlist' into development 2023-08-27 12:45:00 +01:00
Dan Brown
e176aae940 Updated translations with latest Crowdin changes (#4380) 2023-08-27 12:43:59 +01:00
Dan Brown
903895814a SSR: Updated allow list handling & covered webhook usage
- Covered webhook SSR allow list useage via test.
- Updated allow list handling to use trailing slash, or hash, or end of
  line as late anchor for better handling for hosts (prevent .co.uk
passing for .co domain host)
2023-08-26 20:13:37 +01:00
Dan Brown
c324ad928d Security: Added new SSR allow list and validator
Included unit tests to cover validator functionality.
Added to webhooks.
Still need to do testing specifically for webhooks.
2023-08-26 15:28:29 +01:00
Dan Brown
9100a82b47 Guests: Prevented access to profile routes
Prevention of action on certain routes for guest user when public access
is enabled. Could not see a way this could be a security issue, beyond a
mild nuisance that'd only be visible if public users can edit, which
would present larger potential nuisance anyway.
2023-08-26 14:07:48 +01:00
Dan Brown
32516f7b68 Merge pull request #4457 from BookStackApp/drawing_backup_store
Browser-based drawing backup storage system
2023-08-23 19:12:29 +01:00
Dan Brown
69ac425903 Updated readme attribution and fixed eslint issues 2023-08-23 19:02:23 +01:00
Dan Brown
3917e50c90 Drawio: Tweaked fail backup handling during testing
- Tweaked wording of popup title.
- Updated WYSIWYG create handling to properly remove drawing container
  on failure.

Tested across FF and chrome, in both editors for create & editing.
2023-08-23 18:50:37 +01:00
Dan Brown
dd71658d70 Drawio: Added unsaved restore prompt and logic 2023-08-23 14:16:20 +01:00
Dan Brown
a4fbde9185 Drawio: Started browser drawing backup store system
Adds just the part to store image data, and remove on successfull save.
Alters save events to properly throw upon error.
Adds IDB-Keyval library for local large-size store.
For #4421
2023-08-22 19:30:39 +01:00
Dan Brown
cbcec189fd RTL: Fixed screen-reader-only elements pushout out view
For #4429
2023-08-22 18:25:14 +01:00
Dan Brown
0628c28f66 Cache: Increases database cache value size
Upped from text to medium text.
Aligns with modern Laravel default.
Fixes #4453 where were reaching the limit of TEXT.
2023-08-21 23:01:42 +01:00
Dan Brown
391478465a Merge branch 'add-priority' into development 2023-08-21 15:43:16 +01:00
Dan Brown
9ca1139ab0 API: Reviewed changes for API priority control
Review of #4313
- Made constructor changes while reviewing some classes.
- Updated API examples for consistency.
- Tweaked formatting for some array changes.
- Simplified added tests.
- Tweaked chapter/page repo priority handling to be simpler.

Performed manual API endpoint testing of page/chapter create/update.
2023-08-21 15:42:47 +01:00
Dan Brown
7bf5425c6b Updated PHP and npm deps, Upped node version 2023-08-19 20:22:19 +01:00
Dan Brown
e44ef57219 Status: Updated cache check to use unique key
Updated status endpoint cache check to include a random component in the
key to avoid conflict during simultaneous checks.
For #4396
2023-08-17 21:24:35 +01:00
Dan Brown
fef433a9cb Merge pull request #4390 from BookStackApp/content_notifications
Content user notifications
2023-08-17 21:09:52 +01:00
Dan Brown
e709caa005 Notifications: Switched testing from string to reference levels 2023-08-17 18:10:34 +01:00
Dan Brown
38829f8a38 Notifications: Fixed send content permission checking
Added test and changed logic to properly check the view permissions for
the notification receiver before sending.
Required change to permissions applicator to allow the user to be
manually determined, and a service provider update to provide the class
as a singleton without a specific user, so it checks the current logged
in user on demand.
2023-08-17 17:57:31 +01:00
Dan Brown
ee9e342b58 Notifications: Fixed issues causing failing tests
- Ensured watch options passed in all meta template usage to fix failing
  scenarios where watch options did not exist.
- Fixed testing issue caused by guest user permission caching.
2023-08-17 14:59:28 +01:00
Dan Brown
79470ea4b7 Notifications: Made improvements from manual testing
- Added titles for preference pages.
- Added extra check for non-guest for notifications on preferences page.
2023-08-16 20:15:49 +01:00
Dan Brown
565908ef52 Notifications: Add phpunit test for notification sending
Covers core case scenarios, and check of notification content.
2023-08-16 16:02:00 +01:00
Dan Brown
bc6e19b2a1 Notifications: Added testing to cover controls 2023-08-15 20:08:27 +01:00
Dan Brown
615741af9d Notifications: Cleaned up mails, added debounce for updates
- Updated mail notification design to be a bit prettier, and extracted
  text to new lang file for translation.
- Added debounce logic for page update notifications.
- Fixed watch options not being filtered to current user.
2023-08-15 14:39:39 +01:00
Dan Brown
371779205a Notifications: Added new preferences view and access control
- Added general user preferences view and updated link in profile menu
  to suit.
- Made notification permission required for notification preferences
  view, added test to cover.
2023-08-14 17:29:12 +01:00
Dan Brown
d9fdecd902 Notifications: User watch list and differnt page watch options
- Adds option filtering and alternative text for page watch options.
- Adds "Watched & Ignored Items" list to user notification preferences
  page to show existing watched items.
2023-08-14 13:11:18 +01:00
JonatanRek
2b604b5af9 Move Manifest Definition to Separate Config File 2023-08-10 17:02:31 +02:00
JonatanRek
08ea97fd83 Manifest Tweaks 2023-08-10 16:43:14 +02:00
JonatanRek
601491b275 Add Color 2023-08-10 15:51:09 +02:00
JonatanRek
88e148ba00 Initial Draft 2023-08-10 15:44:27 +02:00
Dan Brown
c47b3f805a Notifications: Updated watch control to show parent status 2023-08-09 14:53:31 +01:00
Dan Brown
ecab2c8e42 Notifications: Added logic and classes for remaining notification types 2023-08-05 14:19:23 +01:00
Dan Brown
18ae67a138 Notifications: Got core notification logic working for new pages
Also rolled out watch UI to chapter and page views
2023-08-04 16:51:29 +01:00
Dan Brown
9779c1a357 Notifications: Started core user notification logic
Put together an initial notification.
Started logic to query and identify watchers.
2023-08-04 12:27:29 +01:00
Dan Brown
9d149e4d36 Notifications: Linked watch functionality to UI
Got watch system working to an initial base state.
Moved some existing logic where it makes sense.
2023-08-02 13:14:00 +01:00
Dan Brown
8cdf3203ef Notifications: Started back-end for watch system
Added DB and started controller method.
2023-07-31 16:08:29 +01:00
Dan Brown
6100b99828 Notifications: Extracted watch options, updated UI further 2023-07-31 15:23:28 +01:00
Dan Brown
730f539029 Notifications: Started entity watch UI 2023-07-27 14:27:45 +01:00
Dan Brown
ff2674c464 Notifications: Added role receive-notifications permission 2023-07-25 17:59:04 +01:00
Dan Brown
100b28707c Notifications: added user preference UI & logic
Includes testing to cover.
Also added file missing from previous commit.
2023-07-25 17:08:40 +01:00
Dan Brown
45e75edf05 Notifications: Started activity->notification core framework 2023-07-19 11:03:05 +01:00
Dan Brown
1c922be4c7 Comments: Added text for new activity types 2023-07-19 10:11:53 +01:00
Dan Brown
0359e2490a Comments: Updated testing to check for new activities 2023-07-19 10:09:08 +01:00
Dan Brown
422e50302a Comments: Added extra comment-specific activities
Kept existing "COMMENTED_ON" activity for upgrade compatibility,
specifically for existing webhook usage and for showing comment
activities in activity lists.

Precursor to content notifications.
Currently untested.
Also applied some type updates.
2023-07-18 15:07:31 +01:00
Dan Brown
f563a005f5 Updated version and assets for release v23.06.2 2023-07-12 22:34:25 +01:00
Dan Brown
a14d8e30cc Merge branch 'development' into release 2023-07-12 22:34:15 +01:00
Dan Brown
7504ad32a7 Updated translator attribution before release v23.06.2 2023-07-12 22:34:04 +01:00
Dan Brown
fca18862d2 Updated translations with latest Crowdin changes (#4367) 2023-07-12 22:22:43 +01:00
Dan Brown
ae834050f5 Shelf permissions: reverted create removal
Reverted work in 847a57a49a.
Left test in but updated to new expectation.
Left migration in but removed content to prevent new pre-v23.06
upgraders loosing shelf create permission status.
Added note to permission to describe use-case.

For #4375
2023-07-12 22:04:05 +01:00
Dan Brown
a83150131a Webhooks: Fixed failing delete-based events
Due to queue serialization.
Added a test to check a couple of delete events.
Added ApiTokenFactory to support.
Also made a couple of typing/doc updates while there.

Related to #4373
2023-07-12 16:16:12 +01:00
Jean-René ROUET
3a36d3c847 add tests for priority 2023-07-11 14:11:13 +02:00
Jean-René ROUET
4d399f6ba7 add priority on page and chapter create 2023-07-11 13:28:20 +02:00
Jean-René Rouet
b1b8067cbe Merge branch 'BookStackApp:development' into add-priority 2023-07-11 08:57:14 +02:00
Dan Brown
a9194ffb63 Updated version and assets for release v23.06.1 2023-07-05 13:04:51 +01:00
Dan Brown
2f9c1b7127 Merge branch 'development' into release 2023-07-05 13:04:30 +01:00
Dan Brown
18979e84d6 Updated tranlsator attribution and sponsors 2023-07-05 12:40:49 +01:00
Dan Brown
bf5e886d76 Updated translations with latest Crowdin changes (#4352) 2023-07-05 12:28:19 +01:00
Dan Brown
e04a1af444 Merge pull request #4344 from devdot/update-api-docs
Update API Docs
2023-07-05 12:08:51 +01:00
Dan Brown
eb2c5d00cb Audit log: Added IP address wrapping
Primarily to support long ipv6 addresses which would overflow over the
activity date.
For #4349
2023-07-05 11:37:49 +01:00
Dan Brown
96819b7bd9 Images: Updated image timestamp upon file change
For #4354
2023-07-05 11:28:03 +01:00
Dan Brown
18ee80a743 Roles: fixed error upon created_at sorting
Added test to cover core role sorting functionality.
For #4350
2023-07-04 21:52:46 +01:00
Dan Brown
1a56de6cb4 Testing: Split out role tests to management and permissions 2023-07-04 21:40:05 +01:00
Dan Brown
465989efa9 Mail: Updated to forked symfony/mailer to allow assurance of tls
Related to #4358
2023-07-04 15:21:31 +01:00
Thomas Kuschan
d293171da2 API Docs: Add Missing Fields in Example Responses 2023-06-30 09:36:46 +02:00
Thomas Kuschan
174cd5a893 API Docs: Add Missing editor fields in Example Responses 2023-06-30 09:35:47 +02:00
Thomas Kuschan
ccfe38e963 API Docs: Add book_slug to Example Responses
Remove the book attribute in responses because it is never returned by the API. Currently, Chapters Create does not return book_slug! (The example response is consistent with the inconsistent API behavior)
2023-06-30 09:33:53 +02:00
Thomas Kuschan
23ae332c1b API Docs: Sort a few example responses 2023-06-30 09:27:18 +02:00
Thomas Kuschan
3a39f13420 API Docs: Remove Dates from Tags in Example Responses 2023-06-30 09:24:46 +02:00
Thomas Kuschan
ca2d2c97d4 API Docs: Add User Slugs to Example Responses 2023-06-30 09:23:02 +02:00
Thomas Kuschan
e47870794d API Docs: Add Missing Type in Response
Type is always returned when pages/chapters are in a contents array.
2023-06-26 10:14:10 +02:00
Thomas Kuschan
e43d85b801 API Docs: Remove id from Tag in Response 2023-06-26 10:13:02 +02:00
Jean-René Rouet
bb3ce845b4 Merge branch 'BookStackApp:development' into add-priority 2023-06-15 16:55:14 +02:00
Jean-René ROUET
458cea3644 [API] add priority in book read
[API] add priority in chapter create and update
[API] add priority in page create and update
2023-06-12 15:12:46 +02:00
721 changed files with 21267 additions and 6807 deletions

View File

@@ -72,7 +72,7 @@ MYSQL_ATTR_SSL_CA="/path/to/ca.pem"
# Mail configuration
# Refer to https://www.bookstackapp.com/docs/admin/email-webhooks/#email-configuration
MAIL_DRIVER=smtp
MAIL_FROM=mail@bookstackapp.com
MAIL_FROM=bookstack@example.com
MAIL_FROM_NAME=BookStack
MAIL_HOST=localhost
@@ -359,6 +359,15 @@ ALLOWED_IFRAME_HOSTS=null
# Current host and source for the "DRAWIO" setting will be auto-appended to the sources configured.
ALLOWED_IFRAME_SOURCES="https://*.draw.io https://*.youtube.com https://*.youtube-nocookie.com https://*.vimeo.com"
# A list of the sources/hostnames that can be reached by application SSR calls.
# This is used wherever users can provide URLs/hosts in-platform, like for webhooks.
# Host-specific functionality (usually controlled via other options) like auth
# or user avatars for example, won't use this list.
# Space seperated if multiple. Can use '*' as a wildcard.
# Values will be compared prefix-matched, case-insensitive, against called SSR urls.
# Defaults to allow all hosts.
ALLOWED_SSR_HOSTS="*"
# The default and maximum item-counts for listing API requests.
API_DEFAULT_ITEM_COUNT=100
API_MAX_ITEM_COUNT=500

View File

@@ -1,7 +1,14 @@
name: Bug Report
description: Create a report to help us improve or fix things
description: Create a report to help us fix bugs & issues in existing supported functionality
labels: [":bug: Bug"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out a bug report!
Please note that this form is for reporting bugs in existing supported functionality.
If you are reporting something that's not an issue in functionality we've previously supported and/or is simply something different to your expectations, then it may be more appropriate to raise via a feature or support request instead.
- type: textarea
id: description
attributes:
@@ -13,7 +20,7 @@ body:
id: reproduction
attributes:
label: Steps to Reproduce
description: Detail the steps that would replicate this issue
description: Detail the steps that would replicate this issue.
placeholder: |
1. Go to '...'
2. Click on '....'
@@ -32,7 +39,7 @@ body:
id: context
attributes:
label: Screenshots or Additional Context
description: Provide any additional context and screenshots here to help us solve this issue
description: Provide any additional context and screenshots here to help us solve this issue.
validations:
required: false
- type: input
@@ -48,23 +55,7 @@ body:
id: bsversion
attributes:
label: Exact BookStack Version
description: This can be found in the settings view of BookStack. Please provide an exact version.
placeholder: (eg. v21.08.5)
validations:
required: true
- type: input
id: phpversion
attributes:
label: PHP Version
description: Keep in mind your command-line PHP version may differ to that of your webserver. Provide that relevant to the issue.
placeholder: (eg. 7.4)
validations:
required: false
- type: textarea
id: hosting
attributes:
label: Hosting Environment
description: Describe your hosting environment as much as possible including any proxies used (If applicable).
placeholder: (eg. Ubuntu 20.04 VPS, installed using official installation script)
description: This can be found in the settings view of BookStack. Please provide an exact version(s) you've tested on.
placeholder: (eg. v23.06.7)
validations:
required: true

View File

@@ -33,9 +33,9 @@ body:
attributes:
label: Have you searched for an existing open/closed issue?
description: |
To help us keep these issues under control, please ensure you have first [searched our issue list](https://github.com/BookStackApp/BookStack/issues?q=is%3Aissue) for any existing issues that cover the fundemental benefit/goal of your request.
To help us keep these issues under control, please ensure you have first [searched our issue list](https://github.com/BookStackApp/BookStack/issues?q=is%3Aissue) for any existing issues that cover the fundamental benefit/goal of your request.
options:
- label: I have searched for existing issues and none cover my fundemental request
- label: I have searched for existing issues and none cover my fundamental request
required: true
- type: dropdown
id: existing_usage
@@ -43,8 +43,8 @@ body:
label: How long have you been using BookStack?
options:
- Not using yet, just scoping
- 0 to 6 months
- 6 months to 1 year
- Under 3 months
- 3 months to 1 year
- 1 to 5 years
- Over 5 years
validations:

View File

@@ -33,7 +33,7 @@ body:
attributes:
label: Exact BookStack Version
description: This can be found in the settings view of BookStack. Please provide an exact version.
placeholder: (eg. v21.08.5)
placeholder: (eg. v23.06.7)
validations:
required: true
- type: textarea
@@ -44,19 +44,11 @@ body:
placeholder: Be sure to remove any confidential details in your logs
validations:
required: false
- type: input
id: phpversion
attributes:
label: PHP Version
description: Keep in mind your command-line PHP version may differ to that of your webserver. Provide that most relevant to the issue.
placeholder: (eg. 7.4)
validations:
required: false
- type: textarea
id: hosting
attributes:
label: Hosting Environment
description: Describe your hosting environment as much as possible including any proxies used (If applicable).
placeholder: (eg. Ubuntu 20.04 VPS, installed using official installation script)
placeholder: (eg. PHP8.1 on Ubuntu 22.04 VPS, installed using official installation script)
validations:
required: true

15
.github/SECURITY.md vendored
View File

@@ -15,18 +15,13 @@ If you'd like to be notified of new potential security concerns you can [sign-up
If you've found an issue that likely has no impact to existing users (For example, in a development-only branch)
feel free to raise it via a standard GitHub bug report issue.
If the issue could have a security impact to BookStack instances, please use one of the below
methods to report the vulnerability:
- Directly contact the lead maintainer [@ssddanbrown](https://github.com/ssddanbrown).
- You will need to login to be able to see the email address on the [GitHub profile page](https://github.com/ssddanbrown).
- Alternatively you can send a DM via Twitter to [@ssddanbrown](https://twitter.com/ssddanbrown).
- [Disclose via huntr.dev](https://huntr.dev/bounties/disclose)
- Bounties may be available to you through this platform.
- Be sure to use `https://github.com/BookStackApp/BookStack` as the repository URL.
If the issue could have a security impact to BookStack instances,
please directly contact the lead maintainer [@ssddanbrown](https://github.com/ssddanbrown).
You will need to log in to be able to see the email address on the [GitHub profile page](https://github.com/ssddanbrown).
Alternatively you can send a DM via Mastodon to [@danb@fosstodon.org](https://fosstodon.org/@danb).
Please be patient while the vulnerability is being reviewed. Deploying the fix to address the vulnerability
can often take a little time due to the amount of preparation required, to ensure the vulnerability has
been covered, and to create the content required to adequately notify the user-base.
Thank you for keeping BookStack instances safe!
Thank you for keeping BookStack instances safe!

View File

@@ -57,6 +57,7 @@ Name :: Languages
@Jokuna :: Korean
@smartshogu :: German; German Informal
@samadha56 :: Persian
@mrmuminov :: Uzbek
cipi1965 :: Italian
Mykola Ronik (Mantikor) :: Ukrainian
furkanoyk :: Turkish
@@ -176,7 +177,7 @@ Alexander Predl (Harveyhase68) :: German
Rem (Rem9000) :: Dutch
Michał Stelmach (stelmach-web) :: Polish
arniom :: French
REMOVED_USER :: ; French; Dutch; Turkish
REMOVED_USER :: French; Dutch; Turkish;
林祖年 (contagion) :: Chinese Traditional
Siamak Guodarzi (siamakgoudarzi88) :: Persian
Lis Maestrelo (lismtrl) :: Portuguese, Brazilian
@@ -269,7 +270,7 @@ mcgong (GongMingCai) :: Chinese Simplified; Chinese Traditional
Nanang Setia Budi (sefidananang) :: Indonesian
Андрей Павлов (andrei.pavlov) :: Russian
Alex Navarro (alex.n.navarro) :: Portuguese, Brazilian
Ji-Hyeon Gim (PotatoGim) :: Korean
Jihyeon Gim (PotatoGim) :: Korean
Mihai Ochian (soulstorm19) :: Romanian
HeartCore :: German Informal; German
simon.pct :: French
@@ -289,7 +290,7 @@ Ismael Mesquita (mesquitoliveira) :: Portuguese, Brazilian
LiZerui (CNLiZerui) :: Chinese Traditional
Fabrice Boyer (FabriceBoyer) :: French
mikael (bitcanon) :: Swedish
Matthias Mai (schnapsidee) :: German; German Informal
Matthias Mai (schnapsidee) :: German Informal; German
Ufuk Ayyıldız (ufukayyildiz) :: Turkish
Jan Mitrof (jan.kachlik) :: Czech
edwardsmirnov :: Russian
@@ -341,3 +342,28 @@ Ingus Rūķis (ingus.rukis) :: Latvian
Eugene Pershin (SilentEugene) :: Russian
周盛道 (zhoushengdao) :: Chinese Simplified
hamidreza amini (hamidrezaamini2022) :: Persian
Tomislav Kraljević (tomislav.kraljevic) :: Croatian
Taygun Yıldırım (yildirimtaygun) :: Turkish
robing29 :: German
Bruno Eduardo de Jesus Barroso (brunoejb) :: Portuguese, Brazilian
Igor V Belousov (biv) :: Russian
David Bauer (davbauer) :: German
Guttorm Hveem (guttormhveem) :: Norwegian Bokmal; Norwegian Nynorsk
Minh Giang Truong (minhgiang1204) :: Vietnamese
Ioannis Ioannides (i.ioannides) :: Greek
Vadim (vadrozh) :: Russian
Flip333 :: German Informal; German
Paulo Henrique (paulohsantos114) :: Portuguese, Brazilian
Dženan (Dzenan) :: Swedish
Péter Péli (peter.peli) :: Hungarian
TWME :: Chinese Traditional
Sascha (Man-in-Black) :: German
Mohammadreza Madadi (madadi.efl) :: Persian
Konstantin Kovacheli (kkovacheli) :: Ukrainian
link1183 :: French
Renan (rfpe) :: Portuguese, Brazilian
Lowkey (bbsweb) :: Chinese Simplified
ZZnOB (zznobzz) :: Russian
rupus :: Swedish
developernecsys :: Norwegian Nynorsk
xuan LI (xuanli233) :: Chinese Simplified

View File

@@ -1,6 +1,12 @@
name: analyse-php
on: [push, pull_request]
on:
push:
paths:
- '**.php'
pull_request:
paths:
- '**.php'
jobs:
build:

View File

@@ -1,6 +1,14 @@
name: lint-js
on: [push, pull_request]
on:
push:
paths:
- '**.js'
- '**.json'
pull_request:
paths:
- '**.js'
- '**.json'
jobs:
build:

View File

@@ -1,6 +1,12 @@
name: lint-php
on: [push, pull_request]
on:
push:
paths:
- '**.php'
pull_request:
paths:
- '**.php'
jobs:
build:

View File

@@ -1,6 +1,14 @@
name: test-migrations
on: [push, pull_request]
on:
push:
paths:
- '**.php'
- 'composer.*'
pull_request:
paths:
- '**.php'
- 'composer.*'
jobs:
build:

View File

@@ -1,6 +1,14 @@
name: test-php
on: [push, pull_request]
on:
push:
paths:
- '**.php'
- 'composer.*'
pull_request:
paths:
- '**.php'
- 'composer.*'
jobs:
build:

View File

@@ -16,22 +16,12 @@ use Laravel\Socialite\Contracts\User as SocialUser;
class SocialController extends Controller
{
protected SocialAuthService $socialAuthService;
protected RegistrationService $registrationService;
protected LoginService $loginService;
/**
* SocialController constructor.
*/
public function __construct(
SocialAuthService $socialAuthService,
RegistrationService $registrationService,
LoginService $loginService
protected SocialAuthService $socialAuthService,
protected RegistrationService $registrationService,
protected LoginService $loginService,
) {
$this->middleware('guest')->only(['register']);
$this->socialAuthService = $socialAuthService;
$this->registrationService = $registrationService;
$this->loginService = $loginService;
}
/**
@@ -112,7 +102,7 @@ class SocialController extends Controller
$this->socialAuthService->detachSocialAccount($socialDriver);
session()->flash('success', trans('settings.users_social_disconnected', ['socialAccount' => Str::title($socialDriver)]));
return redirect(user()->getEditUrl());
return redirect('/my-account/auth#social-accounts');
}
/**

View File

@@ -71,7 +71,7 @@ trait ThrottlesLogins
*/
protected function limiter(): RateLimiter
{
return app(RateLimiter::class);
return app()->make(RateLimiter::class);
}
/**

View File

@@ -2,8 +2,8 @@
namespace BookStack\Access;
use BookStack\Access\Notifications\ConfirmEmailNotification;
use BookStack\Exceptions\ConfirmationEmailException;
use BookStack\Notifications\ConfirmEmail;
use BookStack\Users\Models\User;
class EmailConfirmationService extends UserTokenService
@@ -26,7 +26,7 @@ class EmailConfirmationService extends UserTokenService
$this->deleteByUser($user);
$token = $this->createTokenForUser($user);
$user->notify(new ConfirmEmail($token));
$user->notify(new ConfirmEmailNotification($token));
}
/**

View File

@@ -0,0 +1,26 @@
<?php
namespace BookStack\Access\Notifications;
use BookStack\App\MailNotification;
use BookStack\Users\Models\User;
use Illuminate\Notifications\Messages\MailMessage;
class ConfirmEmailNotification extends MailNotification
{
public function __construct(
public string $token
) {
}
public function toMail(User $notifiable): MailMessage
{
$appName = ['appName' => setting('app-name')];
return $this->newMailMessage()
->subject(trans('auth.email_confirm_subject', $appName))
->greeting(trans('auth.email_confirm_greeting', $appName))
->line(trans('auth.email_confirm_text'))
->action(trans('auth.email_confirm_action'), url('/register/confirm/' . $this->token));
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace BookStack\Access\Notifications;
use BookStack\App\MailNotification;
use BookStack\Users\Models\User;
use Illuminate\Notifications\Messages\MailMessage;
class ResetPasswordNotification extends MailNotification
{
public function __construct(
public string $token
) {
}
public function toMail(User $notifiable): MailMessage
{
return $this->newMailMessage()
->subject(trans('auth.email_reset_subject', ['appName' => setting('app-name')]))
->line(trans('auth.email_reset_text'))
->action(trans('auth.reset_password'), url('password/reset/' . $this->token))
->line(trans('auth.email_reset_not_requested'));
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace BookStack\Access\Notifications;
use BookStack\App\MailNotification;
use BookStack\Users\Models\User;
use Illuminate\Notifications\Messages\MailMessage;
class UserInviteNotification extends MailNotification
{
public function __construct(
public string $token
) {
}
public function toMail(User $notifiable): MailMessage
{
$appName = ['appName' => setting('app-name')];
$locale = $notifiable->getLocale();
return $this->newMailMessage($locale)
->subject($locale->trans('auth.user_invite_email_subject', $appName))
->greeting($locale->trans('auth.user_invite_email_greeting', $appName))
->line($locale->trans('auth.user_invite_email_text'))
->action($locale->trans('auth.user_invite_email_action'), url('/register/invite/' . $this->token));
}
}

View File

@@ -20,15 +20,8 @@ class OidcOAuthProvider extends AbstractProvider
{
use BearerAuthorizationTrait;
/**
* @var string
*/
protected $authorizationEndpoint;
/**
* @var string
*/
protected $tokenEndpoint;
protected string $authorizationEndpoint;
protected string $tokenEndpoint;
/**
* Scopes to use for the OIDC authorization call.
@@ -60,7 +53,7 @@ class OidcOAuthProvider extends AbstractProvider
}
/**
* Add an additional scope to this provider upon the default.
* Add another scope to this provider upon the default.
*/
public function addScope(string $scope): void
{

View File

@@ -59,7 +59,7 @@ class OidcProviderSettings
}
}
if (strpos($this->issuer, 'https://') !== 0) {
if (!str_starts_with($this->issuer, 'https://')) {
throw new InvalidArgumentException('Issuer value must start with https://');
}
}

View File

@@ -9,13 +9,13 @@ use BookStack\Exceptions\JsonDebugException;
use BookStack\Exceptions\StoppedAuthenticationException;
use BookStack\Exceptions\UserRegistrationException;
use BookStack\Facades\Theme;
use BookStack\Http\HttpRequestService;
use BookStack\Theming\ThemeEvents;
use BookStack\Users\Models\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Psr\Http\Client\ClientInterface as HttpClient;
/**
* Class OpenIdConnectService
@@ -26,7 +26,7 @@ class OidcService
public function __construct(
protected RegistrationService $registrationService,
protected LoginService $loginService,
protected HttpClient $httpClient,
protected HttpRequestService $http,
protected GroupSyncService $groupService
) {
}
@@ -94,7 +94,7 @@ class OidcService
// Run discovery
if ($config['discover'] ?? false) {
try {
$settings->discoverFromIssuer($this->httpClient, Cache::store(null), 15);
$settings->discoverFromIssuer($this->http->buildClient(5), Cache::store(null), 15);
} catch (OidcIssuerDiscoveryException $exception) {
throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
}
@@ -111,7 +111,7 @@ class OidcService
protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
{
$provider = new OidcOAuthProvider($settings->arrayForProvider(), [
'httpClient' => $this->httpClient,
'httpClient' => $this->http->buildClient(5),
'optionProvider' => new HttpBasicAuthOptionProvider(),
]);
@@ -142,10 +142,11 @@ class OidcService
*/
protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
{
$displayNameAttr = $this->config()['display_name_claims'];
$displayNameAttrString = $this->config()['display_name_claims'] ?? '';
$displayNameAttrs = explode('|', $displayNameAttrString);
$displayName = [];
foreach ($displayNameAttr as $dnAttr) {
foreach ($displayNameAttrs as $dnAttr) {
$dnComponent = $token->getClaim($dnAttr) ?? '';
if ($dnComponent !== '') {
$displayName[] = $dnComponent;

View File

@@ -154,21 +154,21 @@ class SocialAuthService
$currentUser->socialAccounts()->save($account);
session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => $titleCaseDriver]));
return redirect($currentUser->getEditUrl());
return redirect('/my-account/auth#social_accounts');
}
// When a user is logged in and the social account exists and is already linked to the current user.
if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => $titleCaseDriver]));
return redirect($currentUser->getEditUrl());
return redirect('/my-account/auth#social_accounts');
}
// When a user is logged in, A social account exists but the users do not match.
if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => $titleCaseDriver]));
return redirect($currentUser->getEditUrl());
return redirect('/my-account/auth#social_accounts');
}
// Otherwise let the user know this social account is not used by anyone.
@@ -214,6 +214,7 @@ class SocialAuthService
/**
* Gets the names of the active social drivers.
* @returns array<string, string>
*/
public function getActiveDrivers(): array
{

View File

@@ -2,7 +2,7 @@
namespace BookStack\Access;
use BookStack\Notifications\UserInvite;
use BookStack\Access\Notifications\UserInviteNotification;
use BookStack\Users\Models\User;
class UserInviteService extends UserTokenService
@@ -18,6 +18,6 @@ class UserInviteService extends UserTokenService
{
$this->deleteByUser($user);
$token = $this->createTokenForUser($user);
$user->notify(new UserInvite($token));
$user->notify(new UserInviteNotification($token));
}
}

View File

@@ -27,6 +27,10 @@ class ActivityType
const BOOKSHELF_DELETE = 'bookshelf_delete';
const COMMENTED_ON = 'commented_on';
const COMMENT_CREATE = 'comment_create';
const COMMENT_UPDATE = 'comment_update';
const COMMENT_DELETE = 'comment_delete';
const PERMISSIONS_UPDATE = 'permissions_update';
const REVISION_RESTORE = 'revision_restore';

View File

@@ -33,6 +33,7 @@ class CommentRepo
$comment->parent_id = $parent_id;
$entity->comments()->save($comment);
ActivityService::add(ActivityType::COMMENT_CREATE, $comment);
ActivityService::add(ActivityType::COMMENTED_ON, $entity);
return $comment;
@@ -48,6 +49,8 @@ class CommentRepo
$comment->html = $this->commentToHtml($text);
$comment->save();
ActivityService::add(ActivityType::COMMENT_UPDATE, $comment);
return $comment;
}
@@ -57,6 +60,8 @@ class CommentRepo
public function delete(Comment $comment): void
{
$comment->delete();
ActivityService::add(ActivityType::COMMENT_DELETE, $comment);
}
/**

View File

@@ -6,11 +6,17 @@ use BookStack\Activity\Models\Favouritable;
use BookStack\App\Model;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Queries\TopFavourites;
use BookStack\Entities\Tools\MixedEntityRequestHelper;
use BookStack\Http\Controller;
use Illuminate\Http\Request;
class FavouriteController extends Controller
{
public function __construct(
protected MixedEntityRequestHelper $entityHelper,
) {
}
/**
* Show a listing of all favourite items for the current user.
*/
@@ -36,13 +42,14 @@ class FavouriteController extends Controller
*/
public function add(Request $request)
{
$favouritable = $this->getValidatedModelFromRequest($request);
$favouritable->favourites()->firstOrCreate([
$modelInfo = $this->validate($request, $this->entityHelper->validationRules());
$entity = $this->entityHelper->getVisibleEntityFromRequestData($modelInfo);
$entity->favourites()->firstOrCreate([
'user_id' => user()->id,
]);
$this->showSuccessNotification(trans('activities.favourite_add_notification', [
'name' => $favouritable->name,
'name' => $entity->name,
]));
return redirect()->back();
@@ -53,48 +60,16 @@ class FavouriteController extends Controller
*/
public function remove(Request $request)
{
$favouritable = $this->getValidatedModelFromRequest($request);
$favouritable->favourites()->where([
$modelInfo = $this->validate($request, $this->entityHelper->validationRules());
$entity = $this->entityHelper->getVisibleEntityFromRequestData($modelInfo);
$entity->favourites()->where([
'user_id' => user()->id,
])->delete();
$this->showSuccessNotification(trans('activities.favourite_remove_notification', [
'name' => $favouritable->name,
'name' => $entity->name,
]));
return redirect()->back();
}
/**
* @throws \Illuminate\Validation\ValidationException
* @throws \Exception
*/
protected function getValidatedModelFromRequest(Request $request): Entity
{
$modelInfo = $this->validate($request, [
'type' => ['required', 'string'],
'id' => ['required', 'integer'],
]);
if (!class_exists($modelInfo['type'])) {
throw new \Exception('Model not found');
}
/** @var Model $model */
$model = new $modelInfo['type']();
if (!$model instanceof Favouritable) {
throw new \Exception('Model not favouritable');
}
$modelInstance = $model->newQuery()
->where('id', '=', $modelInfo['id'])
->first(['id', 'name', 'owned_by']);
$inaccessibleEntity = ($modelInstance instanceof Entity && !userCan('view', $modelInstance));
if (is_null($modelInstance) || $inaccessibleEntity) {
throw new \Exception('Model instance not found');
}
return $modelInstance;
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace BookStack\Activity\Controllers;
use BookStack\Activity\Tools\UserEntityWatchOptions;
use BookStack\Entities\Tools\MixedEntityRequestHelper;
use BookStack\Http\Controller;
use Illuminate\Http\Request;
class WatchController extends Controller
{
public function update(Request $request, MixedEntityRequestHelper $entityHelper)
{
$this->checkPermission('receive-notifications');
$this->preventGuestAccess();
$requestData = $this->validate($request, array_merge([
'level' => ['required', 'string'],
], $entityHelper->validationRules()));
$watchable = $entityHelper->getVisibleEntityFromRequestData($requestData);
$watchOptions = new UserEntityWatchOptions(user(), $watchable);
$watchOptions->updateLevelByName($requestData['level']);
$this->showSuccessNotification(trans('activities.watch_update_level_notification'));
return redirect()->back();
}
}

View File

@@ -6,14 +6,15 @@ use BookStack\Activity\Models\Loggable;
use BookStack\Activity\Models\Webhook;
use BookStack\Activity\Tools\WebhookFormatter;
use BookStack\Facades\Theme;
use BookStack\Http\HttpRequestService;
use BookStack\Theming\ThemeEvents;
use BookStack\Users\Models\User;
use BookStack\Util\SsrUrlValidator;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class DispatchWebhookJob implements ShouldQueue
@@ -24,27 +25,23 @@ class DispatchWebhookJob implements ShouldQueue
use SerializesModels;
protected Webhook $webhook;
protected string $event;
protected User $initiator;
protected int $initiatedTime;
/**
* @var string|Loggable
*/
protected $detail;
protected array $webhookData;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Webhook $webhook, string $event, $detail)
public function __construct(Webhook $webhook, string $event, Loggable|string $detail)
{
$this->webhook = $webhook;
$this->event = $event;
$this->detail = $detail;
$this->initiator = user();
$this->initiatedTime = time();
$themeResponse = Theme::dispatch(ThemeEvents::WEBHOOK_CALL_BEFORE, $event, $this->webhook, $detail, $this->initiator, $this->initiatedTime);
$this->webhookData = $themeResponse ?? WebhookFormatter::getDefault($event, $this->webhook, $detail, $this->initiator, $this->initiatedTime)->format();
}
/**
@@ -52,25 +49,28 @@ class DispatchWebhookJob implements ShouldQueue
*
* @return void
*/
public function handle()
public function handle(HttpRequestService $http)
{
$themeResponse = Theme::dispatch(ThemeEvents::WEBHOOK_CALL_BEFORE, $this->event, $this->webhook, $this->detail, $this->initiator, $this->initiatedTime);
$webhookData = $themeResponse ?? WebhookFormatter::getDefault($this->event, $this->webhook, $this->detail, $this->initiator, $this->initiatedTime)->format();
$lastError = null;
try {
$response = Http::asJson()
->withOptions(['allow_redirects' => ['strict' => true]])
->timeout($this->webhook->timeout)
->post($this->webhook->endpoint, $webhookData);
} catch (\Exception $exception) {
$lastError = $exception->getMessage();
Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with error \"{$lastError}\"");
}
(new SsrUrlValidator())->ensureAllowed($this->webhook->endpoint);
if (isset($response) && $response->failed()) {
$lastError = "Response status from endpoint was {$response->status()}";
Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with status {$response->status()}");
$client = $http->buildClient($this->webhook->timeout, [
'connect_timeout' => 10,
'allow_redirects' => ['strict' => true],
]);
$response = $client->sendRequest($http->jsonRequest('POST', $this->webhook->endpoint, $this->webhookData));
$statusCode = $response->getStatusCode();
if ($statusCode >= 400) {
$lastError = "Response status from endpoint was {$statusCode}";
Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with status {$statusCode}");
}
} catch (\Exception $error) {
$lastError = $error->getMessage();
Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with error \"{$lastError}\"");
}
$this->webhook->last_called_at = now();

View File

@@ -5,16 +5,21 @@ namespace BookStack\Activity\Models;
use BookStack\App\Model;
use BookStack\Users\Models\HasCreatorAndUpdater;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
/**
* @property int $id
* @property string $text
* @property string $html
* @property int|null $parent_id
* @property int|null $parent_id - Relates to local_id, not id
* @property int $local_id
* @property string $entity_type
* @property int $entity_id
* @property int $created_by
* @property int $updated_by
*/
class Comment extends Model
class Comment extends Model implements Loggable
{
use HasFactory;
use HasCreatorAndUpdater;
@@ -30,6 +35,16 @@ class Comment extends Model
return $this->morphTo('entity');
}
/**
* Get the parent comment this is in reply to (if existing).
*/
public function parent(): BelongsTo
{
return $this->belongsTo(Comment::class, 'parent_id', 'local_id', 'parent')
->where('entity_type', '=', $this->entity_type)
->where('entity_id', '=', $this->entity_id);
}
/**
* Check if a comment has been updated since creation.
*/
@@ -40,21 +55,22 @@ class Comment extends Model
/**
* Get created date as a relative diff.
*
* @return mixed
*/
public function getCreatedAttribute()
public function getCreatedAttribute(): string
{
return $this->created_at->diffForHumans();
}
/**
* Get updated date as a relative diff.
*
* @return mixed
*/
public function getUpdatedAttribute()
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})";
}
}

View File

@@ -41,7 +41,7 @@ class View extends Model
public static function incrementFor(Viewable $viewable): int
{
$user = user();
if (is_null($user) || $user->isDefault()) {
if ($user->isGuest()) {
return 0;
}

View File

@@ -0,0 +1,45 @@
<?php
namespace BookStack\Activity\Models;
use BookStack\Activity\WatchLevels;
use BookStack\Permissions\Models\JointPermission;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
/**
* @property int $id
* @property int $user_id
* @property int $watchable_id
* @property string $watchable_type
* @property int $level
* @property Carbon $created_at
* @property Carbon $updated_at
*/
class Watch extends Model
{
protected $guarded = [];
public function watchable(): MorphTo
{
return $this->morphTo();
}
public function jointPermissions(): HasMany
{
return $this->hasMany(JointPermission::class, 'entity_id', 'watchable_id')
->whereColumn('watches.watchable_type', '=', 'joint_permissions.entity_type');
}
public function getLevelName(): string
{
return WatchLevels::levelValueToName($this->level);
}
public function ignoring(): bool
{
return $this->level === WatchLevels::IGNORE;
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace BookStack\Activity\Notifications\Handlers;
use BookStack\Activity\Models\Loggable;
use BookStack\Activity\Notifications\Messages\BaseActivityNotification;
use BookStack\Entities\Models\Entity;
use BookStack\Permissions\PermissionApplicator;
use BookStack\Users\Models\User;
abstract class BaseNotificationHandler implements NotificationHandler
{
/**
* @param class-string<BaseActivityNotification> $notification
* @param int[] $userIds
*/
protected function sendNotificationToUserIds(string $notification, array $userIds, User $initiator, string|Loggable $detail, Entity $relatedModel): void
{
$users = User::query()->whereIn('id', array_unique($userIds))->get();
foreach ($users as $user) {
// Prevent sending to the user that initiated the activity
if ($user->id === $initiator->id) {
continue;
}
// Prevent sending of the user does not have notification permissions
if (!$user->can('receive-notifications')) {
continue;
}
// Prevent sending if the user does not have access to the related content
$permissions = new PermissionApplicator($user);
if (!$permissions->checkOwnableUserAccess($relatedModel, 'view')) {
continue;
}
// Send the notification
$user->notify(new $notification($detail, $initiator));
}
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace BookStack\Activity\Notifications\Handlers;
use BookStack\Activity\Models\Activity;
use BookStack\Activity\Models\Comment;
use BookStack\Activity\Models\Loggable;
use BookStack\Activity\Notifications\Messages\CommentCreationNotification;
use BookStack\Activity\Tools\EntityWatchers;
use BookStack\Activity\WatchLevels;
use BookStack\Entities\Models\Page;
use BookStack\Settings\UserNotificationPreferences;
use BookStack\Users\Models\User;
class CommentCreationNotificationHandler extends BaseNotificationHandler
{
public function handle(Activity $activity, Loggable|string $detail, User $user): void
{
if (!($detail instanceof Comment)) {
throw new \InvalidArgumentException("Detail for comment creation notifications must be a comment");
}
// Main watchers
/** @var Page $page */
$page = $detail->entity;
$watchers = new EntityWatchers($page, WatchLevels::COMMENTS);
$watcherIds = $watchers->getWatcherUserIds();
// Page owner if user preferences allow
if (!$watchers->isUserIgnoring($page->owned_by) && $page->ownedBy) {
$userNotificationPrefs = new UserNotificationPreferences($page->ownedBy);
if ($userNotificationPrefs->notifyOnOwnPageComments()) {
$watcherIds[] = $page->owned_by;
}
}
// Parent comment creator if preferences allow
$parentComment = $detail->parent()->first();
if ($parentComment && !$watchers->isUserIgnoring($parentComment->created_by) && $parentComment->createdBy) {
$parentCommenterNotificationsPrefs = new UserNotificationPreferences($parentComment->createdBy);
if ($parentCommenterNotificationsPrefs->notifyOnCommentReplies()) {
$watcherIds[] = $parentComment->created_by;
}
}
$this->sendNotificationToUserIds(CommentCreationNotification::class, $watcherIds, $user, $detail, $page);
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace BookStack\Activity\Notifications\Handlers;
use BookStack\Activity\Models\Activity;
use BookStack\Activity\Models\Loggable;
use BookStack\Users\Models\User;
interface NotificationHandler
{
/**
* Run this handler.
* Provides the activity, related activity detail/model
* along with the user that triggered the activity.
*/
public function handle(Activity $activity, string|Loggable $detail, User $user): void;
}

View File

@@ -0,0 +1,24 @@
<?php
namespace BookStack\Activity\Notifications\Handlers;
use BookStack\Activity\Models\Activity;
use BookStack\Activity\Models\Loggable;
use BookStack\Activity\Notifications\Messages\PageCreationNotification;
use BookStack\Activity\Tools\EntityWatchers;
use BookStack\Activity\WatchLevels;
use BookStack\Entities\Models\Page;
use BookStack\Users\Models\User;
class PageCreationNotificationHandler extends BaseNotificationHandler
{
public function handle(Activity $activity, Loggable|string $detail, User $user): void
{
if (!($detail instanceof Page)) {
throw new \InvalidArgumentException("Detail for page create notifications must be a page");
}
$watchers = new EntityWatchers($detail, WatchLevels::NEW);
$this->sendNotificationToUserIds(PageCreationNotification::class, $watchers->getWatcherUserIds(), $user, $detail, $detail);
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace BookStack\Activity\Notifications\Handlers;
use BookStack\Activity\ActivityType;
use BookStack\Activity\Models\Activity;
use BookStack\Activity\Models\Loggable;
use BookStack\Activity\Notifications\Messages\PageUpdateNotification;
use BookStack\Activity\Tools\EntityWatchers;
use BookStack\Activity\WatchLevels;
use BookStack\Entities\Models\Page;
use BookStack\Settings\UserNotificationPreferences;
use BookStack\Users\Models\User;
class PageUpdateNotificationHandler extends BaseNotificationHandler
{
public function handle(Activity $activity, Loggable|string $detail, User $user): void
{
if (!($detail instanceof Page)) {
throw new \InvalidArgumentException("Detail for page update notifications must be a page");
}
// Get last update from activity
$lastUpdate = $detail->activity()
->where('type', '=', ActivityType::PAGE_UPDATE)
->where('id', '!=', $activity->id)
->latest('created_at')
->first();
// Return if the same user has already updated the page in the last 15 mins
if ($lastUpdate && $lastUpdate->user_id === $user->id) {
if ($lastUpdate->created_at->gt(now()->subMinutes(15))) {
return;
}
}
// Get active watchers
$watchers = new EntityWatchers($detail, WatchLevels::UPDATES);
$watcherIds = $watchers->getWatcherUserIds();
// Add page owner if preferences allow
if (!$watchers->isUserIgnoring($detail->owned_by) && $detail->ownedBy) {
$userNotificationPrefs = new UserNotificationPreferences($detail->ownedBy);
if ($userNotificationPrefs->notifyOnOwnPageChanges()) {
$watcherIds[] = $detail->owned_by;
}
}
$this->sendNotificationToUserIds(PageUpdateNotification::class, $watcherIds, $user, $detail, $detail);
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace BookStack\Activity\Notifications\MessageParts;
use Illuminate\Contracts\Support\Htmlable;
use Stringable;
/**
* A line of text with linked text included, intended for use
* in MailMessages. The line should have a ':link' placeholder for
* where the link should be inserted within the line.
*/
class LinkedMailMessageLine implements Htmlable, Stringable
{
public function __construct(
protected string $url,
protected string $line,
protected string $linkText,
) {
}
public function toHtml(): string
{
$link = '<a href="' . e($this->url) . '">' . e($this->linkText) . '</a>';
return str_replace(':link', $link, e($this->line));
}
public function __toString(): string
{
$link = "{$this->linkText} ({$this->url})";
return str_replace(':link', $link, $this->line);
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace BookStack\Activity\Notifications\MessageParts;
use Illuminate\Contracts\Support\Htmlable;
use Stringable;
/**
* A bullet point list of content, where the keys of the given list array
* are bolded header elements, and the values follow.
*/
class ListMessageLine implements Htmlable, Stringable
{
public function __construct(
protected array $list
) {
}
public function toHtml(): string
{
$list = [];
foreach ($this->list as $header => $content) {
$list[] = '<strong>' . e($header) . '</strong> ' . e($content);
}
return implode("<br>\n", $list);
}
public function __toString(): string
{
$list = [];
foreach ($this->list as $header => $content) {
$list[] = $header . ' ' . $content;
}
return implode("\n", $list);
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace BookStack\Activity\Notifications\Messages;
use BookStack\Activity\Models\Loggable;
use BookStack\Activity\Notifications\MessageParts\LinkedMailMessageLine;
use BookStack\App\MailNotification;
use BookStack\Translation\LocaleDefinition;
use BookStack\Users\Models\User;
use Illuminate\Bus\Queueable;
abstract class BaseActivityNotification extends MailNotification
{
use Queueable;
public function __construct(
protected Loggable|string $detail,
protected User $user,
) {
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
'activity_detail' => $this->detail,
'activity_creator' => $this->user,
];
}
/**
* Build the common reason footer line used in mail messages.
*/
protected function buildReasonFooterLine(LocaleDefinition $locale): LinkedMailMessageLine
{
return new LinkedMailMessageLine(
url('/preferences/notifications'),
$locale->trans('notifications.footer_reason'),
$locale->trans('notifications.footer_reason_link'),
);
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace BookStack\Activity\Notifications\Messages;
use BookStack\Activity\Models\Comment;
use BookStack\Activity\Notifications\MessageParts\ListMessageLine;
use BookStack\Entities\Models\Page;
use BookStack\Users\Models\User;
use Illuminate\Notifications\Messages\MailMessage;
class CommentCreationNotification extends BaseActivityNotification
{
public function toMail(User $notifiable): MailMessage
{
/** @var Comment $comment */
$comment = $this->detail;
/** @var Page $page */
$page = $comment->entity;
$locale = $notifiable->getLocale();
return $this->newMailMessage($locale)
->subject($locale->trans('notifications.new_comment_subject', ['pageName' => $page->getShortName()]))
->line($locale->trans('notifications.new_comment_intro', ['appName' => setting('app-name')]))
->line(new ListMessageLine([
$locale->trans('notifications.detail_page_name') => $page->name,
$locale->trans('notifications.detail_commenter') => $this->user->name,
$locale->trans('notifications.detail_comment') => strip_tags($comment->html),
]))
->action($locale->trans('notifications.action_view_comment'), $page->getUrl('#comment' . $comment->local_id))
->line($this->buildReasonFooterLine($locale));
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace BookStack\Activity\Notifications\Messages;
use BookStack\Activity\Notifications\MessageParts\ListMessageLine;
use BookStack\Entities\Models\Page;
use BookStack\Users\Models\User;
use Illuminate\Notifications\Messages\MailMessage;
class PageCreationNotification extends BaseActivityNotification
{
public function toMail(User $notifiable): MailMessage
{
/** @var Page $page */
$page = $this->detail;
$locale = $notifiable->getLocale();
return $this->newMailMessage($locale)
->subject($locale->trans('notifications.new_page_subject', ['pageName' => $page->getShortName()]))
->line($locale->trans('notifications.new_page_intro', ['appName' => setting('app-name')], $locale))
->line(new ListMessageLine([
$locale->trans('notifications.detail_page_name') => $page->name,
$locale->trans('notifications.detail_created_by') => $this->user->name,
]))
->action($locale->trans('notifications.action_view_page'), $page->getUrl())
->line($this->buildReasonFooterLine($locale));
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace BookStack\Activity\Notifications\Messages;
use BookStack\Activity\Notifications\MessageParts\ListMessageLine;
use BookStack\Entities\Models\Page;
use BookStack\Users\Models\User;
use Illuminate\Notifications\Messages\MailMessage;
class PageUpdateNotification extends BaseActivityNotification
{
public function toMail(User $notifiable): MailMessage
{
/** @var Page $page */
$page = $this->detail;
$locale = $notifiable->getLocale();
return $this->newMailMessage($locale)
->subject($locale->trans('notifications.updated_page_subject', ['pageName' => $page->getShortName()]))
->line($locale->trans('notifications.updated_page_intro', ['appName' => setting('app-name')]))
->line(new ListMessageLine([
$locale->trans('notifications.detail_page_name') => $page->name,
$locale->trans('notifications.detail_updated_by') => $this->user->name,
]))
->line($locale->trans('notifications.updated_page_debounce'))
->action($locale->trans('notifications.action_view_page'), $page->getUrl())
->line($this->buildReasonFooterLine($locale));
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace BookStack\Activity\Notifications;
use BookStack\Activity\ActivityType;
use BookStack\Activity\Models\Activity;
use BookStack\Activity\Models\Loggable;
use BookStack\Activity\Notifications\Handlers\CommentCreationNotificationHandler;
use BookStack\Activity\Notifications\Handlers\NotificationHandler;
use BookStack\Activity\Notifications\Handlers\PageCreationNotificationHandler;
use BookStack\Activity\Notifications\Handlers\PageUpdateNotificationHandler;
use BookStack\Users\Models\User;
class NotificationManager
{
/**
* @var class-string<NotificationHandler>[]
*/
protected array $handlers = [];
public function handle(Activity $activity, string|Loggable $detail, User $user): void
{
$activityType = $activity->type;
$handlersToRun = $this->handlers[$activityType] ?? [];
foreach ($handlersToRun as $handlerClass) {
/** @var NotificationHandler $handler */
$handler = new $handlerClass();
$handler->handle($activity, $detail, $user);
}
}
/**
* @param class-string<NotificationHandler> $handlerClass
*/
public function registerHandler(string $activityType, string $handlerClass): void
{
if (!isset($this->handlers[$activityType])) {
$this->handlers[$activityType] = [];
}
if (!in_array($handlerClass, $this->handlers[$activityType])) {
$this->handlers[$activityType][] = $handlerClass;
}
}
public function loadDefaultHandlers(): void
{
$this->registerHandler(ActivityType::PAGE_CREATE, PageCreationNotificationHandler::class);
$this->registerHandler(ActivityType::PAGE_UPDATE, PageUpdateNotificationHandler::class);
$this->registerHandler(ActivityType::COMMENT_CREATE, CommentCreationNotificationHandler::class);
}
}

View File

@@ -6,6 +6,7 @@ use BookStack\Activity\DispatchWebhookJob;
use BookStack\Activity\Models\Activity;
use BookStack\Activity\Models\Loggable;
use BookStack\Activity\Models\Webhook;
use BookStack\Activity\Notifications\NotificationManager;
use BookStack\Entities\Models\Entity;
use BookStack\Facades\Theme;
use BookStack\Theming\ThemeEvents;
@@ -14,12 +15,16 @@ use Illuminate\Support\Facades\Log;
class ActivityLogger
{
public function __construct(
protected NotificationManager $notifications
) {
$this->notifications->loadDefaultHandlers();
}
/**
* Add a generic activity event to the database.
*
* @param string|Loggable $detail
*/
public function add(string $type, $detail = '')
public function add(string $type, string|Loggable $detail = ''): void
{
$detailToStore = ($detail instanceof Loggable) ? $detail->logDescriptor() : $detail;
@@ -35,6 +40,7 @@ class ActivityLogger
$this->setNotification($type);
$this->dispatchWebhooks($type, $detail);
$this->notifications->handle($activity, $detail, user());
Theme::dispatch(ThemeEvents::ACTIVITY_LOGGED, $type, $detail);
}
@@ -55,7 +61,7 @@ class ActivityLogger
* and instead uses the 'extra' field with the entities name.
* Used when an entity is deleted.
*/
public function removeEntity(Entity $entity)
public function removeEntity(Entity $entity): void
{
$entity->activity()->update([
'detail' => $entity->name,
@@ -76,10 +82,7 @@ class ActivityLogger
}
}
/**
* @param string|Loggable $detail
*/
protected function dispatchWebhooks(string $type, $detail): void
protected function dispatchWebhooks(string $type, string|Loggable $detail): void
{
$webhooks = Webhook::query()
->whereHas('trackedEvents', function (Builder $query) use ($type) {
@@ -98,7 +101,7 @@ class ActivityLogger
* Log out a failed login attempt, Providing the given username
* as part of the message if the '%u' string is used.
*/
public function logFailedLogin(string $username)
public function logFailedLogin(string $username): void
{
$message = config('logging.failed_login.message');
if (!$message) {

View File

@@ -0,0 +1,86 @@
<?php
namespace BookStack\Activity\Tools;
use BookStack\Activity\Models\Watch;
use BookStack\Entities\Models\BookChild;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Models\Page;
use Illuminate\Database\Eloquent\Builder;
class EntityWatchers
{
/**
* @var int[]
*/
protected array $watchers = [];
/**
* @var int[]
*/
protected array $ignorers = [];
public function __construct(
protected Entity $entity,
protected int $watchLevel,
) {
$this->build();
}
public function getWatcherUserIds(): array
{
return $this->watchers;
}
public function isUserIgnoring(int $userId): bool
{
return in_array($userId, $this->ignorers);
}
protected function build(): void
{
$watches = $this->getRelevantWatches();
// Sort before de-duping, so that the order looped below follows book -> chapter -> page ordering
usort($watches, function (Watch $watchA, Watch $watchB) {
$entityTypeDiff = $watchA->watchable_type <=> $watchB->watchable_type;
return $entityTypeDiff === 0 ? ($watchA->user_id <=> $watchB->user_id) : $entityTypeDiff;
});
// De-dupe by user id to get their most relevant level
$levelByUserId = [];
foreach ($watches as $watch) {
$levelByUserId[$watch->user_id] = $watch->level;
}
// Populate the class arrays
$this->watchers = array_keys(array_filter($levelByUserId, fn(int $level) => $level >= $this->watchLevel));
$this->ignorers = array_keys(array_filter($levelByUserId, fn(int $level) => $level === 0));
}
/**
* @return Watch[]
*/
protected function getRelevantWatches(): array
{
/** @var Entity[] $entitiesInvolved */
$entitiesInvolved = array_filter([
$this->entity,
$this->entity instanceof BookChild ? $this->entity->book : null,
$this->entity instanceof Page ? $this->entity->chapter : null,
]);
$query = Watch::query()->where(function (Builder $query) use ($entitiesInvolved) {
foreach ($entitiesInvolved as $entity) {
$query->orWhere(function (Builder $query) use ($entity) {
$query->where('watchable_type', '=', $entity->getMorphClass())
->where('watchable_id', '=', $entity->id);
});
}
});
return $query->get([
'level', 'watchable_id', 'watchable_type', 'user_id'
])->all();
}
}

View File

@@ -0,0 +1,131 @@
<?php
namespace BookStack\Activity\Tools;
use BookStack\Activity\Models\Watch;
use BookStack\Activity\WatchLevels;
use BookStack\Entities\Models\BookChild;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Models\Page;
use BookStack\Users\Models\User;
use Illuminate\Database\Eloquent\Builder;
class UserEntityWatchOptions
{
protected ?array $watchMap = null;
public function __construct(
protected User $user,
protected Entity $entity,
) {
}
public function canWatch(): bool
{
return $this->user->can('receive-notifications') && !$this->user->isGuest();
}
public function getWatchLevel(): string
{
return WatchLevels::levelValueToName($this->getWatchLevelValue());
}
public function isWatching(): bool
{
return $this->getWatchLevelValue() !== WatchLevels::DEFAULT;
}
public function getWatchedParent(): ?WatchedParentDetails
{
$watchMap = $this->getWatchMap();
unset($watchMap[$this->entity->getMorphClass()]);
if (isset($watchMap['chapter'])) {
return new WatchedParentDetails('chapter', $watchMap['chapter']);
}
if (isset($watchMap['book'])) {
return new WatchedParentDetails('book', $watchMap['book']);
}
return null;
}
public function updateLevelByName(string $level): void
{
$levelValue = WatchLevels::levelNameToValue($level);
$this->updateLevelByValue($levelValue);
}
public function updateLevelByValue(int $level): void
{
if ($level < 0) {
$this->remove();
return;
}
$this->updateLevel($level);
}
public function getWatchMap(): array
{
if (!is_null($this->watchMap)) {
return $this->watchMap;
}
$entities = [$this->entity];
if ($this->entity instanceof BookChild) {
$entities[] = $this->entity->book;
}
if ($this->entity instanceof Page && $this->entity->chapter) {
$entities[] = $this->entity->chapter;
}
$query = Watch::query()
->where('user_id', '=', $this->user->id)
->where(function (Builder $subQuery) use ($entities) {
foreach ($entities as $entity) {
$subQuery->orWhere(function (Builder $whereQuery) use ($entity) {
$whereQuery->where('watchable_type', '=', $entity->getMorphClass())
->where('watchable_id', '=', $entity->id);
});
}
});
$this->watchMap = $query->get(['watchable_type', 'level'])
->pluck('level', 'watchable_type')
->toArray();
return $this->watchMap;
}
protected function getWatchLevelValue()
{
return $this->getWatchMap()[$this->entity->getMorphClass()] ?? WatchLevels::DEFAULT;
}
protected function updateLevel(int $levelValue): void
{
Watch::query()->updateOrCreate([
'watchable_id' => $this->entity->id,
'watchable_type' => $this->entity->getMorphClass(),
'user_id' => $this->user->id,
], [
'level' => $levelValue,
]);
$this->watchMap = null;
}
protected function remove(): void
{
$this->entityQuery()->delete();
$this->watchMap = null;
}
protected function entityQuery(): Builder
{
return Watch::query()->where('watchable_id', '=', $this->entity->id)
->where('watchable_type', '=', $this->entity->getMorphClass())
->where('user_id', '=', $this->user->id);
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace BookStack\Activity\Tools;
use BookStack\Activity\WatchLevels;
class WatchedParentDetails
{
public function __construct(
public string $type,
public int $level,
) {
}
public function ignoring(): bool
{
return $this->level === WatchLevels::IGNORE;
}
}

View File

@@ -17,18 +17,14 @@ class WebhookFormatter
protected string $event;
protected User $initiator;
protected int $initiatedTime;
/**
* @var string|Loggable
*/
protected $detail;
protected string|Loggable $detail;
/**
* @var array{condition: callable(string, Model):bool, format: callable(Model):void}[]
*/
protected $modelFormatters = [];
public function __construct(string $event, Webhook $webhook, $detail, User $initiator, int $initiatedTime)
public function __construct(string $event, Webhook $webhook, string|Loggable $detail, User $initiator, int $initiatedTime)
{
$this->webhook = $webhook;
$this->event = $event;

View File

@@ -0,0 +1,91 @@
<?php
namespace BookStack\Activity;
use BookStack\Entities\Models\Bookshelf;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Models\Page;
class WatchLevels
{
/**
* Default level, No specific option set
* Typically not a stored status
*/
const DEFAULT = -1;
/**
* Ignore all notifications.
*/
const IGNORE = 0;
/**
* Watch for new content.
*/
const NEW = 1;
/**
* Watch for updates and new content
*/
const UPDATES = 2;
/**
* Watch for comments, updates and new content.
*/
const COMMENTS = 3;
/**
* Get all the possible values as an option_name => value array.
* @returns array<string, int>
*/
public static function all(): array
{
$options = [];
foreach ((new \ReflectionClass(static::class))->getConstants() as $name => $value) {
$options[strtolower($name)] = $value;
}
return $options;
}
/**
* Get the watch options suited for the given entity.
* @returns array<string, int>
*/
public static function allSuitedFor(Entity $entity): array
{
$options = static::all();
if ($entity instanceof Page) {
unset($options['new']);
} elseif ($entity instanceof Bookshelf) {
return [];
}
return $options;
}
/**
* Convert the given name to a level value.
* Defaults to default value if the level does not exist.
*/
public static function levelNameToValue(string $level): int
{
return static::all()[$level] ?? static::DEFAULT;
}
/**
* Convert the given int level value to a level name.
* Defaults to 'default' level name if not existing.
*/
public static function levelValueToName(int $level): string
{
foreach (static::all() as $name => $value) {
if ($level === $value) {
return $name;
}
}
return 'default';
}
}

View File

@@ -31,6 +31,8 @@ class ApiDocsController extends ApiController
/**
* Redirect to the API docs page.
* Required as a controller method, instead of the Route::redirect helper,
* to ensure the URL is generated correctly.
*/
public function redirect()
{

View File

@@ -7,6 +7,7 @@ use Exception;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Password;
@@ -27,13 +28,16 @@ class ApiDocsGenerator
{
$appVersion = trim(file_get_contents(base_path('version')));
$cacheKey = 'api-docs::' . $appVersion;
if (Cache::has($cacheKey) && config('app.env') === 'production') {
$docs = Cache::get($cacheKey);
} else {
$docs = (new ApiDocsGenerator())->generate();
Cache::put($cacheKey, $docs, 60 * 24);
$isProduction = config('app.env') === 'production';
$cacheVal = $isProduction ? Cache::get($cacheKey) : null;
if (!is_null($cacheVal)) {
return $cacheVal;
}
$docs = (new ApiDocsGenerator())->generate();
Cache::put($cacheKey, $docs, 60 * 24);
return $docs;
}

View File

@@ -10,7 +10,7 @@ class ApiEntityListFormatter
* The list to be formatted.
* @var Entity[]
*/
protected $list = [];
protected array $list = [];
/**
* The fields to show in the formatted data.
@@ -19,9 +19,9 @@ class ApiEntityListFormatter
* will be used for the resultant value. A null return value will omit the property.
* @var array<string|int, string|callable>
*/
protected $fields = [
'id', 'name', 'slug', 'book_id', 'chapter_id',
'draft', 'template', 'created_at', 'updated_at',
protected array $fields = [
'id', 'name', 'slug', 'book_id', 'chapter_id', 'draft',
'template', 'priority', 'created_at', 'updated_at',
];
public function __construct(array $list)

View File

@@ -4,6 +4,7 @@ namespace BookStack\Api;
use BookStack\Activity\Models\Loggable;
use BookStack\Users\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;
@@ -20,6 +21,8 @@ use Illuminate\Support\Carbon;
*/
class ApiToken extends Model implements Loggable
{
use HasFactory;
protected $fillable = ['name', 'expires_at'];
protected $casts = [
'expires_at' => 'date:Y-m-d',
@@ -49,4 +52,12 @@ class ApiToken extends Model implements Loggable
{
return "({$this->id}) {$this->name}; User: {$this->user->logDescriptor()}";
}
/**
* Get the URL for managing this token.
*/
public function getUrl(string $path = ''): string
{
return url("/api-tokens/{$this->user_id}/{$this->id}/" . trim($path, '/'));
}
}

View File

@@ -14,16 +14,19 @@ class UserApiTokenController extends Controller
/**
* Show the form to create a new API token.
*/
public function create(int $userId)
public function create(Request $request, int $userId)
{
// Ensure user is has access-api permission and is the current user or has permission to manage the current user.
$this->checkPermission('access-api');
$this->checkPermissionOrCurrentUser('users-manage', $userId);
$this->updateContext($request);
$user = User::query()->findOrFail($userId);
$this->setPageTitle(trans('settings.user_api_token_create'));
return view('users.api-tokens.create', [
'user' => $user,
'back' => $this->getRedirectPath($user),
]);
}
@@ -60,22 +63,27 @@ class UserApiTokenController extends Controller
session()->flash('api-token-secret:' . $token->id, $secret);
$this->logActivity(ActivityType::API_TOKEN_CREATE, $token);
return redirect($user->getEditUrl('/api-tokens/' . $token->id));
return redirect($token->getUrl());
}
/**
* Show the details for a user API token, with access to edit.
*/
public function edit(int $userId, int $tokenId)
public function edit(Request $request, int $userId, int $tokenId)
{
$this->updateContext($request);
[$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
$secret = session()->pull('api-token-secret:' . $token->id, null);
$this->setPageTitle(trans('settings.user_api_token'));
return view('users.api-tokens.edit', [
'user' => $user,
'token' => $token,
'model' => $token,
'secret' => $secret,
'back' => $this->getRedirectPath($user),
]);
}
@@ -97,7 +105,7 @@ class UserApiTokenController extends Controller
$this->logActivity(ActivityType::API_TOKEN_UPDATE, $token);
return redirect($user->getEditUrl('/api-tokens/' . $token->id));
return redirect($token->getUrl());
}
/**
@@ -107,6 +115,8 @@ class UserApiTokenController extends Controller
{
[$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
$this->setPageTitle(trans('settings.user_api_token_delete'));
return view('users.api-tokens.delete', [
'user' => $user,
'token' => $token,
@@ -123,7 +133,7 @@ class UserApiTokenController extends Controller
$this->logActivity(ActivityType::API_TOKEN_DELETE, $token);
return redirect($user->getEditUrl('#api_tokens'));
return redirect($this->getRedirectPath($user));
}
/**
@@ -142,4 +152,30 @@ class UserApiTokenController extends Controller
return [$user, $token];
}
/**
* Update the context for where the user is coming from to manage API tokens.
* (Track of location for correct return redirects)
*/
protected function updateContext(Request $request): void
{
$context = $request->query('context');
if ($context) {
session()->put('api-token-context', $context);
}
}
/**
* Get the redirect path for the current api token editing session.
* Attempts to recall the context of where the user is editing from.
*/
protected function getRedirectPath(User $relatedUser): string
{
$context = session()->get('api-token-context');
if ($context === 'settings' || user()->id !== $relatedUser->id) {
return $relatedUser->getEditUrl('#api_tokens');
}
return url('/my-account/auth#api_tokens');
}
}

View File

@@ -78,14 +78,14 @@ class HomeController extends Controller
}
if ($homepageOption === 'bookshelves') {
$shelves = app(BookshelfRepo::class)->getAllPaginated(18, $commonData['listOptions']->getSort(), $commonData['listOptions']->getOrder());
$shelves = app()->make(BookshelfRepo::class)->getAllPaginated(18, $commonData['listOptions']->getSort(), $commonData['listOptions']->getOrder());
$data = array_merge($commonData, ['shelves' => $shelves]);
return view('home.shelves', $data);
}
if ($homepageOption === 'books') {
$books = app(BookRepo::class)->getAllPaginated(18, $commonData['listOptions']->getSort(), $commonData['listOptions']->getOrder());
$books = app()->make(BookRepo::class)->getAllPaginated(18, $commonData['listOptions']->getSort(), $commonData['listOptions']->getOrder());
$data = array_merge($commonData, ['books' => $books]);
return view('home.books', $data);
@@ -140,4 +140,12 @@ class HomeController extends Controller
$exists = $favicons->restoreOriginalIfNotExists();
return response()->file($exists ? $favicons->getPath() : $favicons->getOriginalPath());
}
/**
* Serve a PWA application manifest.
*/
public function pwaManifest(PwaManifestBuilder $manifestBuilder)
{
return response()->json($manifestBuilder->build());
}
}

View File

@@ -1,16 +1,23 @@
<?php
namespace BookStack\Notifications;
namespace BookStack\App;
use BookStack\Translation\LocaleDefinition;
use BookStack\Users\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class MailNotification extends Notification implements ShouldQueue
abstract class MailNotification extends Notification implements ShouldQueue
{
use Queueable;
/**
* Get the mail representation of the notification.
*/
abstract public function toMail(User $notifiable): MailMessage;
/**
* Get the notification's channels.
*
@@ -25,14 +32,14 @@ class MailNotification extends Notification implements ShouldQueue
/**
* Create a new mail message.
*
* @return MailMessage
*/
protected function newMailMessage()
protected function newMailMessage(?LocaleDefinition $locale = null): MailMessage
{
$data = ['locale' => $locale ?? user()->getLocale()];
return (new MailMessage())->view([
'html' => 'vendor.notifications.email',
'text' => 'vendor.notifications.email-plain',
]);
], $data);
}
}

View File

@@ -9,15 +9,15 @@ use BookStack\Entities\Models\Bookshelf;
use BookStack\Entities\Models\Chapter;
use BookStack\Entities\Models\Page;
use BookStack\Exceptions\BookStackExceptionHandlerPage;
use BookStack\Http\HttpRequestService;
use BookStack\Permissions\PermissionApplicator;
use BookStack\Settings\SettingService;
use BookStack\Util\CspService;
use GuzzleHttp\Client;
use Illuminate\Contracts\Foundation\ExceptionRenderer;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
use Psr\Http\Client\ClientInterface as HttpClientInterface;
class AppServiceProvider extends ServiceProvider
{
@@ -38,6 +38,7 @@ class AppServiceProvider extends ServiceProvider
SettingService::class => SettingService::class,
SocialAuthService::class => SocialAuthService::class,
CspService::class => CspService::class,
HttpRequestService::class => HttpRequestService::class,
];
/**
@@ -50,7 +51,7 @@ class AppServiceProvider extends ServiceProvider
// Set root URL
$appUrl = config('app.url');
if ($appUrl) {
$isHttps = (strpos($appUrl, 'https://') === 0);
$isHttps = str_starts_with($appUrl, 'https://');
URL::forceRootUrl($appUrl);
URL::forceScheme($isHttps ? 'https' : 'http');
}
@@ -74,10 +75,8 @@ class AppServiceProvider extends ServiceProvider
*/
public function register()
{
$this->app->bind(HttpClientInterface::class, function ($app) {
return new Client([
'timeout' => 3,
]);
$this->app->singleton(PermissionApplicator::class, function ($app) {
return new PermissionApplicator(null);
});
}
}

View File

@@ -9,6 +9,7 @@ use BookStack\Access\LdapService;
use BookStack\Access\LoginService;
use BookStack\Access\RegistrationService;
use BookStack\Api\ApiTokenGuard;
use BookStack\Users\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
@@ -65,5 +66,11 @@ class AuthServiceProvider extends ServiceProvider
Auth::provider('external-users', function ($app, array $config) {
return new ExternalBaseUserProvider($config['model']);
});
// Bind and provide the default system user as a singleton to the app instance when needed.
// This effectively "caches" fetching the user at an app-instance level.
$this->app->singleton('users.default', function () {
return User::query()->where('system_name', '=', 'public')->first();
});
}
}

View File

@@ -3,7 +3,12 @@
namespace BookStack\App\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use SocialiteProviders\Azure\AzureExtendSocialite;
use SocialiteProviders\Discord\DiscordExtendSocialite;
use SocialiteProviders\GitLab\GitLabExtendSocialite;
use SocialiteProviders\Manager\SocialiteWasCalled;
use SocialiteProviders\Okta\OktaExtendSocialite;
use SocialiteProviders\Twitch\TwitchExtendSocialite;
class EventServiceProvider extends ServiceProvider
{
@@ -14,12 +19,11 @@ class EventServiceProvider extends ServiceProvider
*/
protected $listen = [
SocialiteWasCalled::class => [
'SocialiteProviders\Slack\SlackExtendSocialite@handle',
'SocialiteProviders\Azure\AzureExtendSocialite@handle',
'SocialiteProviders\Okta\OktaExtendSocialite@handle',
'SocialiteProviders\GitLab\GitLabExtendSocialite@handle',
'SocialiteProviders\Twitch\TwitchExtendSocialite@handle',
'SocialiteProviders\Discord\DiscordExtendSocialite@handle',
AzureExtendSocialite::class . '@handle',
OktaExtendSocialite::class . '@handle',
GitLabExtendSocialite::class . '@handle',
TwitchExtendSocialite::class . '@handle',
DiscordExtendSocialite::class . '@handle',
],
];

View File

@@ -25,7 +25,7 @@ class ViewTweaksServiceProvider extends ServiceProvider
// Custom blade view directives
Blade::directive('icon', function ($expression) {
return "<?php echo icon($expression); ?>";
return "<?php echo (new \BookStack\Util\SvgIcon($expression))->toHtml(); ?>";
});
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace BookStack\App;
class PwaManifestBuilder
{
public function build(): array
{
$darkMode = (bool) setting()->getForCurrentUser('dark-mode-enabled');
$appName = setting('app-name');
return [
"name" => $appName,
"short_name" => $appName,
"start_url" => "./",
"scope" => "/",
"display" => "standalone",
"background_color" => $darkMode ? '#111111' : '#F2F2F2',
"description" => $appName,
"theme_color" => ($darkMode ? setting('app-color-dark') : setting('app-color')),
"launch_handler" => [
"client_mode" => "focus-existing"
],
"orientation" => "portrait",
"icons" => [
[
"src" => setting('app-icon-32') ?: url('/icon-32.png'),
"sizes" => "32x32",
"type" => "image/png"
],
[
"src" => setting('app-icon-64') ?: url('/icon-64.png'),
"sizes" => "64x64",
"type" => "image/png"
],
[
"src" => setting('app-icon-128') ?: url('/icon-128.png'),
"sizes" => "128x128",
"type" => "image/png"
],
[
"src" => setting('app-icon-180') ?: url('/icon-180.png'),
"sizes" => "180x180",
"type" => "image/png"
],
[
"src" => setting('app-icon') ?: url('/icon.png'),
"sizes" => "256x256",
"type" => "image/png"
],
[
"src" => url('favicon.ico'),
"sizes" => "48x48",
"type" => "image/vnd.microsoft.icon"
],
],
];
}
}

View File

@@ -35,23 +35,7 @@ function versioned_asset(string $file = ''): string
*/
function user(): User
{
return auth()->user() ?: User::getDefault();
}
/**
* Check if current user is a signed in user.
*/
function signedInUser(): bool
{
return auth()->user() && !auth()->user()->isDefault();
}
/**
* Check if the current user has general access.
*/
function hasAppAccess(): bool
{
return !auth()->guest() || setting('app-public');
return auth()->user() ?: User::getGuest();
}
/**
@@ -61,11 +45,11 @@ function hasAppAccess(): bool
function userCan(string $permission, Model $ownable = null): bool
{
if ($ownable === null) {
return user() && user()->can($permission);
return user()->can($permission);
}
// Check permission on ownable item
$permissions = app(PermissionApplicator::class);
$permissions = app()->make(PermissionApplicator::class);
return $permissions->checkOwnableUserAccess($ownable, $permission);
}
@@ -76,7 +60,7 @@ function userCan(string $permission, Model $ownable = null): bool
*/
function userCanOnAny(string $action, string $entityClass = ''): bool
{
$permissions = app(PermissionApplicator::class);
$permissions = app()->make(PermissionApplicator::class);
return $permissions->checkUserHasEntityPermissionOnAny($action, $entityClass);
}
@@ -88,7 +72,7 @@ function userCanOnAny(string $action, string $entityClass = ''): bool
*/
function setting(string $key = null, $default = null)
{
$settingService = resolve(SettingService::class);
$settingService = app()->make(SettingService::class);
if (is_null($key)) {
return $settingService;
@@ -113,39 +97,6 @@ function theme_path(string $path = ''): ?string
return base_path('themes/' . $theme . ($path ? DIRECTORY_SEPARATOR . $path : $path));
}
/**
* Get fetch an SVG icon as a string.
* Checks for icons defined within a custom theme before defaulting back
* to the 'resources/assets/icons' folder.
*
* Returns an empty string if icon file not found.
*/
function icon(string $name, array $attrs = []): string
{
$attrs = array_merge([
'class' => 'svg-icon',
'data-icon' => $name,
'role' => 'presentation',
], $attrs);
$attrString = ' ';
foreach ($attrs as $attrName => $attr) {
$attrString .= $attrName . '="' . $attr . '" ';
}
$iconPath = resource_path('icons/' . $name . '.svg');
$themeIconPath = theme_path('icons/' . $name . '.svg');
if ($themeIconPath && file_exists($themeIconPath)) {
$iconPath = $themeIconPath;
} elseif (!file_exists($iconPath)) {
return '';
}
$fileContents = file_get_contents($iconPath);
return str_replace('<svg', '<svg' . $attrString, $fileContents);
}
/**
* Generate a URL with multiple parameters for sorting purposes.
* Works out the logic to set the correct sorting direction

View File

@@ -66,6 +66,15 @@ return [
// Current host and source for the "DRAWIO" setting will be auto-appended to the sources configured.
'iframe_sources' => env('ALLOWED_IFRAME_SOURCES', 'https://*.draw.io https://*.youtube.com https://*.youtube-nocookie.com https://*.vimeo.com'),
// A list of the sources/hostnames that can be reached by application SSR calls.
// This is used wherever users can provide URLs/hosts in-platform, like for webhooks.
// Host-specific functionality (usually controlled via other options) like auth
// or user avatars for example, won't use this list.
// Space seperated if multiple. Can use '*' as a wildcard.
// Values will be compared prefix-matched, case-insensitive, against called SSR urls.
// Defaults to allow all hosts.
'ssr_hosts' => env('ALLOWED_SSR_HOSTS', '*'),
// Alter the precision of IP addresses stored by BookStack.
// Integer value between 0 (IP hidden) to 4 (Full IP usage)
'ip_address_precision' => env('IP_ADDRESS_PRECISION', 4),
@@ -74,10 +83,10 @@ return [
'timezone' => env('APP_TIMEZONE', 'UTC'),
// Default locale to use
// A default variant is also stored since Laravel can overwrite
// app.locale when dynamically setting the locale in-app.
'locale' => env('APP_LANG', 'en'),
// Locales available
'locales' => ['en', 'ar', 'bg', 'bs', 'ca', 'cs', 'cy', 'da', 'de', 'de_informal', 'el', 'es', 'es_AR', 'et', 'eu', 'fa', 'fr', 'he', 'hr', 'hu', 'id', 'it', 'ja', 'ka', 'ko', 'lt', 'lv', 'nl', 'nb', 'pt', 'pt_BR', 'sk', 'sl', 'sv', 'pl', 'ro', 'ru', 'tr', 'uk', 'uz', 'vi', 'zh_CN', 'zh_TW'],
'default_locale' => env('APP_LANG', 'en'),
// Application Fallback Locale
'fallback_locale' => 'en',
@@ -85,9 +94,6 @@ return [
// Faker Locale
'faker_locale' => 'en_GB',
// Enable right-to-left text control.
'rtl' => false,
// Auto-detect the locale for public users
// For public users their locale can be guessed by headers sent by their
// browser. This is usually set by users in their browser settings.

View File

@@ -22,7 +22,7 @@ return [
// Global "From" address & name
'from' => [
'address' => env('MAIL_FROM', 'mail@bookstackapp.com'),
'address' => env('MAIL_FROM', 'bookstack@example.com'),
'name' => env('MAIL_FROM_NAME', 'BookStack'),
],
@@ -31,7 +31,7 @@ return [
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => ($mailEncryption === 'tls' || $mailEncryption === 'ssl') ? 'smtps' : null,
'scheme' => null,
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'username' => env('MAIL_USERNAME'),
@@ -39,6 +39,7 @@ return [
'verify_peer' => env('MAIL_VERIFY_SSL', true),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN'),
'tls_required' => ($mailEncryption === 'tls' || $mailEncryption === 'ssl'),
],
'sendmail' => [

View File

@@ -9,7 +9,7 @@ return [
'dump_user_details' => env('OIDC_DUMP_USER_DETAILS', false),
// Claim, within an OpenId token, to find the user's display name
'display_name_claims' => explode('|', env('OIDC_DISPLAY_NAME_CLAIMS', 'name')),
'display_name_claims' => env('OIDC_DISPLAY_NAME_CLAIMS', 'name'),
// Claim, within an OpenID token, to use to connect a BookStack user to the OIDC user.
'external_id_claim' => env('OIDC_EXTERNAL_ID_CLAIM', 'sub'),

View File

@@ -35,7 +35,7 @@ class CleanupImagesCommand extends Command
if (!$dryRun) {
$this->warn("This operation is destructive and is not guaranteed to be fully accurate.\nEnsure you have a backup of your images.\n");
$proceed = $this->confirm("Are you sure you want to proceed?");
$proceed = !$this->input->isInteractive() || $this->confirm("Are you sure you want to proceed?");
if (!$proceed) {
return 0;
}
@@ -46,7 +46,7 @@ class CleanupImagesCommand extends Command
if ($dryRun) {
$this->comment('Dry run, no images have been deleted');
$this->comment($deleteCount . ' images found that would have been deleted');
$this->comment($deleteCount . ' image(s) found that would have been deleted');
$this->showDeletedImages($deleted);
$this->comment('Run with -f or --force to perform deletions');
@@ -54,7 +54,8 @@ class CleanupImagesCommand extends Command
}
$this->showDeletedImages($deleted);
$this->comment($deleteCount . ' images deleted');
$this->comment("{$deleteCount} image(s) deleted");
return 0;
}
@@ -65,7 +66,7 @@ class CleanupImagesCommand extends Command
}
if (count($paths) > 0) {
$this->line('Images to delete:');
$this->line('Image(s) to delete:');
}
foreach ($paths as $path) {

View File

@@ -0,0 +1,40 @@
<?php
namespace BookStack\Console\Commands;
use BookStack\Users\Models\User;
use Exception;
use Illuminate\Console\Command;
/**
* @mixin Command
*/
trait HandlesSingleUser
{
/**
* Fetch a user provided to this command.
* Expects the command to accept 'id' and 'email' options.
* @throws Exception
*/
private function fetchProvidedUser(): User
{
$id = $this->option('id');
$email = $this->option('email');
if (!$id && !$email) {
throw new Exception("Either a --id=<number> or --email=<email> option must be provided.\nRun this command with `--help` to show more options.");
}
$field = $id ? 'id' : 'email';
$value = $id ?: $email;
$user = User::query()
->where($field, '=', $value)
->first();
if (!$user) {
throw new Exception("A user where {$field}={$value} could not be found.");
}
return $user;
}
}

View File

@@ -0,0 +1,116 @@
<?php
namespace BookStack\Console\Commands;
use BookStack\Users\Models\User;
use Exception;
use Illuminate\Console\Command;
use BookStack\Uploads\UserAvatars;
class RefreshAvatarCommand extends Command
{
use HandlesSingleUser;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'bookstack:refresh-avatar
{--id= : Numeric ID of the user to refresh avatar for}
{--email= : Email address of the user to refresh avatar for}
{--users-without-avatars : Refresh avatars for users that currently have no avatar}
{--a|all : Refresh avatars for all users}
{--f|force : Actually run the update, Defaults to a dry-run}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Refresh avatar for the given user(s)';
public function handle(UserAvatars $userAvatar): int
{
if (!$userAvatar->avatarFetchEnabled()) {
$this->error("Avatar fetching is disabled on this instance.");
return self::FAILURE;
}
if ($this->option('users-without-avatars')) {
return $this->processUsers(User::query()->whereDoesntHave('avatar')->get()->all(), $userAvatar);
}
if ($this->option('all')) {
return $this->processUsers(User::query()->get()->all(), $userAvatar);
}
try {
$user = $this->fetchProvidedUser();
return $this->processUsers([$user], $userAvatar);
} catch (Exception $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
}
/**
* @param User[] $users
*/
private function processUsers(array $users, UserAvatars $userAvatar): int
{
$dryRun = !$this->option('force');
$this->info(count($users) . " user(s) found to update avatars for.");
if (count($users) === 0) {
return self::SUCCESS;
}
if (!$dryRun) {
$fetchHost = parse_url($userAvatar->getAvatarUrl(), PHP_URL_HOST);
$this->warn("This will destroy any existing avatar images these users have, and attempt to fetch new avatar images from {$fetchHost}.");
$proceed = !$this->input->isInteractive() || $this->confirm('Are you sure you want to proceed?');
if (!$proceed) {
return self::SUCCESS;
}
}
$this->info("");
$exitCode = self::SUCCESS;
foreach ($users as $user) {
$linePrefix = "[ID: {$user->id}] $user->email -";
if ($dryRun) {
$this->warn("{$linePrefix} Not updated");
continue;
}
if ($this->fetchAvatar($userAvatar, $user)) {
$this->info("{$linePrefix} Updated");
} else {
$this->error("{$linePrefix} Not updated");
$exitCode = self::FAILURE;
}
}
if ($dryRun) {
$this->comment("");
$this->comment("Dry run, no avatars were updated.");
$this->comment('Run with -f or --force to perform the update.');
}
return $exitCode;
}
private function fetchAvatar(UserAvatars $userAvatar, User $user): bool
{
$oldId = $user->avatar->id ?? 0;
$userAvatar->fetchAndAssignToUser($user);
$user->refresh();
$newId = $user->avatar->id ?? $oldId;
return $oldId !== $newId;
}
}

View File

@@ -2,11 +2,13 @@
namespace BookStack\Console\Commands;
use BookStack\Users\Models\User;
use Exception;
use Illuminate\Console\Command;
class ResetMfaCommand extends Command
{
use HandlesSingleUser;
/**
* The name and signature of the console command.
*
@@ -29,25 +31,10 @@ class ResetMfaCommand extends Command
*/
public function handle(): int
{
$id = $this->option('id');
$email = $this->option('email');
if (!$id && !$email) {
$this->error('Either a --id=<number> or --email=<email> option must be provided.');
return 1;
}
$field = $id ? 'id' : 'email';
$value = $id ?: $email;
/** @var User $user */
$user = User::query()
->where($field, '=', $value)
->first();
if (!$user) {
$this->error("A user where {$field}={$value} could not be found.");
try {
$user = $this->fetchProvidedUser();
} catch (Exception $exception) {
$this->error($exception->getMessage());
return 1;
}

View File

@@ -8,29 +8,21 @@ use Illuminate\View\View;
class BreadcrumbsViewComposer
{
protected $entityContextManager;
/**
* BreadcrumbsViewComposer constructor.
*
* @param ShelfContext $entityContextManager
*/
public function __construct(ShelfContext $entityContextManager)
{
$this->entityContextManager = $entityContextManager;
public function __construct(
protected ShelfContext $shelfContext
) {
}
/**
* Modify data when the view is composed.
*
* @param View $view
*/
public function compose(View $view)
public function compose(View $view): void
{
$crumbs = $view->getData()['crumbs'];
$firstCrumb = $crumbs[0] ?? null;
if ($firstCrumb instanceof Book) {
$shelf = $this->entityContextManager->getContextualShelfForBook($firstCrumb);
$shelf = $this->shelfContext->getContextualShelfForBook($firstCrumb);
if ($shelf) {
array_unshift($crumbs, $shelf);
$view->with('crumbs', $crumbs);

View File

@@ -5,6 +5,7 @@ namespace BookStack\Entities\Controllers;
use BookStack\Activity\ActivityQueries;
use BookStack\Activity\ActivityType;
use BookStack\Activity\Models\View;
use BookStack\Activity\Tools\UserEntityWatchOptions;
use BookStack\Entities\Models\Bookshelf;
use BookStack\Entities\Repos\BookRepo;
use BookStack\Entities\Tools\BookContents;
@@ -138,6 +139,7 @@ class BookController extends Controller
'current' => $book,
'bookChildren' => $bookChildren,
'bookParentShelves' => $bookParentShelves,
'watchOptions' => new UserEntityWatchOptions(user(), $book),
'activity' => $activities->entityActivity($book, 20, 1),
'referenceCount' => $this->referenceFetcher->getPageReferenceCountToEntity($book),
]);

View File

@@ -19,12 +19,14 @@ class ChapterApiController extends ApiController
'name' => ['required', 'string', 'max:255'],
'description' => ['string', 'max:1000'],
'tags' => ['array'],
'priority' => ['integer'],
],
'update' => [
'book_id' => ['integer'],
'name' => ['string', 'min:1', 'max:255'],
'description' => ['string', 'max:1000'],
'tags' => ['array'],
'priority' => ['integer'],
],
];

View File

@@ -3,6 +3,7 @@
namespace BookStack\Entities\Controllers;
use BookStack\Activity\Models\View;
use BookStack\Activity\Tools\UserEntityWatchOptions;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Repos\ChapterRepo;
use BookStack\Entities\Tools\BookContents;
@@ -81,6 +82,7 @@ class ChapterController extends Controller
'chapter' => $chapter,
'current' => $chapter,
'sidebarTree' => $sidebarTree,
'watchOptions' => new UserEntityWatchOptions(user(), $chapter),
'pages' => $pages,
'next' => $nextPreviousLocator->getNext(),
'previous' => $nextPreviousLocator->getPrevious(),

View File

@@ -21,6 +21,7 @@ class PageApiController extends ApiController
'html' => ['required_without:markdown', 'string'],
'markdown' => ['required_without:html', 'string'],
'tags' => ['array'],
'priority' => ['integer'],
],
'update' => [
'book_id' => ['integer'],
@@ -29,6 +30,7 @@ class PageApiController extends ApiController
'html' => ['string'],
'markdown' => ['string'],
'tags' => ['array'],
'priority' => ['integer'],
],
];

View File

@@ -4,6 +4,7 @@ namespace BookStack\Entities\Controllers;
use BookStack\Activity\Models\View;
use BookStack\Activity\Tools\CommentTree;
use BookStack\Activity\Tools\UserEntityWatchOptions;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Repos\PageRepo;
use BookStack\Entities\Tools\BookContents;
@@ -151,6 +152,7 @@ class PageController extends Controller
'sidebarTree' => $sidebarTree,
'commentTree' => $commentTree,
'pageNav' => $pageNav,
'watchOptions' => new UserEntityWatchOptions(user(), $page),
'next' => $nextPreviousLocator->getNext(),
'previous' => $nextPreviousLocator->getPrevious(),
'referenceCount' => $this->referenceFetcher->getPageReferenceCountToEntity($page),

View File

@@ -37,7 +37,7 @@ class EntityProvider
* Fetch all core entity types as an associated array
* with their basic names as the keys.
*
* @return array<Entity>
* @return array<string, Entity>
*/
public function all(): array
{

View File

@@ -40,26 +40,19 @@ class Book extends Entity implements HasCoverImage
/**
* Returns book cover image, if book cover not exists return default cover image.
*
* @param int $width - Width of the image
* @param int $height - Height of the image
*
* @return string
*/
public function getBookCover($width = 440, $height = 250)
public function getBookCover(int $width = 440, int $height = 250): string
{
$default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
if (!$this->image_id) {
if (!$this->image_id || !$this->cover) {
return $default;
}
try {
$cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
return $this->cover->getThumb($width, $height, false) ?? $default;
} catch (Exception $err) {
$cover = $default;
return $default;
}
return $cover;
}
/**

View File

@@ -3,6 +3,7 @@
namespace BookStack\Entities\Models;
use BookStack\Uploads\Image;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
@@ -49,28 +50,21 @@ class Bookshelf extends Entity implements HasCoverImage
}
/**
* Returns BookShelf cover image, if cover does not exists return default cover image.
*
* @param int $width - Width of the image
* @param int $height - Height of the image
*
* @return string
* Returns shelf cover image, if cover not exists return default cover image.
*/
public function getBookCover($width = 440, $height = 250)
public function getBookCover(int $width = 440, int $height = 250): string
{
// TODO - Make generic, focused on books right now, Perhaps set-up a better image
$default = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
if (!$this->image_id) {
if (!$this->image_id || !$this->cover) {
return $default;
}
try {
$cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
} catch (\Exception $err) {
$cover = $default;
return $this->cover->getThumb($width, $height, false) ?? $default;
} catch (Exception $err) {
return $default;
}
return $cover;
}
/**

View File

@@ -10,6 +10,7 @@ use BookStack\Activity\Models\Loggable;
use BookStack\Activity\Models\Tag;
use BookStack\Activity\Models\View;
use BookStack\Activity\Models\Viewable;
use BookStack\Activity\Models\Watch;
use BookStack\App\Model;
use BookStack\App\Sluggable;
use BookStack\Entities\Tools\SlugGenerator;
@@ -330,6 +331,14 @@ abstract class Entity extends Model implements Sluggable, Favouritable, Viewable
->exists();
}
/**
* Get the related watches for this entity.
*/
public function watches(): MorphMany
{
return $this->morphMany(Watch::class, 'watchable');
}
/**
* {@inheritdoc}
*/

View File

@@ -10,7 +10,7 @@ class RecentlyViewed extends EntityQuery
public function run(int $count, int $page): Collection
{
$user = user();
if ($user === null || $user->isDefault()) {
if ($user === null || $user->isGuest()) {
return collect();
}

View File

@@ -10,7 +10,7 @@ class TopFavourites extends EntityQuery
public function run(int $count, int $skip = 0)
{
$user = user();
if (is_null($user) || $user->isDefault()) {
if ($user->isGuest()) {
return collect();
}

View File

@@ -16,14 +16,9 @@ use Exception;
class ChapterRepo
{
protected $baseRepo;
/**
* ChapterRepo constructor.
*/
public function __construct(BaseRepo $baseRepo)
{
$this->baseRepo = $baseRepo;
public function __construct(
protected BaseRepo $baseRepo
) {
}
/**

View File

@@ -23,24 +23,12 @@ use Illuminate\Pagination\LengthAwarePaginator;
class PageRepo
{
protected BaseRepo $baseRepo;
protected RevisionRepo $revisionRepo;
protected ReferenceStore $referenceStore;
protected ReferenceUpdater $referenceUpdater;
/**
* PageRepo constructor.
*/
public function __construct(
BaseRepo $baseRepo,
RevisionRepo $revisionRepo,
ReferenceStore $referenceStore,
ReferenceUpdater $referenceUpdater
protected BaseRepo $baseRepo,
protected RevisionRepo $revisionRepo,
protected ReferenceStore $referenceStore,
protected ReferenceUpdater $referenceUpdater
) {
$this->baseRepo = $baseRepo;
$this->revisionRepo = $revisionRepo;
$this->referenceStore = $referenceStore;
$this->referenceUpdater = $referenceUpdater;
}
/**
@@ -159,13 +147,11 @@ class PageRepo
*/
public function publishDraft(Page $draft, array $input): Page
{
$this->updateTemplateStatusAndContentFromInput($draft, $input);
$this->baseRepo->update($draft, $input);
$draft->draft = false;
$draft->revision_count = 1;
$draft->priority = $this->getNewPriority($draft);
$draft->save();
$this->updateTemplateStatusAndContentFromInput($draft, $input);
$this->baseRepo->update($draft, $input);
$this->revisionRepo->storeNewForPage($draft, trans('entities.pages_initial_revision'));
$this->referenceStore->updateForPage($draft);

View File

@@ -16,18 +16,11 @@ use Throwable;
class ExportFormatter
{
protected ImageService $imageService;
protected PdfGenerator $pdfGenerator;
protected CspService $cspService;
/**
* ExportService constructor.
*/
public function __construct(ImageService $imageService, PdfGenerator $pdfGenerator, CspService $cspService)
{
$this->imageService = $imageService;
$this->pdfGenerator = $pdfGenerator;
$this->cspService = $cspService;
public function __construct(
protected ImageService $imageService,
protected PdfGenerator $pdfGenerator,
protected CspService $cspService
) {
}
/**
@@ -36,13 +29,14 @@ class ExportFormatter
*
* @throws Throwable
*/
public function pageToContainedHtml(Page $page)
public function pageToContainedHtml(Page $page): string
{
$page->html = (new PageContent($page))->render();
$pageHtml = view('exports.page', [
'page' => $page,
'format' => 'html',
'cspContent' => $this->cspService->getCspMetaTagValue(),
'locale' => user()->getLocale(),
])->render();
return $this->containHtml($pageHtml);
@@ -53,7 +47,7 @@ class ExportFormatter
*
* @throws Throwable
*/
public function chapterToContainedHtml(Chapter $chapter)
public function chapterToContainedHtml(Chapter $chapter): string
{
$pages = $chapter->getVisiblePages();
$pages->each(function ($page) {
@@ -64,6 +58,7 @@ class ExportFormatter
'pages' => $pages,
'format' => 'html',
'cspContent' => $this->cspService->getCspMetaTagValue(),
'locale' => user()->getLocale(),
])->render();
return $this->containHtml($html);
@@ -74,7 +69,7 @@ class ExportFormatter
*
* @throws Throwable
*/
public function bookToContainedHtml(Book $book)
public function bookToContainedHtml(Book $book): string
{
$bookTree = (new BookContents($book))->getTree(false, true);
$html = view('exports.book', [
@@ -82,6 +77,7 @@ class ExportFormatter
'bookChildren' => $bookTree,
'format' => 'html',
'cspContent' => $this->cspService->getCspMetaTagValue(),
'locale' => user()->getLocale(),
])->render();
return $this->containHtml($html);
@@ -92,13 +88,14 @@ class ExportFormatter
*
* @throws Throwable
*/
public function pageToPdf(Page $page)
public function pageToPdf(Page $page): string
{
$page->html = (new PageContent($page))->render();
$html = view('exports.page', [
'page' => $page,
'format' => 'pdf',
'engine' => $this->pdfGenerator->getActiveEngine(),
'locale' => user()->getLocale(),
])->render();
return $this->htmlToPdf($html);
@@ -109,7 +106,7 @@ class ExportFormatter
*
* @throws Throwable
*/
public function chapterToPdf(Chapter $chapter)
public function chapterToPdf(Chapter $chapter): string
{
$pages = $chapter->getVisiblePages();
$pages->each(function ($page) {
@@ -121,6 +118,7 @@ class ExportFormatter
'pages' => $pages,
'format' => 'pdf',
'engine' => $this->pdfGenerator->getActiveEngine(),
'locale' => user()->getLocale(),
])->render();
return $this->htmlToPdf($html);
@@ -131,7 +129,7 @@ class ExportFormatter
*
* @throws Throwable
*/
public function bookToPdf(Book $book)
public function bookToPdf(Book $book): string
{
$bookTree = (new BookContents($book))->getTree(false, true);
$html = view('exports.book', [
@@ -139,6 +137,7 @@ class ExportFormatter
'bookChildren' => $bookTree,
'format' => 'pdf',
'engine' => $this->pdfGenerator->getActiveEngine(),
'locale' => user()->getLocale(),
])->render();
return $this->htmlToPdf($html);
@@ -194,7 +193,7 @@ class ExportFormatter
/** @var DOMElement $iframe */
foreach ($iframes as $iframe) {
$link = $iframe->getAttribute('src');
if (strpos($link, '//') === 0) {
if (str_starts_with($link, '//')) {
$link = 'https:' . $link;
}
@@ -223,7 +222,7 @@ class ExportFormatter
foreach ($imageTagsOutput[0] as $index => $imgMatch) {
$oldImgTagString = $imgMatch;
$srcString = $imageTagsOutput[2][$index];
$imageEncoded = $this->imageService->imageUriToBase64($srcString);
$imageEncoded = $this->imageService->imageUrlToBase64($srcString);
if ($imageEncoded === null) {
$imageEncoded = $srcString;
}
@@ -240,7 +239,7 @@ class ExportFormatter
foreach ($linksOutput[0] as $index => $linkMatch) {
$oldLinkString = $linkMatch;
$srcString = $linksOutput[2][$index];
if (strpos(trim($srcString), 'http') !== 0) {
if (!str_starts_with(trim($srcString), 'http')) {
$newSrcString = url($srcString);
$newLinkString = str_replace($srcString, $newSrcString, $oldLinkString);
$htmlContent = str_replace($oldLinkString, $newLinkString, $htmlContent);
@@ -255,17 +254,20 @@ class ExportFormatter
* Converts the page contents into simple plain text.
* This method filters any bad looking content to provide a nice final output.
*/
public function pageToPlainText(Page $page): string
public function pageToPlainText(Page $page, bool $pageRendered = false, bool $fromParent = false): string
{
$html = (new PageContent($page))->render();
$text = strip_tags($html);
$html = $pageRendered ? $page->html : (new PageContent($page))->render();
// Add proceeding spaces before tags so spaces remain between
// text within elements after stripping tags.
$html = str_replace('<', " <", $html);
$text = trim(strip_tags($html));
// Replace multiple spaces with single spaces
$text = preg_replace('/\ {2,}/', ' ', $text);
$text = preg_replace('/ {2,}/', ' ', $text);
// Reduce multiple horrid whitespace characters.
$text = preg_replace('/(\x0A|\xA0|\x0A|\r|\n){2,}/su', "\n\n", $text);
$text = html_entity_decode($text);
// Add title
$text = $page->name . "\n\n" . $text;
$text = $page->name . ($fromParent ? "\n" : "\n\n") . $text;
return $text;
}
@@ -275,13 +277,15 @@ class ExportFormatter
*/
public function chapterToPlainText(Chapter $chapter): string
{
$text = $chapter->name . "\n\n";
$text .= $chapter->description . "\n\n";
$text = $chapter->name . "\n" . $chapter->description;
$text = trim($text) . "\n\n";
$parts = [];
foreach ($chapter->getVisiblePages() as $page) {
$text .= $this->pageToPlainText($page);
$parts[] = $this->pageToPlainText($page, false, true);
}
return $text;
return $text . implode("\n\n", $parts);
}
/**
@@ -289,17 +293,20 @@ class ExportFormatter
*/
public function bookToPlainText(Book $book): string
{
$bookTree = (new BookContents($book))->getTree(false, false);
$text = $book->name . "\n\n";
$bookTree = (new BookContents($book))->getTree(false, true);
$text = $book->name . "\n" . $book->description;
$text = rtrim($text) . "\n\n";
$parts = [];
foreach ($bookTree as $bookChild) {
if ($bookChild->isA('chapter')) {
$text .= $this->chapterToPlainText($bookChild);
$parts[] = $this->chapterToPlainText($bookChild);
} else {
$text .= $this->pageToPlainText($bookChild);
$parts[] = $this->pageToPlainText($bookChild, true, true);
}
}
return $text;
return $text . implode("\n\n", $parts);
}
/**

View File

@@ -0,0 +1,39 @@
<?php
namespace BookStack\Entities\Tools;
use BookStack\Entities\EntityProvider;
use BookStack\Entities\Models\Entity;
class MixedEntityRequestHelper
{
public function __construct(
protected EntityProvider $entities,
) {
}
/**
* Query out an entity, visible to the current user, for the given
* entity request details (this provided in a request validated by
* this classes' validationRules method).
* @param array{type: string, id: string} $requestData
*/
public function getVisibleEntityFromRequestData(array $requestData): Entity
{
$entityType = $this->entities->get($requestData['type']);
return $entityType->newQuery()->scopes(['visible'])->findOrFail($requestData['id']);
}
/**
* Get the validation rules for an abstract entity request.
* @return array{type: string[], id: string[]}
*/
public function validationRules(): array
{
return [
'type' => ['required', 'string'],
'id' => ['required', 'integer'],
];
}
}

View File

@@ -197,7 +197,7 @@ class TrashCan
$page->allRevisions()->delete();
// Delete Attached Files
$attachmentService = app(AttachmentService::class);
$attachmentService = app()->make(AttachmentService::class);
foreach ($page->attachments as $attachment) {
$attachmentService->deleteFile($attachment);
}
@@ -376,6 +376,7 @@ class TrashCan
$entity->searchTerms()->delete();
$entity->deletions()->delete();
$entity->favourites()->delete();
$entity->watches()->delete();
$entity->referencesTo()->delete();
$entity->referencesFrom()->delete();

View File

@@ -6,9 +6,11 @@ use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\PostTooLargeException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\ErrorHandler\Error\FatalError;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Throwable;
@@ -35,6 +37,15 @@ class Handler extends ExceptionHandler
'password_confirmation',
];
/**
* A function to run upon out of memory.
* If it returns a response, that will be provided back to the request
* upon an out of memory event.
*
* @var ?callable<?\Illuminate\Http\Response>
*/
protected $onOutOfMemory = null;
/**
* Report or log an exception.
*
@@ -59,6 +70,17 @@ class Handler extends ExceptionHandler
*/
public function render($request, Throwable $e)
{
if ($e instanceof FatalError && str_contains($e->getMessage(), 'bytes exhausted (tried to allocate') && $this->onOutOfMemory) {
$response = call_user_func($this->onOutOfMemory);
if ($response) {
return $response;
}
}
if ($e instanceof PostTooLargeException) {
$e = new NotifyException(trans('errors.server_post_limit'), '/', 413);
}
if ($this->isApiRequest($request)) {
return $this->renderApiException($e);
}
@@ -66,12 +88,30 @@ class Handler extends ExceptionHandler
return parent::render($request, $e);
}
/**
* Provide a function to be called when an out of memory event occurs.
* If the callable returns a response, this response will be returned
* to the request upon error.
*/
public function prepareForOutOfMemory(callable $onOutOfMemory)
{
$this->onOutOfMemory = $onOutOfMemory;
}
/**
* Forget the current out of memory handler, if existing.
*/
public function forgetOutOfMemoryHandler()
{
$this->onOutOfMemory = null;
}
/**
* Check if the given request is an API request.
*/
protected function isApiRequest(Request $request): bool
{
return strpos($request->path(), 'api/') === 0;
return str_starts_with($request->path(), 'api/');
}
/**

View File

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

View File

@@ -66,6 +66,16 @@ abstract class Controller extends BaseController
}
}
/**
* Prevent access for guest users beyond this point.
*/
protected function preventGuestAccess(): void
{
if (user()->isGuest()) {
$this->showPermissionError();
}
}
/**
* Check the current user's permissions against an ownable item otherwise throw an exception.
*/

View File

@@ -0,0 +1,33 @@
<?php
namespace BookStack\Http;
use GuzzleHttp\Psr7\Request as GuzzleRequest;
class HttpClientHistory
{
public function __construct(
protected &$container
) {
}
public function requestCount(): int
{
return count($this->container);
}
public function requestAt(int $index): ?GuzzleRequest
{
return $this->container[$index]['request'] ?? null;
}
public function latestRequest(): ?GuzzleRequest
{
return $this->requestAt($this->requestCount() - 1);
}
public function all(): array
{
return $this->container;
}
}

View File

@@ -0,0 +1,70 @@
<?php
namespace BookStack\Http;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request as GuzzleRequest;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Client\ClientInterface;
class HttpRequestService
{
protected ?HandlerStack $handler = null;
/**
* Build a new http client for sending requests on.
*/
public function buildClient(int $timeout, array $options = []): ClientInterface
{
$defaultOptions = [
'timeout' => $timeout,
'handler' => $this->handler,
];
return new Client(array_merge($options, $defaultOptions));
}
/**
* Create a new JSON http request for use with a client.
*/
public function jsonRequest(string $method, string $uri, array $data): GuzzleRequest
{
$headers = ['Content-Type' => 'application/json'];
return new GuzzleRequest($method, $uri, $headers, json_encode($data));
}
/**
* Mock any http clients built from this service, and response with the given responses.
* Returns history which can then be queried.
* @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
*/
public function mockClient(array $responses = [], bool $pad = true): HttpClientHistory
{
// By default, we pad out the responses with 10 successful values so that requests will be
// properly recorded for inspection. Otherwise, we can't later check if we're received
// too many requests.
if ($pad) {
$response = new Response(200, [], 'success');
$responses = array_merge($responses, array_fill(0, 10, $response));
}
$container = [];
$history = Middleware::history($container);
$mock = new MockHandler($responses);
$this->handler = HandlerStack::create($mock);
$this->handler->push($history, 'history');
return new HttpClientHistory($container);
}
/**
* Clear mocking that has been set up for clients.
*/
public function clearMocking(): void
{
$this->handler = null;
}
}

View File

@@ -15,6 +15,7 @@ class Kernel extends HttpKernel
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\BookStack\Http\Middleware\TrimStrings::class,
\BookStack\Http\Middleware\TrustProxies::class,
\BookStack\Http\Middleware\PreventResponseCaching::class,
];
/**
@@ -30,7 +31,6 @@ class Kernel extends HttpKernel
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\BookStack\Http\Middleware\VerifyCsrfToken::class,
\BookStack\Http\Middleware\PreventAuthenticatedResponseCaching::class,
\BookStack\Http\Middleware\CheckEmailConfirmed::class,
\BookStack\Http\Middleware\RunThemeActions::class,
\BookStack\Http\Middleware\Localization::class,
@@ -40,7 +40,6 @@ class Kernel extends HttpKernel
\BookStack\Http\Middleware\EncryptCookies::class,
\BookStack\Http\Middleware\StartSessionIfCookieExists::class,
\BookStack\Http\Middleware\ApiAuthenticate::class,
\BookStack\Http\Middleware\PreventAuthenticatedResponseCaching::class,
\BookStack\Http\Middleware\CheckEmailConfirmed::class,
],
];

View File

@@ -31,7 +31,7 @@ class ApiAuthenticate
{
// Return if the user is already found to be signed in via session-based auth.
// This is to make it easy to browser the API via browser after just logging into the system.
if (signedInUser() || session()->isStarted()) {
if (!user()->isGuest() || session()->isStarted()) {
if (!$this->sessionUserHasApiAccess()) {
throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403);
}
@@ -53,6 +53,6 @@ class ApiAuthenticate
{
$hasApiPermission = user()->can('access-api');
return $hasApiPermission && hasAppAccess();
return $hasApiPermission && user()->hasAppAccess();
}
}

View File

@@ -12,7 +12,7 @@ class Authenticate
*/
public function handle(Request $request, Closure $next)
{
if (!hasAppAccess()) {
if (!user()->hasAppAccess()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
}

View File

@@ -2,17 +2,14 @@
namespace BookStack\Http\Middleware;
use BookStack\Translation\LanguageManager;
use Carbon\Carbon;
use BookStack\Translation\LocaleManager;
use Closure;
class Localization
{
protected LanguageManager $languageManager;
public function __construct(LanguageManager $languageManager)
{
$this->languageManager = $languageManager;
public function __construct(
protected LocaleManager $localeManager
) {
}
/**
@@ -25,22 +22,12 @@ class Localization
*/
public function handle($request, Closure $next)
{
// Get and record the default language in the config
$defaultLang = config('app.locale');
config()->set('app.default_locale', $defaultLang);
// Share details of the user's locale for use in views
$userLocale = $this->localeManager->getForUser(user());
view()->share('locale', $userLocale);
// Get the user's language and record that in the config for use in views
$userLang = $this->languageManager->getUserLanguage($request, $defaultLang);
config()->set('app.lang', str_replace('_', '-', $this->languageManager->getIsoName($userLang)));
// Set text direction
if ($this->languageManager->isRTL($userLang)) {
config()->set('app.rtl', true);
}
app()->setLocale($userLang);
Carbon::setLocale($userLang);
$this->languageManager->setPhpDateTimeLocale($userLang);
// Set locale for system components
app()->setLocale($userLocale->appLocale());
return $next($request);
}

View File

@@ -5,7 +5,7 @@ namespace BookStack\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\Response;
class PreventAuthenticatedResponseCaching
class PreventResponseCaching
{
/**
* Handle an incoming request.
@@ -20,11 +20,8 @@ class PreventAuthenticatedResponseCaching
/** @var Response $response */
$response = $next($request);
if (signedInUser()) {
$response->headers->set('Cache-Control', 'max-age=0, no-store, private');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', 'Sun, 12 Jul 2015 19:01:00 GMT');
}
$response->headers->set('Cache-Control', 'no-cache, no-store, private');
$response->headers->set('Expires', 'Sun, 12 Jul 2015 19:01:00 GMT');
return $response;
}

View File

@@ -1,36 +0,0 @@
<?php
namespace BookStack\Notifications;
class ConfirmEmail extends MailNotification
{
public $token;
/**
* Create a new notification instance.
*
* @param string $token
*/
public function __construct($token)
{
$this->token = $token;
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$appName = ['appName' => setting('app-name')];
return $this->newMailMessage()
->subject(trans('auth.email_confirm_subject', $appName))
->greeting(trans('auth.email_confirm_greeting', $appName))
->line(trans('auth.email_confirm_text'))
->action(trans('auth.email_confirm_action'), url('/register/confirm/' . $this->token));
}
}

View File

@@ -1,37 +0,0 @@
<?php
namespace BookStack\Notifications;
class ResetPassword extends MailNotification
{
/**
* The password reset token.
*
* @var string
*/
public $token;
/**
* Create a notification instance.
*
* @param string $token
*/
public function __construct($token)
{
$this->token = $token;
}
/**
* Build the mail representation of the notification.
*
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail()
{
return $this->newMailMessage()
->subject(trans('auth.email_reset_subject', ['appName' => setting('app-name')]))
->line(trans('auth.email_reset_text'))
->action(trans('auth.reset_password'), url('password/reset/' . $this->token))
->line(trans('auth.email_reset_not_requested'));
}
}

View File

@@ -1,34 +0,0 @@
<?php
namespace BookStack\Notifications;
use BookStack\Users\Models\User;
use Illuminate\Notifications\Messages\MailMessage;
class UserInvite extends MailNotification
{
public $token;
/**
* Create a new notification instance.
*/
public function __construct(string $token)
{
$this->token = $token;
}
/**
* Get the mail representation of the notification.
*/
public function toMail(User $notifiable): MailMessage
{
$appName = ['appName' => setting('app-name')];
$language = setting()->getUser($notifiable, 'language');
return $this->newMailMessage()
->subject(trans('auth.user_invite_email_subject', $appName, $language))
->greeting(trans('auth.user_invite_email_greeting', $appName, $language))
->line(trans('auth.user_invite_email_text', [], $language))
->action(trans('auth.user_invite_email_action', [], $language), url('/register/invite/' . $this->token));
}
}

View File

@@ -3,19 +3,25 @@
namespace BookStack\Permissions;
use BookStack\App\Model;
use BookStack\Entities\EntityProvider;
use BookStack\Entities\Models\Entity;
use BookStack\Entities\Models\Page;
use BookStack\Permissions\Models\EntityPermission;
use BookStack\Users\Models\HasCreatorAndUpdater;
use BookStack\Users\Models\HasOwner;
use BookStack\Users\Models\Role;
use BookStack\Users\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Query\JoinClause;
use InvalidArgumentException;
class PermissionApplicator
{
public function __construct(
protected ?User $user = null
) {
}
/**
* Checks if an entity has a restriction set upon it.
*
@@ -143,6 +149,42 @@ class PermissionApplicator
});
}
/**
* Filter out items that have related entity relations where
* the entity is marked as deleted.
*/
public function filterDeletedFromEntityRelationQuery(Builder $query, string $tableName, string $entityIdColumn, string $entityTypeColumn): Builder
{
$tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
$entityProvider = new EntityProvider();
$joinQuery = function ($query) use ($entityProvider) {
$first = true;
/** @var Builder $query */
foreach ($entityProvider->all() as $entity) {
$entityQuery = function ($query) use ($entity) {
/** @var Builder $query */
$query->select(['id', 'deleted_at'])
->selectRaw("'{$entity->getMorphClass()}' as type")
->from($entity->getTable())
->whereNotNull('deleted_at');
};
if ($first) {
$entityQuery($query);
$first = false;
} else {
$query->union($entityQuery);
}
}
};
return $query->leftJoinSub($joinQuery, 'deletions', function (JoinClause $join) use ($tableDetails) {
$join->on($tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'], '=', 'deletions.id')
->on($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', 'deletions.type');
})->whereNull('deletions.deleted_at');
}
/**
* Add conditions to a query for a model that's a relation of a page, so only the model results
* on visible pages are returned by the query.
@@ -173,7 +215,7 @@ class PermissionApplicator
*/
protected function currentUser(): User
{
return user();
return $this->user ?? user();
}
/**

View File

@@ -12,12 +12,11 @@ use Illuminate\Database\Eloquent\Collection;
class PermissionsRepo
{
protected JointPermissionBuilder $permissionBuilder;
protected array $systemRoles = ['admin', 'public'];
public function __construct(JointPermissionBuilder $permissionBuilder)
{
$this->permissionBuilder = $permissionBuilder;
public function __construct(
protected JointPermissionBuilder $permissionBuilder
) {
}
/**

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