Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
83.33% covered (warning)
83.33%
125 / 150
65.00% covered (warning)
65.00%
13 / 20
CRAP
0.00% covered (danger)
0.00%
0 / 1
engine
83.33% covered (warning)
83.33%
125 / 150
65.00% covered (warning)
65.00%
13 / 20
87.78
0.00% covered (danger)
0.00%
0 / 1
 is_installed
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 index
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 call
80.00% covered (warning)
80.00%
8 / 10
0.00% covered (danger)
0.00%
0 / 1
4.13
 call_ok
33.33% covered (danger)
33.33%
3 / 9
0.00% covered (danger)
0.00%
0 / 1
5.67
 ensure_index
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 is_server_ready
66.67% covered (warning)
66.67%
8 / 12
0.00% covered (danger)
0.00%
0 / 1
8.81
 to_meili
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 add_document
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 supports_add_document_batch
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_document_batch
66.67% covered (warning)
66.67%
8 / 12
0.00% covered (danger)
0.00%
0 / 1
3.33
 quote
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 build_filter
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
11
 execute_query
81.58% covered (warning)
81.58%
31 / 38
0.00% covered (danger)
0.00%
0 / 1
18.81
 get_query_total_count
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 delete_by_id
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 delete
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 delete_index_for_context
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 delete_index_for_course
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 wait_for_tasks
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
3.02
 drop_index
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2// This file is part of Moodle - https://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.
16
17namespace search_meilisearch;
18
19use core_search\manager;
20
21/**
22 * Moodle global search on a Meilisearch server.
23 *
24 * Documents are stored in one Meilisearch index whose primary key is Moodle's document id. Meilisearch processes
25 * writes in the background (tasks); searches see them once processed, usually within a second.
26 *
27 * @package    search_meilisearch
28 * @copyright  2026 DevLMS
29 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 */
31class engine extends \core_search\engine {
32    /** @var string[] fields people search in */
33    private const SEARCHABLE = ['title', 'content', 'description1', 'description2'];
34
35    /** @var string[] fields used in filters */
36    private const FILTERABLE = ['areaid', 'contextid', 'courseid', 'owneruserid', 'modified', 'itemid'];
37
38    /** @var string[] Moodle fields stored as numbers, so number filters work */
39    private const NUMERIC = ['itemid', 'contextid', 'courseid', 'owneruserid', 'userid', 'modified', 'type'];
40
41    /** @var int how many pages of results to read while filling a page of results the user can see */
42    private const MAX_PAGES = 5;
43
44    /** @var int|null total of the last query */
45    protected $totalresults = null;
46
47    /** @var bool whether the index exists with our settings, checked once per request */
48    private bool $indexready = false;
49
50    /**
51     * Nothing to install in PHP.
52     *
53     * @return bool
54     */
55    public function is_installed() {
56        return true;
57    }
58
59    /**
60     * The index name, as configured.
61     *
62     * @return string
63     */
64    private function index(): string {
65        return (string)($this->config->indexname ?? 'moodle') ?: 'moodle';
66    }
67
68    /**
69     * Call the Meilisearch API.
70     *
71     * @param string $method
72     * @param string $path starting with /
73     * @param mixed $body sent as JSON when not null
74     * @return array [status code, decoded body]
75     */
76    private function call(string $method, string $path, $body = null): array {
77        $url = rtrim((string)($this->config->serverurl ?? ''), '/') . $path;
78        $options = ['headers' => ['Content-Type' => 'application/json'], 'timeout' => 30, 'http_errors' => false];
79        if (!empty($this->config->apikey)) {
80            $options['headers']['Authorization'] = 'Bearer ' . $this->config->apikey;
81        }
82        if ($body !== null) {
83            $options['body'] = json_encode($body);
84        }
85        try {
86            // The server URL is infrastructure set by site administrators, like the database host, and usually on
87            // 127.0.0.1 or a private network, which Moodle's HTTP security blocks by default. Core's Solr engine does
88            // not go through that check either.
89            $response = (new \core\http_client(['ignoresecurity' => true]))->request($method, $url, $options);
90        } catch (\Throwable $e) {
91            return [0, ['message' => $e->getMessage()]];
92        }
93        return [$response->getStatusCode(), json_decode((string)$response->getBody(), true) ?? []];
94    }
95
96    /**
97     * Call the API and throw on failure.
98     *
99     * @param string $method
100     * @param string $path
101     * @param mixed $body
102     * @return array decoded body
103     */
104    private function call_ok(string $method, string $path, $body = null): array {
105        [$status, $result] = $this->call($method, $path, $body);
106        if ($status < 200 || $status >= 300) {
107            throw new \core_search\engine_exception(
108                'engineserverstatus',
109                'search',
110                '',
111                ($result['message'] ?? '') . " (HTTP $status)"
112            );
113        }
114        return $result;
115    }
116
117    /**
118     * Create the index with the id primary key and our settings when it is missing.
119     *
120     * Meilisearch cannot guess the primary key of Moodle documents: areaid and contextid also end in "id".
121     */
122    private function ensure_index(): void {
123        if ($this->indexready) {
124            return;
125        }
126        [$status] = $this->call('GET', '/indexes/' . rawurlencode($this->index()));
127        if ($status === 404) {
128            $this->call_ok('POST', '/indexes', ['uid' => $this->index(), 'primaryKey' => 'id']);
129            $this->call_ok('PATCH', '/indexes/' . rawurlencode($this->index()) . '/settings', [
130                'searchableAttributes' => self::SEARCHABLE,
131                'filterableAttributes' => self::FILTERABLE,
132            ]);
133        }
134        $this->indexready = true;
135    }
136
137    /**
138     * Whether the server answers, the key works and the index is usable.
139     *
140     * @return true|string
141     */
142    public function is_server_ready() {
143        if (empty($this->config->serverurl)) {
144            return get_string('noserverurl', 'search_meilisearch');
145        }
146        [$status, $health] = $this->call('GET', '/health');
147        if ($status !== 200 || ($health['status'] ?? '') !== 'available') {
148            return get_string('servernotready', 'search_meilisearch', $health['message'] ?? "HTTP $status");
149        }
150        [$status, $result] = $this->call('GET', '/indexes/' . rawurlencode($this->index()));
151        if ($status === 401 || $status === 403) {
152            return get_string('badkey', 'search_meilisearch', $result['message'] ?? "HTTP $status");
153        }
154        try {
155            $this->ensure_index();
156        } catch (\core_search\engine_exception $e) {
157            return $e->getMessage();
158        }
159        return true;
160    }
161
162    /**
163     * A Moodle document as stored in Meilisearch.
164     *
165     * @param \core_search\document $document
166     * @return array
167     */
168    private function to_meili(\core_search\document $document): array {
169        $doc = $document->export_for_engine();
170        foreach (self::NUMERIC as $field) {
171            if (isset($doc[$field])) {
172                $doc[$field] = (int)$doc[$field];
173            }
174        }
175        return $doc;
176    }
177
178    /**
179     * Add or replace one document.
180     *
181     * @param \core_search\document $document
182     * @param bool $fileindexing files are not indexed by this engine
183     * @return bool
184     */
185    public function add_document($document, $fileindexing = false) {
186        return $this->add_document_batch([$document], $fileindexing)[0] === 1;
187    }
188
189    /**
190     * Documents are sent in batches.
191     *
192     * @return bool
193     */
194    public function supports_add_document_batch(): bool {
195        return true;
196    }
197
198    /**
199     * Add or replace documents in one request.
200     *
201     * @param \core_search\document[] $documents
202     * @param bool $fileindexing
203     * @return int[] added, failed, batches
204     */
205    public function add_document_batch(array $documents, bool $fileindexing = false): array {
206        if (!$documents) {
207            return [0, 0, 0];
208        }
209        try {
210            $this->ensure_index();
211            $this->call_ok(
212                'POST',
213                '/indexes/' . rawurlencode($this->index()) . '/documents?primaryKey=id',
214                array_map(fn($document) => $this->to_meili($document), array_values($documents))
215            );
216        } catch (\core_search\engine_exception $e) {
217            debugging('Meilisearch could not add documents: ' . $e->getMessage(), DEBUG_DEVELOPER);
218            return [0, count($documents), 1];
219        }
220        return [count($documents), 0, 1];
221    }
222
223    /**
224     * Quote a string for a Meilisearch filter.
225     *
226     * @param string $value
227     * @return string
228     */
229    private static function quote(string $value): string {
230        return '"' . str_replace(['\\', '"'], ['\\\\', '\\"'], $value) . '"';
231    }
232
233    /**
234     * Turn Moodle's search filters and the user's access into a Meilisearch filter.
235     *
236     * @param \stdClass $filters from the search form
237     * @param array|bool $usercontexts true for everything, else area id => context ids the user can access
238     * @param int $userid
239     * @return string|null null when the user can access nothing that matches
240     */
241    public static function build_filter(\stdClass $filters, $usercontexts, int $userid): ?string {
242        $parts = ['(owneruserid = ' . manager::NO_OWNER_ID . ' OR owneruserid = ' . $userid . ')'];
243
244        if ($usercontexts !== true) {
245            $contexts = [];
246            foreach ((array)$usercontexts as $areaid => $areacontexts) {
247                if (!empty($filters->areaids) && !in_array($areaid, $filters->areaids)) {
248                    continue;
249                }
250                foreach ($areacontexts as $contextid) {
251                    $contexts[(int)$contextid] = (int)$contextid;
252                }
253            }
254            if (!$contexts) {
255                return null;
256            }
257            sort($contexts);
258            $parts[] = 'contextid IN [' . implode(', ', $contexts) . ']';
259        }
260        if (!empty($filters->areaids)) {
261            $parts[] = 'areaid IN [' . implode(', ', array_map(fn($a) => self::quote((string)$a), $filters->areaids)) . ']';
262        }
263        if (!empty($filters->courseids)) {
264            $parts[] = 'courseid IN [' . implode(', ', array_map('intval', $filters->courseids)) . ']';
265        }
266        if (!empty($filters->timestart)) {
267            $parts[] = 'modified >= ' . (int)$filters->timestart;
268        }
269        if (!empty($filters->timeend)) {
270            $parts[] = 'modified <= ' . (int)$filters->timeend;
271        }
272        return implode(' AND ', $parts);
273    }
274
275    /**
276     * Search, keeping only results the user may see.
277     *
278     * @param \stdClass $filters
279     * @param array|bool $usercontexts
280     * @param int $limit
281     * @return \core_search\document[]
282     */
283    public function execute_query($filters, $usercontexts, $limit = 0) {
284        global $USER;
285
286        if ($this->is_server_ready() !== true) {
287            throw new \core_search\engine_exception('engineserverstatus', 'search');
288        }
289        $limit = $limit ?: manager::MAX_RESULTS;
290        $this->totalresults = 0;
291        $filter = self::build_filter($filters, $usercontexts, (int)$USER->id);
292        if ($filter === null) {
293            return [];
294        }
295        $title = !empty($filters->title) ? \core_text::strtolower(trim(str_replace('%', '', $filters->title))) : '';
296
297        $docs = [];
298        for ($page = 1; $page <= self::MAX_PAGES && count($docs) < $limit; $page++) {
299            $result = $this->call_ok('POST', '/indexes/' . rawurlencode($this->index()) . '/search', [
300                'q' => (string)($filters->q ?? ''),
301                'filter' => $filter,
302                'page' => $page,
303                'hitsPerPage' => $limit,
304            ]);
305            if ($page === 1) {
306                $this->totalresults = (int)($result['totalHits'] ?? 0);
307            }
308            foreach ($result['hits'] ?? [] as $hit) {
309                if ($title !== '' && !str_contains(\core_text::strtolower((string)($hit['title'] ?? '')), $title)) {
310                    $this->totalresults--;
311                    continue;
312                }
313                $searcharea = $this->get_search_area($hit['areaid'] ?? '');
314                if (!$searcharea) {
315                    $this->totalresults--;
316                    continue;
317                }
318                $access = $searcharea->check_access($hit['itemid']);
319                if ($access === manager::ACCESS_DELETED) {
320                    $this->delete_by_id($hit['id']);
321                    $this->totalresults--;
322                } else if ($access === manager::ACCESS_DENIED) {
323                    $this->totalresults--;
324                } else if ($access === manager::ACCESS_GRANTED && count($docs) < $limit) {
325                    $docs[] = $this->to_document($searcharea, $hit);
326                }
327            }
328            if ($page >= (int)($result['totalPages'] ?? 0)) {
329                break;
330            }
331        }
332        $this->totalresults = max($this->totalresults, count($docs));
333        return $docs;
334    }
335
336    /**
337     * Total of the last query, after access checks on the pages read.
338     *
339     * @return int
340     */
341    public function get_query_total_count() {
342        return (int)$this->totalresults;
343    }
344
345    /**
346     * Delete one document.
347     *
348     * @param string $id Moodle document id
349     */
350    public function delete_by_id($id) {
351        $this->call('DELETE', '/indexes/' . rawurlencode($this->index()) . '/documents/' . rawurlencode((string)$id));
352    }
353
354    /**
355     * Delete the documents of one area, or all documents.
356     *
357     * @param string|null $areaid
358     */
359    public function delete($areaid = null) {
360        $index = '/indexes/' . rawurlencode($this->index());
361        if ($areaid) {
362            $this->call_ok('POST', "$index/documents/delete", ['filter' => 'areaid = ' . self::quote((string)$areaid)]);
363        } else {
364            $this->call_ok('DELETE', "$index/documents");
365        }
366    }
367
368    /**
369     * Delete the documents of a deleted context.
370     *
371     * @param int $oldcontextid
372     * @return bool
373     */
374    public function delete_index_for_context(int $oldcontextid) {
375        $this->call_ok(
376            'POST',
377            '/indexes/' . rawurlencode($this->index()) . '/documents/delete',
378            ['filter' => 'contextid = ' . $oldcontextid]
379        );
380        return true;
381    }
382
383    /**
384     * Delete the documents of a deleted course.
385     *
386     * @param int $oldcourseid
387     * @return bool
388     */
389    public function delete_index_for_course(int $oldcourseid) {
390        $this->call_ok(
391            'POST',
392            '/indexes/' . rawurlencode($this->index()) . '/documents/delete',
393            ['filter' => 'courseid = ' . $oldcourseid]
394        );
395        return true;
396    }
397
398    /**
399     * Wait until Meilisearch has processed every write sent to this index (tests, and the CLI).
400     *
401     * @param int $timeout seconds
402     * @return bool false if tasks were still running at the timeout
403     */
404    public function wait_for_tasks(int $timeout = 30): bool {
405        $path = '/tasks?indexUids=' . rawurlencode($this->index()) . '&statuses=enqueued,processing&limit=1';
406        $end = microtime(true) + $timeout;
407        do {
408            [$status, $result] = $this->call('GET', $path);
409            if ($status === 200 && empty($result['results'])) {
410                return true;
411            }
412            usleep(100000);
413        } while (microtime(true) < $end);
414        return false;
415    }
416
417    /**
418     * Remove the whole index (tests).
419     */
420    public function drop_index(): void {
421        $this->call('DELETE', '/indexes/' . rawurlencode($this->index()));
422        $this->indexready = false;
423    }
424}