]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Api/SearchApiController.php
Fixed page editor back button sometimes going nowhere
[bookstack] / app / Http / Controllers / Api / SearchApiController.php
1 <?php
2
3 namespace BookStack\Http\Controllers\Api;
4
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Entities\Tools\SearchOptions;
7 use BookStack\Entities\Tools\SearchRunner;
8 use Illuminate\Http\Request;
9
10 class SearchApiController extends ApiController
11 {
12     protected $searchRunner;
13
14     protected $rules = [
15         'all' => [
16             'query'  => ['required'],
17             'page'   => ['integer', 'min:1'],
18             'count'  => ['integer', 'min:1', 'max:100'],
19         ],
20     ];
21
22     public function __construct(SearchRunner $searchRunner)
23     {
24         $this->searchRunner = $searchRunner;
25     }
26
27     /**
28      * Run a search query against all main content types (shelves, books, chapters & pages)
29      * in the system. Takes the same input as the main search bar within the BookStack
30      * interface as a 'query' parameter. See https://www.bookstackapp.com/docs/user/searching/
31      * for a full list of search term options. Results contain a 'type' property to distinguish
32      * between: bookshelf, book, chapter & page.
33      *
34      * The paging parameters and response format emulates a standard listing endpoint
35      * but standard sorting and filtering cannot be done on this endpoint. If a count value
36      * is provided this will only be taken as a suggestion. The results in the response
37      * may currently be up to 4x this value.
38      */
39     public function all(Request $request)
40     {
41         $this->validate($request, $this->rules['all']);
42
43         $options = SearchOptions::fromString($request->get('query') ?? '');
44         $page = intval($request->get('page', '0')) ?: 1;
45         $count = min(intval($request->get('count', '0')) ?: 20, 100);
46
47         $results = $this->searchRunner->searchEntities($options, 'all', $page, $count);
48
49         /** @var Entity $result */
50         foreach ($results['results'] as $result) {
51             $result->setVisible([
52                 'id', 'name', 'slug', 'book_id',
53                 'chapter_id', 'draft', 'template',
54                 'created_at', 'updated_at',
55                 'tags', 'type',
56             ]);
57             $result->setAttribute('type', $result->getType());
58         }
59
60         return response()->json([
61             'data'  => $results['results'],
62             'total' => $results['total'],
63         ]);
64     }
65 }