3 namespace BookStack\Sorting;
5 use BookStack\Activity\ActivityType;
6 use BookStack\Entities\Queries\BookQueries;
7 use BookStack\Entities\Tools\BookContents;
8 use BookStack\Facades\Activity;
9 use BookStack\Http\Controller;
10 use BookStack\Permissions\Permission;
11 use BookStack\Util\DatabaseTransaction;
12 use Illuminate\Http\Request;
14 class BookSortController extends Controller
16 public function __construct(
17 protected BookQueries $queries,
22 * Shows the view which allows pages to be re-ordered and sorted.
24 public function show(string $bookSlug)
26 $book = $this->queries->findVisibleBySlugOrFail($bookSlug);
27 $this->checkOwnablePermission(Permission::BookUpdate, $book);
29 $bookChildren = (new BookContents($book))->getTree(false);
31 $this->setPageTitle(trans('entities.books_sort_named', ['bookName' => $book->getShortName()]));
33 return view('books.sort', ['book' => $book, 'current' => $book, 'bookChildren' => $bookChildren]);
37 * Shows the sort box for a single book.
38 * Used via AJAX when loading in extra books to a sort.
40 public function showItem(string $bookSlug)
42 $book = $this->queries->findVisibleBySlugOrFail($bookSlug);
43 $bookChildren = (new BookContents($book))->getTree();
45 return view('books.parts.sort-box', ['book' => $book, 'bookChildren' => $bookChildren]);
49 * Update the sort options of a book, setting the auto-sort and/or updating
50 * child order via mapping.
52 public function update(Request $request, BookSorter $sorter, string $bookSlug)
54 $book = $this->queries->findVisibleBySlugOrFail($bookSlug);
55 $this->checkOwnablePermission(Permission::BookUpdate, $book);
56 $loggedActivityForBook = false;
59 if ($request->filled('sort-tree')) {
60 (new DatabaseTransaction(function () use ($book, $request, $sorter, &$loggedActivityForBook) {
61 $sortMap = BookSortMap::fromJson($request->get('sort-tree'));
62 $booksInvolved = $sorter->sortUsingMap($sortMap);
64 // Add activity for involved books.
65 foreach ($booksInvolved as $bookInvolved) {
66 Activity::add(ActivityType::BOOK_SORT, $bookInvolved);
67 if ($bookInvolved->id === $book->id) {
68 $loggedActivityForBook = true;
74 if ($request->filled('auto-sort')) {
75 $sortSetId = intval($request->get('auto-sort')) ?: null;
76 if ($sortSetId && SortRule::query()->find($sortSetId) === null) {
79 $book->sort_rule_id = $sortSetId;
81 $sorter->runBookAutoSort($book);
82 if (!$loggedActivityForBook) {
83 Activity::add(ActivityType::BOOK_SORT, $book);
87 return redirect($book->getUrl());