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