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