]> BookStack Code Mirror - bookstack/blob - app/Entities/Controllers/BookSortController.php
5aefc583279dbdf7f97cb42122f1af52cf6489a5
[bookstack] / app / Entities / Controllers / BookSortController.php
1 <?php
2
3 namespace BookStack\Entities\Controllers;
4
5 use BookStack\Activity\ActivityType;
6 use BookStack\Entities\Queries\BookQueries;
7 use BookStack\Entities\Tools\BookContents;
8 use BookStack\Entities\Tools\BookSortMap;
9 use BookStack\Facades\Activity;
10 use BookStack\Http\Controller;
11 use Illuminate\Http\Request;
12
13 class BookSortController extends Controller
14 {
15     public function __construct(
16         protected BookQueries $queries,
17     ) {
18     }
19
20     /**
21      * Shows the view which allows pages to be re-ordered and sorted.
22      */
23     public function show(string $bookSlug)
24     {
25         $book = $this->queries->findVisibleBySlugOrFail($bookSlug);
26         $this->checkOwnablePermission('book-update', $book);
27
28         $bookChildren = (new BookContents($book))->getTree(false);
29
30         $this->setPageTitle(trans('entities.books_sort_named', ['bookName' => $book->getShortName()]));
31
32         return view('books.sort', ['book' => $book, 'current' => $book, 'bookChildren' => $bookChildren]);
33     }
34
35     /**
36      * Shows the sort box for a single book.
37      * Used via AJAX when loading in extra books to a sort.
38      */
39     public function showItem(string $bookSlug)
40     {
41         $book = $this->queries->findVisibleBySlugOrFail($bookSlug);
42         $bookChildren = (new BookContents($book))->getTree();
43
44         return view('books.parts.sort-box', ['book' => $book, 'bookChildren' => $bookChildren]);
45     }
46
47     /**
48      * Sorts a book using a given mapping array.
49      */
50     public function update(Request $request, string $bookSlug)
51     {
52         $book = $this->queries->findVisibleBySlugOrFail($bookSlug);
53         $this->checkOwnablePermission('book-update', $book);
54
55         // Return if no map sent
56         if (!$request->filled('sort-tree')) {
57             return redirect($book->getUrl());
58         }
59
60         $sortMap = BookSortMap::fromJson($request->get('sort-tree'));
61         $bookContents = new BookContents($book);
62         $booksInvolved = $bookContents->sortUsingMap($sortMap);
63
64         // Rebuild permissions and add activity for involved books.
65         foreach ($booksInvolved as $bookInvolved) {
66             Activity::add(ActivityType::BOOK_SORT, $bookInvolved);
67         }
68
69         return redirect($book->getUrl());
70     }
71 }