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