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