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