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