weekly release 3.5dev
[moodle.git] / search / engine / solr / classes / engine.php
CommitLineData
95c6aeaf
DM
1<?php
2// This file is part of Moodle - http://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 <http://www.gnu.org/licenses/>.
16
17/**
18 * Solr engine.
19 *
20 * @package search_solr
21 * @copyright 2015 Daniel Neis Araujo
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace search_solr;
26
27defined('MOODLE_INTERNAL') || die();
28
29/**
30 * Solr engine.
31 *
32 * @package search_solr
33 * @copyright 2015 Daniel Neis Araujo
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 */
36class engine extends \core_search\engine {
37
38 /**
39 * @var string The date format used by solr.
40 */
41 const DATE_FORMAT = 'Y-m-d\TH:i:s\Z';
42
43 /**
44 * @var int Commit documents interval (number of miliseconds).
45 */
46 const AUTOCOMMIT_WITHIN = 15000;
47
053118a1
EM
48 /**
49 * The maximum number of results to fetch at a time.
50 */
51 const QUERY_SIZE = 120;
52
95c6aeaf 53 /**
4894840d 54 * Highlighting fragsize. Slightly larger than output size (500) to allow for ... appending.
95c6aeaf 55 */
4894840d
EM
56 const FRAG_SIZE = 510;
57
58 /**
59 * Marker for the start of a highlight.
60 */
61 const HIGHLIGHT_START = '@@HI_S@@';
62
63 /**
64 * Marker for the end of a highlight.
65 */
66 const HIGHLIGHT_END = '@@HI_E@@';
95c6aeaf
DM
67
68 /**
69 * @var \SolrClient
70 */
71 protected $client = null;
72
7a4a0bc8
EM
73 /**
74 * @var bool True if we should reuse SolrClients, false if not.
75 */
76 protected $cacheclient = true;
77
5dc4624c
EM
78 /**
79 * @var \curl Direct curl object.
80 */
81 protected $curl = null;
82
95c6aeaf
DM
83 /**
84 * @var array Fields that can be highlighted.
85 */
4894840d 86 protected $highlightfields = array('title', 'content', 'description1', 'description2');
95c6aeaf 87
053118a1
EM
88 /**
89 * @var int Number of total docs reported by Sorl for the last query.
90 */
91 protected $totalenginedocs = 0;
92
93 /**
94 * @var int Number of docs we have processed for the last query.
95 */
96 protected $processeddocs = 0;
97
98 /**
99 * @var int Number of docs that have been skipped while processing the last query.
100 */
101 protected $skippeddocs = 0;
102
7a4a0bc8
EM
103 /**
104 * Initialises the search engine configuration.
105 *
106 * @return void
107 */
108 public function __construct() {
109 parent::__construct();
110
111 $curlversion = curl_version();
112 if (isset($curlversion['version']) && stripos($curlversion['version'], '7.35.') === 0) {
113 // There is a flaw with curl 7.35.0 that causes problems with client reuse.
114 $this->cacheclient = false;
115 }
116 }
117
95c6aeaf
DM
118 /**
119 * Prepares a Solr query, applies filters and executes it returning its results.
120 *
121 * @throws \core_search\engine_exception
f6b425e2
EM
122 * @param stdClass $filters Containing query and filters.
123 * @param array $usercontexts Contexts where the user has access. True if the user can access all contexts.
053118a1 124 * @param int $limit The maximum number of results to return.
95c6aeaf
DM
125 * @return \core_search\document[] Results or false if no results
126 */
053118a1 127 public function execute_query($filters, $usercontexts, $limit = 0) {
f6b425e2 128 global $USER;
95c6aeaf 129
053118a1
EM
130 if (empty($limit)) {
131 $limit = \core_search\manager::MAX_RESULTS;
132 }
95c6aeaf
DM
133
134 // If there is any problem we trigger the exception as soon as possible.
7a4a0bc8 135 $client = $this->get_search_client();
95c6aeaf 136
053118a1
EM
137 // Create the query object.
138 $query = $this->create_user_query($filters, $usercontexts);
139
cfa00fc5 140 // If the query cannot have results, return none.
141 if (!$query) {
142 return [];
143 }
144
053118a1
EM
145 // We expect good match rates, so for our first get, we will get a small number of records.
146 // This significantly speeds solr response time for first few pages.
147 $query->setRows(min($limit * 3, static::QUERY_SIZE));
148 $response = $this->get_query_response($query);
149
150 // Get count data out of the response, and reset our counters.
151 list($included, $found) = $this->get_response_counts($response);
152 $this->totalenginedocs = $found;
153 $this->processeddocs = 0;
154 $this->skippeddocs = 0;
155 if ($included == 0 || $this->totalenginedocs == 0) {
156 // No results.
157 return array();
158 }
159
160 // Get valid documents out of the response.
161 $results = $this->process_response($response, $limit);
162
163 // We have processed all the docs in the response at this point.
164 $this->processeddocs += $included;
165
166 // If we haven't reached the limit, and there are more docs left in Solr, lets keep trying.
167 while (count($results) < $limit && ($this->totalenginedocs - $this->processeddocs) > 0) {
168 // Offset the start of the query, and since we are making another call, get more per call.
169 $query->setStart($this->processeddocs);
170 $query->setRows(static::QUERY_SIZE);
171
172 $response = $this->get_query_response($query);
173 list($included, $found) = $this->get_response_counts($response);
174 if ($included == 0 || $found == 0) {
175 // No new results were found. Found being empty would be weird, so we will just return.
176 return $results;
177 }
178 $this->totalenginedocs = $found;
179
180 // Get the new response docs, limiting to remaining we need, then add it to the end of the results array.
181 $newdocs = $this->process_response($response, $limit - count($results));
182 $results = array_merge($results, $newdocs);
183
184 // Add to our processed docs count.
185 $this->processeddocs += $included;
186 }
187
188 return $results;
189 }
190
191 /**
192 * Takes a query and returns the response in SolrObject format.
193 *
194 * @param SolrQuery $query Solr query object.
195 * @return SolrObject|false Response document or false on error.
196 */
197 protected function get_query_response($query) {
198 try {
199 return $this->get_search_client()->query($query)->getResponse();
200 } catch (\SolrClientException $ex) {
201 debugging('Error executing the provided query: ' . $ex->getMessage(), DEBUG_DEVELOPER);
202 $this->queryerror = $ex->getMessage();
203 return false;
204 } catch (\SolrServerException $ex) {
205 debugging('Error executing the provided query: ' . $ex->getMessage(), DEBUG_DEVELOPER);
206 $this->queryerror = $ex->getMessage();
207 return false;
cd894f84 208 }
053118a1
EM
209 }
210
211 /**
212 * Returns the total number of documents available for the most recently call to execute_query.
213 *
214 * @return int
215 */
216 public function get_query_total_count() {
217 // Return the total engine count minus the docs we have determined are bad.
218 return $this->totalenginedocs - $this->skippeddocs;
219 }
220
221 /**
222 * Returns count information for a provided response. Will return 0, 0 for invalid or empty responses.
223 *
224 * @param SolrDocument $response The response document from Solr.
225 * @return array A two part array. First how many response docs are in the response.
226 * Second, how many results are vailable in the engine.
227 */
228 protected function get_response_counts($response) {
229 $found = 0;
230 $included = 0;
231
232 if (isset($response->grouped->solr_filegroupingid->ngroups)) {
233 // Get the number of results for file grouped queries.
234 $found = $response->grouped->solr_filegroupingid->ngroups;
235 $included = count($response->grouped->solr_filegroupingid->groups);
236 } else if (isset($response->response->numFound)) {
237 // Get the number of results for standard queries.
238 $found = $response->response->numFound;
239 $included = count($response->response->docs);
cd894f84 240 }
053118a1
EM
241
242 return array($included, $found);
243 }
244
245 /**
246 * Prepares a new query object with needed limits, filters, etc.
247 *
248 * @param stdClass $filters Containing query and filters.
249 * @param array $usercontexts Contexts where the user has access. True if the user can access all contexts.
cfa00fc5 250 * @return \SolrDisMaxQuery|null Query object or null if they can't get any results
053118a1
EM
251 */
252 protected function create_user_query($filters, $usercontexts) {
253 global $USER;
254
255 // Let's keep these changes internal.
256 $data = clone $filters;
257
258 $query = new \SolrDisMaxQuery();
259
260 $this->set_query($query, $data->q);
95c6aeaf
DM
261 $this->add_fields($query);
262
263 // Search filters applied, we don't cache these filters as we don't want to pollute the cache with tmp filters
264 // we are really interested in caching contexts filters instead.
265 if (!empty($data->title)) {
266 $query->addFilterQuery('{!field cache=false f=title}' . $data->title);
267 }
501801a2
EM
268 if (!empty($data->areaids)) {
269 // If areaids are specified, we want to get any that match.
270 $query->addFilterQuery('{!cache=false}areaid:(' . implode(' OR ', $data->areaids) . ')');
95c6aeaf 271 }
427e3cbc
EM
272 if (!empty($data->courseids)) {
273 $query->addFilterQuery('{!cache=false}courseid:(' . implode(' OR ', $data->courseids) . ')');
274 }
95c6aeaf
DM
275
276 if (!empty($data->timestart) or !empty($data->timeend)) {
277 if (empty($data->timestart)) {
278 $data->timestart = '*';
279 } else {
280 $data->timestart = \search_solr\document::format_time_for_engine($data->timestart);
281 }
282 if (empty($data->timeend)) {
283 $data->timeend = '*';
284 } else {
285 $data->timeend = \search_solr\document::format_time_for_engine($data->timeend);
286 }
287
288 // No cache.
289 $query->addFilterQuery('{!cache=false}modified:[' . $data->timestart . ' TO ' . $data->timeend . ']');
290 }
291
f6b425e2
EM
292 // Restrict to users who are supposed to be able to see a particular result.
293 $query->addFilterQuery('owneruserid:(' . \core_search\manager::NO_OWNER_ID . ' OR ' . $USER->id . ')');
294
95c6aeaf
DM
295 // And finally restrict it to the context where the user can access, we want this one cached.
296 // If the user can access all contexts $usercontexts value is just true, we don't need to filter
297 // in that case.
298 if ($usercontexts && is_array($usercontexts)) {
427e3cbc
EM
299 // Join all area contexts into a single array and implode.
300 $allcontexts = array();
301 foreach ($usercontexts as $areaid => $areacontexts) {
501801a2 302 if (!empty($data->areaids) && !in_array($areaid, $data->areaids)) {
427e3cbc
EM
303 // Skip unused areas.
304 continue;
95c6aeaf 305 }
427e3cbc
EM
306 foreach ($areacontexts as $contextid) {
307 // Ensure they are unique.
308 $allcontexts[$contextid] = $contextid;
309 }
310 }
311 if (empty($allcontexts)) {
312 // This means there are no valid contexts for them, so they get no results.
cfa00fc5 313 return null;
95c6aeaf 314 }
427e3cbc 315 $query->addFilterQuery('contextid:(' . implode(' OR ', $allcontexts) . ')');
95c6aeaf
DM
316 }
317
053118a1
EM
318 if ($this->file_indexing_enabled()) {
319 // Now group records by solr_filegroupingid. Limit to 3 results per group.
320 $query->setGroup(true);
321 $query->setGroupLimit(3);
322 $query->setGroupNGroups(true);
323 $query->addGroupField('solr_filegroupingid');
e0867b22
EM
324 } else {
325 // Make sure we only get text files, in case the index has pre-existing files.
326 $query->addFilterQuery('type:'.\core_search\manager::TYPE_TEXT);
95c6aeaf
DM
327 }
328
053118a1 329 return $query;
95c6aeaf
DM
330 }
331
332 /**
333 * Prepares a new query by setting the query, start offset and rows to return.
3744ceb6 334 *
95c6aeaf 335 * @param SolrQuery $query
cd894f84 336 * @param object $q Containing query and filters.
95c6aeaf 337 */
053118a1 338 protected function set_query($query, $q) {
95c6aeaf
DM
339 // Set hightlighting.
340 $query->setHighlight(true);
341 foreach ($this->highlightfields as $field) {
342 $query->addHighlightField($field);
343 }
344 $query->setHighlightFragsize(static::FRAG_SIZE);
4894840d
EM
345 $query->setHighlightSimplePre(self::HIGHLIGHT_START);
346 $query->setHighlightSimplePost(self::HIGHLIGHT_END);
347 $query->setHighlightMergeContiguous(true);
95c6aeaf
DM
348
349 $query->setQuery($q);
350
351 // A reasonable max.
053118a1 352 $query->setRows(static::QUERY_SIZE);
95c6aeaf
DM
353 }
354
355 /**
356 * Sets fields to be returned in the result.
357 *
3744ceb6 358 * @param SolrDisMaxQuery|SolrQuery $query object.
95c6aeaf
DM
359 */
360 public function add_fields($query) {
361 $documentclass = $this->get_document_classname();
3744ceb6
EM
362 $fields = $documentclass::get_default_fields_definition();
363
364 $dismax = false;
546c0af5 365 if ($query instanceof \SolrDisMaxQuery) {
3744ceb6
EM
366 $dismax = true;
367 }
368
369 foreach ($fields as $key => $field) {
370 $query->addField($key);
371 if ($dismax && !empty($field['mainquery'])) {
372 // Add fields the main query should be run against.
373 $query->addQueryField($key);
374 }
95c6aeaf
DM
375 }
376 }
377
378 /**
379 * Finds the key common to both highlighing and docs array returned from response.
380 * @param object $response containing results.
381 */
382 public function add_highlight_content($response) {
cd894f84
EM
383 if (!isset($response->highlighting)) {
384 // There is no highlighting to add.
385 return;
386 }
387
95c6aeaf
DM
388 $highlightedobject = $response->highlighting;
389 foreach ($response->response->docs as $doc) {
390 $x = $doc->id;
391 $highlighteddoc = $highlightedobject->$x;
392 $this->merge_highlight_field_values($doc, $highlighteddoc);
393 }
394 }
395
396 /**
397 * Adds the highlighting array values to docs array values.
398 *
399 * @throws \core_search\engine_exception
400 * @param object $doc containing the results.
401 * @param object $highlighteddoc containing the highlighted results values.
402 */
403 public function merge_highlight_field_values($doc, $highlighteddoc) {
404
405 foreach ($this->highlightfields as $field) {
406 if (!empty($doc->$field)) {
407
408 // Check that the returned value is not an array. No way we can make this work with multivalued solr fields.
409 if (is_array($doc->{$field})) {
410 throw new \core_search\engine_exception('multivaluedfield', 'search_solr', '', $field);
411 }
412
413 if (!empty($highlighteddoc->$field)) {
414 // Replace by the highlighted result.
415 $doc->$field = reset($highlighteddoc->$field);
416 }
417 }
418 }
419 }
420
421 /**
422 * Filters the response on Moodle side.
423 *
053118a1
EM
424 * @param SolrObject $response Solr object containing the response return from solr server.
425 * @param int $limit The maximum number of results to return. 0 for all.
426 * @param bool $skipaccesscheck Don't use check_access() on results. Only to be used when results have known access.
95c6aeaf
DM
427 * @return array $results containing final results to be displayed.
428 */
053118a1 429 protected function process_response($response, $limit = 0, $skipaccesscheck = false) {
f6b425e2
EM
430 global $USER;
431
053118a1
EM
432 if (empty($response)) {
433 return array();
434 }
435
436 if (isset($response->grouped)) {
437 return $this->grouped_files_process_response($response, $limit);
438 }
439
f6b425e2
EM
440 $userid = $USER->id;
441 $noownerid = \core_search\manager::NO_OWNER_ID;
95c6aeaf 442
95c6aeaf
DM
443 $numgranted = 0;
444
445 if (!$docs = $response->response->docs) {
446 return array();
447 }
448
053118a1 449 $out = array();
95c6aeaf
DM
450 if (!empty($response->response->numFound)) {
451 $this->add_highlight_content($response);
452
453 // Iterate through the results checking its availability and whether they are available for the user or not.
454 foreach ($docs as $key => $docdata) {
f6b425e2
EM
455 if ($docdata['owneruserid'] != $noownerid && $docdata['owneruserid'] != $userid) {
456 // If owneruserid is set, no other user should be able to access this record.
f6b425e2
EM
457 continue;
458 }
459
95c6aeaf 460 if (!$searcharea = $this->get_search_area($docdata->areaid)) {
95c6aeaf
DM
461 continue;
462 }
463
464 $docdata = $this->standarize_solr_obj($docdata);
465
053118a1
EM
466 if ($skipaccesscheck) {
467 $access = \core_search\manager::ACCESS_GRANTED;
468 } else {
469 $access = $searcharea->check_access($docdata['itemid']);
470 }
95c6aeaf
DM
471 switch ($access) {
472 case \core_search\manager::ACCESS_DELETED:
473 $this->delete_by_id($docdata['id']);
053118a1
EM
474 // Remove one from our processed and total counters, since we promptly deleted.
475 $this->processeddocs--;
476 $this->totalenginedocs--;
95c6aeaf
DM
477 break;
478 case \core_search\manager::ACCESS_DENIED:
053118a1 479 $this->skippeddocs++;
95c6aeaf
DM
480 break;
481 case \core_search\manager::ACCESS_GRANTED:
482 $numgranted++;
483
484 // Add the doc.
053118a1 485 $out[] = $this->to_document($searcharea, $docdata);
95c6aeaf
DM
486 break;
487 }
488
053118a1
EM
489 // Stop when we hit our limit.
490 if (!empty($limit) && count($out) >= $limit) {
95c6aeaf
DM
491 break;
492 }
493 }
494 }
495
053118a1 496 return $out;
95c6aeaf
DM
497 }
498
cd894f84
EM
499 /**
500 * Processes grouped file results into documents, with attached matching files.
501 *
053118a1
EM
502 * @param SolrObject $response The response returned from solr server
503 * @param int $limit The maximum number of results to return. 0 for all.
cd894f84
EM
504 * @return array Final results to be displayed.
505 */
053118a1 506 protected function grouped_files_process_response($response, $limit = 0) {
cd894f84
EM
507 // If we can't find the grouping, or there are no matches in the grouping, return empty.
508 if (!isset($response->grouped->solr_filegroupingid) || empty($response->grouped->solr_filegroupingid->matches)) {
509 return array();
510 }
511
512 $numgranted = 0;
513 $orderedids = array();
514 $completedocs = array();
515 $incompletedocs = array();
516
517 $highlightingobj = $response->highlighting;
518
519 // Each group represents a "master document".
520 $groups = $response->grouped->solr_filegroupingid->groups;
521 foreach ($groups as $group) {
522 $groupid = $group->groupValue;
523 $groupdocs = $group->doclist->docs;
524 $firstdoc = reset($groupdocs);
525
526 if (!$searcharea = $this->get_search_area($firstdoc->areaid)) {
527 // Well, this is a problem.
528 continue;
529 }
530
531 // Check for access.
532 $access = $searcharea->check_access($firstdoc->itemid);
533 switch ($access) {
534 case \core_search\manager::ACCESS_DELETED:
535 // If deleted from Moodle, delete from index and then continue.
536 $this->delete_by_id($firstdoc->id);
053118a1
EM
537 // Remove one from our processed and total counters, since we promptly deleted.
538 $this->processeddocs--;
539 $this->totalenginedocs--;
cd894f84
EM
540 continue 2;
541 break;
542 case \core_search\manager::ACCESS_DENIED:
543 // This means we should just skip for the current user.
053118a1 544 $this->skippeddocs++;
cd894f84
EM
545 continue 2;
546 break;
547 }
548 $numgranted++;
549
550 $maindoc = false;
551 $fileids = array();
552 // Seperate the main document and any files returned.
553 foreach ($groupdocs as $groupdoc) {
554 if ($groupdoc->id == $groupid) {
555 $maindoc = $groupdoc;
556 } else if (isset($groupdoc->solr_fileid)) {
557 $fileids[] = $groupdoc->solr_fileid;
558 }
559 }
560
561 // Store the id of this group, in order, for later merging.
562 $orderedids[] = $groupid;
563
564 if (!$maindoc) {
565 // We don't have the main doc, store what we know for later building.
566 $incompletedocs[$groupid] = $fileids;
567 } else {
568 if (isset($highlightingobj->$groupid)) {
569 // Merge the highlighting for this doc.
570 $this->merge_highlight_field_values($maindoc, $highlightingobj->$groupid);
571 }
572 $docdata = $this->standarize_solr_obj($maindoc);
573 $doc = $this->to_document($searcharea, $docdata);
574 // Now we need to attach the result files to the doc.
575 foreach ($fileids as $fileid) {
576 $doc->add_stored_file($fileid);
577 }
578 $completedocs[$groupid] = $doc;
579 }
580
053118a1 581 if (!empty($limit) && $numgranted >= $limit) {
cd894f84
EM
582 // We have hit the max results, we will just ignore the rest.
583 break;
584 }
585 }
586
587 $incompletedocs = $this->get_missing_docs($incompletedocs);
588
589 $out = array();
590 // Now merge the complete and incomplete documents, in results order.
591 foreach ($orderedids as $docid) {
592 if (isset($completedocs[$docid])) {
593 $out[] = $completedocs[$docid];
594 } else if (isset($incompletedocs[$docid])) {
595 $out[] = $incompletedocs[$docid];
596 }
597 }
598
599 return $out;
600 }
601
602 /**
603 * Retreive any missing main documents and attach provided files.
604 *
605 * The missingdocs array should be an array, indexed by document id, of main documents we need to retrieve. The value
606 * associated to the key should be an array of stored_files or stored file ids to attach to the result document.
607 *
608 * Return array also indexed by document id.
609 *
610 * @param array() $missingdocs An array, indexed by document id, with arrays of files/ids to attach.
611 * @return document[]
612 */
613 protected function get_missing_docs($missingdocs) {
614 if (empty($missingdocs)) {
615 return array();
616 }
617
618 $docids = array_keys($missingdocs);
619
620 // Build a custom query that will get all the missing documents.
621 $query = new \SolrQuery();
053118a1 622 $this->set_query($query, '*');
cd894f84 623 $this->add_fields($query);
053118a1 624 $query->setRows(count($docids));
cd894f84
EM
625 $query->addFilterQuery('{!cache=false}id:(' . implode(' OR ', $docids) . ')');
626
053118a1
EM
627 $response = $this->get_query_response($query);
628 // We know the missing docs have already been checked for access, so don't recheck.
629 $results = $this->process_response($response, 0, true);
cd894f84
EM
630
631 $out = array();
632 foreach ($results as $result) {
633 $resultid = $result->get('id');
634 if (!isset($missingdocs[$resultid])) {
635 // We got a result we didn't expect. Skip it.
636 continue;
637 }
638 // Attach the files.
639 foreach ($missingdocs[$resultid] as $filedoc) {
640 $result->add_stored_file($filedoc);
641 }
642 $out[$resultid] = $result;
643 }
644
645 return $out;
646 }
647
95c6aeaf
DM
648 /**
649 * Returns a standard php array from a \SolrObject instance.
650 *
651 * @param \SolrObject $obj
652 * @return array The returned document as an array.
653 */
654 public function standarize_solr_obj(\SolrObject $obj) {
655 $properties = $obj->getPropertyNames();
656
657 $docdata = array();
658 foreach($properties as $name) {
659 // http://php.net/manual/en/solrobject.getpropertynames.php#98018.
660 $name = trim($name);
661 $docdata[$name] = $obj->offsetGet($name);
662 }
663 return $docdata;
664 }
665
666 /**
667 * Adds a document to the search engine.
668 *
669 * This does not commit to the search engine.
670 *
091973db
EM
671 * @param document $document
672 * @param bool $fileindexing True if file indexing is to be used
673 * @return bool
95c6aeaf 674 */
091973db
EM
675 public function add_document($document, $fileindexing = false) {
676 $docdata = $document->export_for_engine();
677
cd894f84 678 if (!$this->add_solr_document($docdata)) {
091973db
EM
679 return false;
680 }
681
cd894f84
EM
682 if ($fileindexing) {
683 // This will take care of updating all attached files in the index.
684 $this->process_document_files($document);
685 }
686
091973db
EM
687 return true;
688 }
95c6aeaf 689
091973db
EM
690 /**
691 * Adds a text document to the search engine.
692 *
cd894f84 693 * @param array $doc
091973db
EM
694 * @return bool
695 */
cd894f84 696 protected function add_solr_document($doc) {
95c6aeaf
DM
697 $solrdoc = new \SolrInputDocument();
698 foreach ($doc as $field => $value) {
699 $solrdoc->addField($field, $value);
700 }
701
702 try {
703 $result = $this->get_search_client()->addDocument($solrdoc, true, static::AUTOCOMMIT_WITHIN);
091973db 704 return true;
95c6aeaf
DM
705 } catch (\SolrClientException $e) {
706 debugging('Solr client error adding document with id ' . $doc['id'] . ': ' . $e->getMessage(), DEBUG_DEVELOPER);
63d5007b
EM
707 } catch (\SolrServerException $e) {
708 // We only use the first line of the message, as it's a fully java stacktrace behind it.
709 $msg = strtok($e->getMessage(), "\n");
710 debugging('Solr server error adding document with id ' . $doc['id'] . ': ' . $msg, DEBUG_DEVELOPER);
95c6aeaf 711 }
091973db
EM
712
713 return false;
95c6aeaf
DM
714 }
715
cd894f84
EM
716 /**
717 * Index files attached to the docuemnt, ensuring the index matches the current document files.
718 *
719 * For documents that aren't known to be new, we check the index for existing files.
720 * - New files we will add.
721 * - Existing and unchanged files we will skip.
722 * - File that are in the index but not on the document will be deleted from the index.
723 * - Files that have changed will be re-indexed.
724 *
725 * @param document $document
726 */
727 protected function process_document_files($document) {
728 if (!$this->file_indexing_enabled()) {
729 return;
730 }
731
732 // Maximum rows to process at a time.
733 $rows = 500;
734
735 // Get the attached files.
736 $files = $document->get_files();
737
738 // If this isn't a new document, we need to check the exiting indexed files.
739 if (!$document->get_is_new()) {
740 // We do this progressively, so we can handle lots of files cleanly.
741 list($numfound, $indexedfiles) = $this->get_indexed_files($document, 0, $rows);
742 $count = 0;
743 $idstodelete = array();
744
745 do {
746 // Go through each indexed file. We want to not index any stored and unchanged ones, delete any missing ones.
747 foreach ($indexedfiles as $indexedfile) {
748 $fileid = $indexedfile->solr_fileid;
749
750 if (isset($files[$fileid])) {
751 // Check for changes that would mean we need to re-index the file. If so, just leave in $files.
752 // Filelib does not guarantee time modified is updated, so we will check important values.
1aaead91 753 if ($indexedfile->modified != $files[$fileid]->get_timemodified()) {
cd894f84
EM
754 continue;
755 }
756 if (strcmp($indexedfile->title, $files[$fileid]->get_filename()) !== 0) {
757 continue;
758 }
759 if ($indexedfile->solr_filecontenthash != $files[$fileid]->get_contenthash()) {
760 continue;
761 }
f6b4ec7b 762 if ($indexedfile->solr_fileindexstatus == document::INDEXED_FILE_FALSE &&
cd894f84
EM
763 $this->file_is_indexable($files[$fileid])) {
764 // This means that the last time we indexed this file, filtering blocked it.
765 // Current settings say it is indexable, so we will allow it to be indexed.
766 continue;
767 }
768
769 // If the file is already indexed, we can just remove it from the files array and skip it.
770 unset($files[$fileid]);
771 } else {
772 // This means we have found a file that is no longer attached, so we need to delete from the index.
773 // We do it later, since this is progressive, and it could reorder results.
774 $idstodelete[] = $indexedfile->id;
775 }
776 }
777 $count += $rows;
778
779 if ($count < $numfound) {
780 // If we haven't hit the total count yet, fetch the next batch.
781 list($numfound, $indexedfiles) = $this->get_indexed_files($document, $count, $rows);
782 }
783
784 } while ($count < $numfound);
785
786 // Delete files that are no longer attached.
787 foreach ($idstodelete as $id) {
788 // We directly delete the item using the client, as the engine delete_by_id won't work on file docs.
789 $this->get_search_client()->deleteById($id);
790 }
791 }
792
793 // Now we can actually index all the remaining files.
794 foreach ($files as $file) {
795 $this->add_stored_file($document, $file);
796 }
797 }
798
799 /**
800 * Get the currently indexed files for a particular document, returns the total count, and a subset of files.
801 *
802 * @param document $document
803 * @param int $start The row to start the results on. Zero indexed.
804 * @param int $rows The number of rows to fetch
805 * @return array A two element array, the first is the total number of availble results, the second is an array
806 * of documents for the current request.
807 */
808 protected function get_indexed_files($document, $start = 0, $rows = 500) {
809 // Build a custom query that will get any document files that are in our solr_filegroupingid.
810 $query = new \SolrQuery();
811
812 // We want to get all file records tied to a document.
813 // For efficiency, we are building our own, stripped down, query.
814 $query->setQuery('*');
815 $query->setRows($rows);
816 $query->setStart($start);
817 // We want a consistent sorting.
818 $query->addSortField('id');
819
820 // We only want the bare minimum of fields.
821 $query->addField('id');
822 $query->addField('modified');
823 $query->addField('title');
824 $query->addField('solr_fileid');
825 $query->addField('solr_filecontenthash');
f6b4ec7b 826 $query->addField('solr_fileindexstatus');
cd894f84
EM
827
828 $query->addFilterQuery('{!cache=false}solr_filegroupingid:(' . $document->get('id') . ')');
829 $query->addFilterQuery('type:' . \core_search\manager::TYPE_FILE);
830
053118a1
EM
831 $response = $this->get_query_response($query);
832 if (empty($response->response->numFound)) {
cd894f84
EM
833 return array(0, array());
834 }
053118a1
EM
835
836 return array($response->response->numFound, $this->convert_file_results($response));
cd894f84
EM
837 }
838
839 /**
840 * A very lightweight handler for getting information about already indexed files from a Solr response.
841 *
842 * @param SolrObject $responsedoc A Solr response document
843 * @return stdClass[] An array of objects that contain the basic information for file processing.
844 */
845 protected function convert_file_results($responsedoc) {
846 if (!$docs = $responsedoc->response->docs) {
847 return array();
848 }
849
850 $out = array();
851
852 foreach ($docs as $doc) {
853 // Copy the bare minimim needed info.
854 $result = new \stdClass();
855 $result->id = $doc->id;
856 $result->modified = document::import_time_from_engine($doc->modified);
857 $result->title = $doc->title;
858 $result->solr_fileid = $doc->solr_fileid;
859 $result->solr_filecontenthash = $doc->solr_filecontenthash;
f6b4ec7b 860 $result->solr_fileindexstatus = $doc->solr_fileindexstatus;
cd894f84
EM
861 $out[] = $result;
862 }
863
864 return $out;
865 }
866
867 /**
868 * Adds a file to the search engine.
869 *
870 * Notes about Solr and Tika indexing. We do not send the mime type, only the filename.
871 * Tika has much better content type detection than Moodle, and we will have many more doc failures
872 * if we try to send mime types.
873 *
874 * @param document $document
875 * @param \stored_file $storedfile
876 * @return void
877 */
878 protected function add_stored_file($document, $storedfile) {
879 $filedoc = $document->export_file_for_engine($storedfile);
880
881 if (!$this->file_is_indexable($storedfile)) {
882 // For files that we don't consider indexable, we will still place a reference in the search engine.
f6b4ec7b 883 $filedoc['solr_fileindexstatus'] = document::INDEXED_FILE_FALSE;
cd894f84
EM
884 $this->add_solr_document($filedoc);
885 return;
886 }
887
888 $curl = $this->get_curl_object();
889
890 $url = $this->get_connection_url('/update/extract');
891
892 // This will prevent solr from automatically making fields for every tika output.
893 $url->param('uprefix', 'ignored_');
894
546c0af5
EM
895 // Control how content is captured. This will keep our file content clean of non-important metadata.
896 $url->param('captureAttr', 'true');
897 // Move the content to a field for indexing.
898 $url->param('fmap.content', 'solr_filecontent');
899
cd894f84
EM
900 // These are common fields that matches the standard *_point dynamic field and causes an error.
901 $url->param('fmap.media_white_point', 'ignored_mwp');
902 $url->param('fmap.media_black_point', 'ignored_mbp');
903
904 // Copy each key to the url with literal.
905 // We place in a temp name then copy back to the true field, which prevents errors or Tika overwriting common field names.
906 foreach ($filedoc as $key => $value) {
907 // This will take any fields from tika that match our schema and discard them, so they don't overwrite ours.
908 $url->param('fmap.'.$key, 'ignored_'.$key);
909 // Place data in a tmp field.
910 $url->param('literal.mdltmp_'.$key, $value);
911 // Then move to the final field.
912 $url->param('fmap.mdltmp_'.$key, $key);
913 }
914
915 // This sets the true filename for Tika.
916 $url->param('resource.name', $storedfile->get_filename());
917
918 // A giant block of code that is really just error checking around the curl request.
919 try {
920 // Now actually do the request.
921 $result = $curl->post($url->out(false), array('myfile' => $storedfile));
922
923 $code = $curl->get_errno();
924 $info = $curl->get_info();
925
926 // Now error handling. It is just informational, since we aren't tracking per file/doc results.
927 if ($code != 0) {
928 // This means an internal cURL error occurred error is in result.
929 $message = 'Curl error '.$code.' while indexing file with document id '.$filedoc['id'].': '.$result.'.';
930 debugging($message, DEBUG_DEVELOPER);
931 } else if (isset($info['http_code']) && ($info['http_code'] !== 200)) {
932 // Unexpected HTTP response code.
933 $message = 'Error while indexing file with document id '.$filedoc['id'];
934 // Try to get error message out of msg or title if it exists.
935 if (preg_match('|<str [^>]*name="msg"[^>]*>(.*?)</str>|i', $result, $matches)) {
936 $message .= ': '.$matches[1];
937 } else if (preg_match('|<title[^>]*>([^>]*)</title>|i', $result, $matches)) {
938 $message .= ': '.$matches[1];
939 }
940 // This is a common error, happening whenever a file fails to index for any reason, so we will make it quieter.
941 if (CLI_SCRIPT && !PHPUNIT_TEST) {
942 mtrace($message);
943 }
944 } else {
945 // Check for the expected status field.
946 if (preg_match('|<int [^>]*name="status"[^>]*>(\d*)</int>|i', $result, $matches)) {
947 // Now check for the expected status of 0, if not, error.
948 if ((int)$matches[1] !== 0) {
949 $message = 'Unexpected Solr status code '.(int)$matches[1];
950 $message .= ' while indexing file with document id '.$filedoc['id'].'.';
951 debugging($message, DEBUG_DEVELOPER);
952 } else {
953 // The document was successfully indexed.
954 return;
955 }
956 } else {
957 // We received an unprocessable response.
958 $message = 'Unexpected Solr response while indexing file with document id '.$filedoc['id'].': ';
959 $message .= strtok($result, "\n");
960 debugging($message, DEBUG_DEVELOPER);
961 }
962 }
963 } catch (\Exception $e) {
964 // There was an error, but we are not tracking per-file success, so we just continue on.
965 debugging('Unknown exception while indexing file "'.$storedfile->get_filename().'".', DEBUG_DEVELOPER);
966 }
967
968 // If we get here, the document was not indexed due to an error. So we will index just the base info without the file.
f6b4ec7b 969 $filedoc['solr_fileindexstatus'] = document::INDEXED_FILE_ERROR;
cd894f84
EM
970 $this->add_solr_document($filedoc);
971 }
972
973 /**
974 * Checks to see if a passed file is indexable.
975 *
976 * @param \stored_file $file The file to check
977 * @return bool True if the file can be indexed
978 */
979 protected function file_is_indexable($file) {
980 if (!empty($this->config->maxindexfilekb) && ($file->get_filesize() > ($this->config->maxindexfilekb * 1024))) {
981 // The file is too big to index.
982 return false;
983 }
984
985 $mime = $file->get_mimetype();
986
987 if ($mime == 'application/vnd.moodle.backup') {
988 // We don't index Moodle backup files. There is nothing usefully indexable in them.
989 return false;
990 }
991
992 return true;
993 }
994
95c6aeaf
DM
995 /**
996 * Commits all pending changes.
997 *
998 * @return void
999 */
075fa912 1000 protected function commit() {
95c6aeaf
DM
1001 $this->get_search_client()->commit();
1002 }
1003
075fa912
EM
1004 /**
1005 * Do any area cleanup needed, and do anything to confirm contents.
1006 *
1007 * Return false to prevent the search area completed time and stats from being updated.
1008 *
0bd8383a 1009 * @param \core_search\base $searcharea The search area that was complete
075fa912
EM
1010 * @param int $numdocs The number of documents that were added to the index
1011 * @param bool $fullindex True if a full index is being performed
1012 * @return bool True means that data is considered indexed
1013 */
1014 public function area_index_complete($searcharea, $numdocs = 0, $fullindex = false) {
1015 $this->commit();
1016
1017 return true;
1018 }
1019
cd894f84
EM
1020 /**
1021 * Return true if file indexing is supported and enabled. False otherwise.
1022 *
1023 * @return bool
1024 */
1025 public function file_indexing_enabled() {
1026 return (bool)$this->config->fileindexing;
1027 }
1028
95c6aeaf
DM
1029 /**
1030 * Defragments the index.
1031 *
1032 * @return void
1033 */
1034 public function optimize() {
bfd6c78f 1035 $this->get_search_client()->optimize(1, true, false);
95c6aeaf
DM
1036 }
1037
1038 /**
1039 * Deletes the specified document.
1040 *
1041 * @param string $id The document id to delete
1042 * @return void
1043 */
1044 public function delete_by_id($id) {
cd894f84
EM
1045 // We need to make sure we delete the item and all related files, which can be done with solr_filegroupingid.
1046 $this->get_search_client()->deleteByQuery('solr_filegroupingid:' . $id);
075fa912 1047 $this->commit();
95c6aeaf
DM
1048 }
1049
1050 /**
1051 * Delete all area's documents.
1052 *
1053 * @param string $areaid
1054 * @return void
1055 */
1056 public function delete($areaid = null) {
1057 if ($areaid) {
1058 $this->get_search_client()->deleteByQuery('areaid:' . $areaid);
1059 } else {
1060 $this->get_search_client()->deleteByQuery('*:*');
1061 }
075fa912 1062 $this->commit();
95c6aeaf
DM
1063 }
1064
1065 /**
1066 * Pings the Solr server using search_solr config
1067 *
1068 * @return true|string Returns true if all good or an error string.
1069 */
1070 public function is_server_ready() {
1071
23fc1be8
DM
1072 $configured = $this->is_server_configured();
1073 if ($configured !== true) {
1074 return $configured;
1075 }
1076
1077 // Check that the schema is already set up.
1078 try {
1079 $schema = new \search_solr\schema();
1080 $schema->validate_setup();
1081 } catch (\moodle_exception $e) {
1082 return $e->getMessage();
1083 }
1084
1085 return true;
1086 }
1087
1088 /**
1089 * Is the solr server properly configured?.
1090 *
1091 * @return true|string Returns true if all good or an error string.
1092 */
1093 public function is_server_configured() {
1094
95c6aeaf
DM
1095 if (empty($this->config->server_hostname) || empty($this->config->indexname)) {
1096 return 'No solr configuration found';
1097 }
1098
7a4a0bc8 1099 if (!$client = $this->get_search_client(false)) {
95c6aeaf
DM
1100 return get_string('engineserverstatus', 'search');
1101 }
1102
1103 try {
23fc1be8
DM
1104 if ($this->get_solr_major_version() < 4) {
1105 // Minimum solr 4.0.
1106 return get_string('minimumsolr4', 'search_solr');
1107 }
95c6aeaf 1108 } catch (\SolrClientException $ex) {
d0b4772c
DM
1109 debugging('Solr client error: ' . html_to_text($ex->getMessage()), DEBUG_DEVELOPER);
1110 return get_string('engineserverstatus', 'search');
95c6aeaf 1111 } catch (\SolrServerException $ex) {
d0b4772c
DM
1112 debugging('Solr server error: ' . html_to_text($ex->getMessage()), DEBUG_DEVELOPER);
1113 return get_string('engineserverstatus', 'search');
95c6aeaf
DM
1114 }
1115
95c6aeaf
DM
1116 return true;
1117 }
1118
23fc1be8
DM
1119 /**
1120 * Returns the solr server major version.
1121 *
1122 * @return int
1123 */
1124 public function get_solr_major_version() {
d0b4772c
DM
1125 // We should really ping first the server to see if the specified indexname is valid but
1126 // we want to minimise solr server requests as they are expensive. system() emits a warning
1127 // if it can not connect to the configured index in the configured server.
1128 $systemdata = @$this->get_search_client()->system();
23fc1be8
DM
1129 $solrversion = $systemdata->getResponse()->offsetGet('lucene')->offsetGet('solr-spec-version');
1130 return intval(substr($solrversion, 0, strpos($solrversion, '.')));
1131 }
1132
95c6aeaf
DM
1133 /**
1134 * Checks if the PHP Solr extension is available.
1135 *
1136 * @return bool
1137 */
1138 public function is_installed() {
1139 return function_exists('solr_get_version');
1140 }
1141
1142 /**
1143 * Returns the solr client instance.
1144 *
7a4a0bc8
EM
1145 * We don't reuse SolrClient if we are on libcurl 7.35.0, due to a bug in that version of curl.
1146 *
95c6aeaf
DM
1147 * @throws \core_search\engine_exception
1148 * @param bool $triggerexception
1149 * @return \SolrClient
1150 */
1151 protected function get_search_client($triggerexception = true) {
558b6306 1152 global $CFG;
95c6aeaf
DM
1153
1154 // Type comparison as it is set to false if not available.
1155 if ($this->client !== null) {
1156 return $this->client;
1157 }
1158
1159 $options = array(
1160 'hostname' => $this->config->server_hostname,
1161 'path' => '/solr/' . $this->config->indexname,
1162 'login' => !empty($this->config->server_username) ? $this->config->server_username : '',
1163 'password' => !empty($this->config->server_password) ? $this->config->server_password : '',
1164 'port' => !empty($this->config->server_port) ? $this->config->server_port : '',
5dc4624c 1165 'secure' => !empty($this->config->secure) ? true : false,
95c6aeaf 1166 'ssl_cert' => !empty($this->config->ssl_cert) ? $this->config->ssl_cert : '',
95c6aeaf 1167 'ssl_key' => !empty($this->config->ssl_key) ? $this->config->ssl_key : '',
5dc4624c 1168 'ssl_keypassword' => !empty($this->config->ssl_keypassword) ? $this->config->ssl_keypassword : '',
95c6aeaf
DM
1169 'ssl_cainfo' => !empty($this->config->ssl_cainfo) ? $this->config->ssl_cainfo : '',
1170 'ssl_capath' => !empty($this->config->ssl_capath) ? $this->config->ssl_capath : '',
bfd6c78f 1171 'timeout' => !empty($this->config->server_timeout) ? $this->config->server_timeout : '30'
95c6aeaf
DM
1172 );
1173
558b6306 1174 if ($CFG->proxyhost && !is_proxybypass('http://' . $this->config->server_hostname . '/')) {
1175 $options['proxy_host'] = $CFG->proxyhost;
1176 $options['proxy_port'] = $CFG->proxyport;
1177 }
1178
e240a613
DM
1179 if (!class_exists('\SolrClient')) {
1180 throw new \core_search\engine_exception('enginenotinstalled', 'search', '', 'solr');
1181 }
1182
7a4a0bc8 1183 $client = new \SolrClient($options);
95c6aeaf 1184
7a4a0bc8 1185 if ($client === false && $triggerexception) {
95c6aeaf
DM
1186 throw new \core_search\engine_exception('engineserverstatus', 'search');
1187 }
1188
7a4a0bc8
EM
1189 if ($this->cacheclient) {
1190 $this->client = $client;
1191 }
1192
1193 return $client;
95c6aeaf 1194 }
5dc4624c
EM
1195
1196 /**
1197 * Returns a curl object for conntecting to solr.
1198 *
1199 * @return \curl
1200 */
1201 public function get_curl_object() {
1202 if (!is_null($this->curl)) {
1203 return $this->curl;
1204 }
1205
402a8e7a
MG
1206 // Connection to Solr is allowed to use 'localhost' and other potentially blocked hosts/ports.
1207 $this->curl = new \curl(['ignoresecurity' => true]);
5dc4624c
EM
1208
1209 $options = array();
1210 // Build the SSL options. Based on pecl-solr and general testing.
1211 if (!empty($this->config->secure)) {
1212 if (!empty($this->config->ssl_cert)) {
1213 $options['CURLOPT_SSLCERT'] = $this->config->ssl_cert;
1214 $options['CURLOPT_SSLCERTTYPE'] = 'PEM';
1215 }
1216
1217 if (!empty($this->config->ssl_key)) {
1218 $options['CURLOPT_SSLKEY'] = $this->config->ssl_key;
1219 $options['CURLOPT_SSLKEYTYPE'] = 'PEM';
1220 }
1221
1222 if (!empty($this->config->ssl_keypassword)) {
1223 $options['CURLOPT_KEYPASSWD'] = $this->config->ssl_keypassword;
1224 }
1225
1226 if (!empty($this->config->ssl_cainfo)) {
1227 $options['CURLOPT_CAINFO'] = $this->config->ssl_cainfo;
1228 }
1229
1230 if (!empty($this->config->ssl_capath)) {
1231 $options['CURLOPT_CAPATH'] = $this->config->ssl_capath;
1232 }
1233 }
1234
411b5f3a 1235 // Set timeout as for Solr client.
1236 $options['CURLOPT_TIMEOUT'] = !empty($this->config->server_timeout) ? $this->config->server_timeout : '30';
1237
5dc4624c
EM
1238 $this->curl->setopt($options);
1239
1240 if (!empty($this->config->server_username) && !empty($this->config->server_password)) {
1241 $authorization = $this->config->server_username . ':' . $this->config->server_password;
c7203847 1242 $this->curl->setHeader('Authorization: Basic ' . base64_encode($authorization));
5dc4624c
EM
1243 }
1244
1245 return $this->curl;
1246 }
1247
1248 /**
1249 * Return a Moodle url object for the server connection.
1250 *
1251 * @param string $path The solr path to append.
1252 * @return \moodle_url
1253 */
1254 public function get_connection_url($path) {
1255 // Must use the proper protocol, or SSL will fail.
1256 $protocol = !empty($this->config->secure) ? 'https' : 'http';
1257 $url = $protocol . '://' . rtrim($this->config->server_hostname, '/');
1258 if (!empty($this->config->server_port)) {
1259 $url .= ':' . $this->config->server_port;
1260 }
1261 $url .= '/solr/' . $this->config->indexname . '/' . ltrim($path, '/');
1262
1263 return new \moodle_url($url);
1264 }
95c6aeaf 1265}