]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/BookSortController.php
8fe05a9beb62a395da399ed7feb2f2588126fdd8
[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\Entities\Tools\BookSortMap;
10 use BookStack\Exceptions\SortOperationException;
11 use BookStack\Facades\Activity;
12 use Illuminate\Http\Request;
13
14 class BookSortController extends Controller
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
35         return view('books.sort', ['book' => $book, 'current' => $book, 'bookChildren' => $bookChildren]);
36     }
37
38     /**
39      * Shows the sort box for a single book.
40      * Used via AJAX when loading in extra books to a sort.
41      */
42     public function showItem(string $bookSlug)
43     {
44         $book = $this->bookRepo->getBySlug($bookSlug);
45         $bookChildren = (new BookContents($book))->getTree();
46
47         return view('books.parts.sort-box', ['book' => $book, 'bookChildren' => $bookChildren]);
48     }
49
50     /**
51      * Sorts a book using a given mapping array.
52      */
53     public function update(Request $request, string $bookSlug)
54     {
55         $book = $this->bookRepo->getBySlug($bookSlug);
56         $this->checkOwnablePermission('book-update', $book);
57
58         // Return if no map sent
59         if (!$request->filled('sort-tree')) {
60             return redirect($book->getUrl());
61         }
62
63         $sortMap = BookSortMap::fromJson($request->get('sort-tree'));
64         $bookContents = new BookContents($book);
65         $booksInvolved = collect();
66
67         try {
68             $booksInvolved = $bookContents->sortUsingMap($sortMap);
69         } catch (SortOperationException $exception) {
70             $this->showPermissionError();
71         }
72
73         // Rebuild permissions and add activity for involved books.
74         $booksInvolved->each(function (Book $book) {
75             Activity::add(ActivityType::BOOK_SORT, $book);
76         });
77
78         return redirect($book->getUrl());
79     }
80 }