-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsearchlib.php
1911 lines (1776 loc) · 73.4 KB
/
searchlib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Library functions that provide full-text search.
*
* @package local_ousearch
* @copyright 2015 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use \local_ousearch\year_tables;
defined('MOODLE_INTERNAL') || die();
/**
* Class that handles search documents. A search document represents a single
* thing that can be found by the search engine, so it could be a forum post,
* a blog entry, or whatever.
*/
class local_ousearch_document {
/**
* Maximum length of words stored in database.
* @var int
*/
const MAX_WORD_LENGTH = 32;
public $id, $plugin, $coursemoduleid, $courseid, $timemodified, $timeexpires, $groupid, $userid, $stringref, $intref1, $intref2;
/**
* Static function. Deletes all data relating to a module instance.
* @param object $cm Course-module object (must have at least ->id and ->course)
*/
public static function delete_module_instance_data($cm) {
global $DB;
$where = 'courseid=? AND coursemoduleid=?';
$wherearray = array($cm->course, $cm->id);
$course = get_course($cm->course);
$year = year_tables::get_year_for_tables($course);
$occurstable = year_tables::get_occurs_table($year);
$docstable = year_tables::get_docs_table($year);
$DB->delete_records_select($occurstable,
'documentid IN (SELECT id FROM {' . $docstable . '} WHERE ' .
$where . ')', $wherearray);
$DB->delete_records_select($docstable, $where, $wherearray);
// If this course is currently being transferred to the year-table
// system, delete in both places in case this data was already
// transferred.
if (!$year && year_tables::currently_transferring_course($cm->course)) {
$newyear = year_tables::get_year_for_course($course);
$occurstable = year_tables::get_occurs_table($newyear);
$docstable = year_tables::get_docs_table($newyear);
$DB->delete_records_select($occurstable,
'documentid IN (SELECT id FROM {' . $docstable . '} WHERE ' .
$where . ')', $wherearray);
$DB->delete_records_select($docstable,
$where, $wherearray);
}
}
/**
* Initialise document with appropriate parameters for when text comes
* from a module instance.
* @param string $modulename Name of module e.g. 'ouwiki'
* @param object $cm Course-module object (required fields: id, course)
* @param int $timemodified Optional modified time, otherwise uses current
* @param int $timeexpires Optional expire time, otherwise uses null
*/
public function init_module_instance($modulename, $cm,
$timemodified=null, $timeexpires=null) {
$this->plugin = 'mod_' . $modulename;
$this->coursemoduleid = (int)$cm->id;
$this->courseid = (int)$cm->course;
if ($timemodified) {
$this->timemodified = (int)$timemodified;
} else {
$this->timemodified = time();
}
if ($timeexpires) {
$this->timeexpires = (int)$timeexpires;
}
}
/**
* Initialises document with all fields from database record.
*
* @param stdClass $rec Database record
*/
public function init_from_record($rec) {
$this->id = $rec->id;
$this->plugin = $rec->plugin;
$this->timemodified = $rec->timemodified;
if ($rec->courseid) {
$this->courseid = $rec->courseid;
}
if ($rec->coursemoduleid) {
$this->coursemoduleid = $rec->coursemoduleid;
}
if ($rec->groupid) {
$this->groupid = $rec->groupid;
}
if ($rec->userid) {
$this->userid = $rec->userid;
}
if ($rec->stringref) {
$this->stringref = $rec->stringref;
}
if ($rec->intref1) {
$this->intref1 = $rec->intref1;
}
if ($rec->intref2) {
$this->intref2 = $rec->intref2;
}
if ($rec->timeexpires) {
$this->timeexpires = $rec->timeexpires;
}
}
/**
* Initialise document for testing use.
* @param string $testname Test name (used for
* testname_ousearch_get_document function)
*/
public function init_test($testname) {
$this->plugin = 'test_' . $testname;
$this->timemodified = time();
}
/**
* Sets the optional group ID.
* @param int $groupid Group ID
*/
public function set_group_id($groupid) {
$this->groupid = (int)$groupid;
}
/**
* Sets the optional user ID.
* @param int $userid User ID
*/
public function set_user_id($userid) {
$this->userid = (int)$userid;
}
/**
* Sets the optional string reference that locates this document
* within a module instance.
* @param string $stringref String reference
*/
public function set_string_ref($stringref) {
$this->stringref = $stringref;
}
/**
* Sets the optional int refs that locate this document within a
* module instance.
* @param int $intref1 Int ref
* @param int $intref2 Optional second int ref
*/
public function set_int_refs($intref1, $intref2=null) {
$this->intref1 = (int)$intref1;
if (!is_null($intref2)) {
$this->intref2 = (int)$intref2;
}
}
/**
* Gets the year to use for tables.
*
* @return int|bool Year number or false if not using system
*/
private function get_year_for_tables() {
if (empty($this->courseid)) {
return \local_ousearch\year_tables::get_year_for_tables(null);
} else {
return \local_ousearch\year_tables::get_year_for_tables(get_course($this->courseid));
}
}
/**
* Gets the documents table to use for this document.
*
* @return string Table name (without Moodle prefix)
*/
protected function get_documents_table() {
return year_tables::get_docs_table($this->get_year_for_tables());
}
/**
* Gets the occurrences table to use for this document.
*
* @return string Table name (without Moodle prefix)
*/
protected function get_occurrences_table() {
return year_tables::get_occurs_table($this->get_year_for_tables());
}
/**
* Finds an existing document. The necessary set_ methods must already
* have been called. If successful, $this->id will be set.
*
* @param string $table Table to look in (leave null for default)
* @return True for success, false for failure
*/
public function find($table = null) {
global $DB;
if (!empty($this->id)) { // Already got it.
return true;
}
if (!$table) {
$table = $this->get_documents_table();
}
// Set up conditions and start off with plugin restriction.
$wherearray = array();
if (isset($this->plugin)) {
$where = "plugin=?";
$wherearray[] = $this->plugin;
}
if (isset($this->courseid)) {
$where .= " AND courseid=?";
$wherearray[] = $this->courseid;
} else {
$where .= " AND courseid IS NULL";
}
if (isset($this->coursemoduleid)) {
$where .= " AND coursemoduleid=?";
$wherearray[] = $this->coursemoduleid;
} else {
$where .= " AND coursemoduleid IS NULL";
}
if (isset($this->groupid)) {
$where .= " AND groupid=?";
$wherearray[] = $this->groupid;
} else {
$where .= " AND groupid IS NULL";
}
if (isset($this->userid)) {
$where .= " AND userid=?";
$wherearray[] = $this->userid;
} else {
$where .= " AND userid IS NULL";
}
if (isset($this->stringref)) {
$where .= " AND stringref=?";
$wherearray[] = $this->stringref;
} else {
$where .= " AND stringref IS NULL";
}
if (isset($this->intref1)) {
$where .= " AND intref1=?";
$wherearray[] = $this->intref1;
} else {
$where .= " AND intref1 IS NULL";
}
if (isset($this->intref2)) {
$where .= " AND intref2=?";
$wherearray[] = $this->intref2;
} else {
$where .= " AND intref2 IS NULL";
}
$this->id = $DB->get_field_select($table, 'id', $where, $wherearray);
return $this->id ? true : false;
}
/**
* Adds a new document or updates an existing one. The necessary set_
* methods must already have been called.
* @param string $title Document title (plain text)
* @param string $content Document content (XHTML)
* @param int $timemodified Optional modified time (defaults to now)
* @param int $timeexpires Optional expiry time (defaults to none); if
* expiry time is included then module must provide a
* modulename_ousearch_update($document=null) function
* @param array $extrastrings An array of additional strings which are
* searchable, but not included as part of the document content (for
* display to users etc); this can be used for keywords and the like;
* null for none
* @throws dml_exception If failure
*/
public function update($title, $content, $timemodified=null, $timeexpires=null,
$extrastrings=null) {
global $DB;
if (local_ousearch_indexingdisabled()) {
// Do nothing if the OU Search system is turned off.
return;
}
$transaction = $DB->start_delegated_transaction();
// Find document ID, creating document if needed.
if (!$this->find()) {
// Arse around with slashes so we can insert it safely
// but the data is corrected again later.
$this->id = $DB->insert_record($this->get_documents_table(), $this);
} else {
// When updating existing document, set timemodified.
$timemodified = time();
}
// Update document record if needed.
if ($timemodified || $timeexpires) {
$update = new StdClass;
$update->id = $this->id;
if ($timemodified) {
$update->timemodified = $timemodified;
}
if ($timeexpires) {
$update->timeexpires = $timeexpires;
}
$DB->update_record($this->get_documents_table(), $update);
}
// Delete existing words.
$DB->delete_records($this->get_occurrences_table(),
array('documentid' => $this->id));
// Extra strings are just counted as more content in the database.
if ($extrastrings) {
foreach ($extrastrings as $string) {
$content .= ' ' . $string;
}
}
// Add new words.
$this->internal_add_words($title, $content);
$transaction->allow_commit();
}
/**
* Strips XHTML bits that don't display as text to users.
*
* Note: This is not really intended to be public as such, but it needs to be called
* within ousearch_search.
* @param string $content XHTML string
* @return string Plain-text string
*/
public static function strip_xhtml($content) {
$content = preg_replace(array(
'|<!--.*?-->|s', // Comments.
'|<script.*?</script>|s', // Scripts.
'|<noscript.*?</noscript>|s', // Noscript.
'|<object.*?</object>|s', // Objects.
), '', $content);
$content = preg_replace('|<.*?>|', ' ', $content); // All tags.
return html_entity_decode($content, ENT_QUOTES, 'UTF-8');
}
/**
* Internal method that actually adds words for this document to the
* database.
* @param string $title Title of document
* @param string $content XHTML content of document
* @throws dml_exception If failure
*/
private function internal_add_words($title, $content) {
global $DB;
// Build up set of words with counts.
$wordset = array();
self::internal_add_to_wordset($wordset, $title, true);
self::internal_add_to_wordset($wordset, self::strip_xhtml($content));
if (count($wordset) == 0) {
return true;
}
// Cut down all words to max db length.
foreach ($wordset as $word => $count) {
// Check byte length just to save time.
if (strlen($word) > self::MAX_WORD_LENGTH) {
// Cut length of word.
$short = core_text::substr($word, 0, self::MAX_WORD_LENGTH);
// Combine with existing word if there are two with same prefix.
if (array_key_exists($short, $wordset)) {
$count += $wordset[$short];
}
// Save as short word and remove long one.
$wordset[$short] = $count;
unset($wordset[$word]);
}
}
// Get word IDs from database.
$list = '';
$listarray = array();
foreach ($wordset as $word => $count) {
$list .= ",?";
$listarray[] = $word;
}
$list = substr($list, 1); // Get rid of first comma.
$dbwords = $DB->get_records_select('local_ousearch_words',
'word IN (' . $list . ')', $listarray, '', 'word,id');
// Add any missing words to database. This is a performance-critical
// operation, so we provide an efficient way to do it coded specifically
// for Postgres. Unfortunately this cannot be done with standard Moodle
// Postgres driver because it does not expose the Postgres connection
// ID, so you can only use this if you use an OU overridden version of
// the Postgres driver. (This override is very simple. It is available
// in OU public repository in lib/dml folder.)
if ($fastpg = is_a($DB, 'ou_pgsql_native_moodle_database')) {
// Do this in 512-word blocks (there is a limit at 1664).
$sequences = array();
$pos = 0;
$missingwords = array();
foreach ($wordset as $word => $count) {
if (!isset($dbwords[$word])) {
$missingwords[$pos] = $word;
$sequenceindex = (int)($pos / 512);
if (!array_key_exists($sequenceindex, $sequences)) {
$sequences[$sequenceindex] = '';
}
// Note: Cannot use {} syntax here because the sequence name
// is inside a string so I don't think Moodle will replace
// it.
$sequences[$sequenceindex] .= ',nextval(\'' .
$DB->get_prefix() .
'local_ousearch_words_id_seq\') AS s' . $pos;
$pos++;
}
}
if (count($missingwords) > 0) {
foreach ($sequences as $sequenceindex => $sequenceselect) {
$rs = $DB->get_recordset_sql($sql = 'SELECT ' .
substr($sequences[$sequenceindex], 1), array());
$fields = (array)$rs->current();
$rs->close();
$data = array();
for ($i = $sequenceindex * 512;
$i < $pos && $i < ($sequenceindex + 1) * 512;
$i++) {
$id = $fields['s' . $i];
$data[] = $id . "\t" . $missingwords[$i];
$dbwords[$missingwords[$i]] = new stdClass;
$dbwords[$missingwords[$i]]->id = $id;
}
if (!pg_copy_from($DB->get_pgsql_connection_id(),
$DB->get_prefix() . 'local_ousearch_words',
$data)) {
throw new dml_exception(
'fastinserterror', 'local_ousearch');
}
}
}
} else {
// This is the slow Moodle-standard way to insert words, for all
// other database drivers.
foreach ($wordset as $word => $count) {
if (!isset($dbwords[$word])) {
$newword = (object)array('word' => $word);
$newword->id = $DB->insert_record(
'local_ousearch_words', $newword);
$dbwords[$word] = $newword;
}
}
}
// Now add the records attaching the words, with scoring, to this document.
if ($fastpg && count($wordset) > 0) {
// Fast insert data.
$data = array();
foreach ($wordset as $word => $count) {
$titlecount = empty($count[true]) ? 0 : $count[true];
$bodycount = empty($count[false]) ? 0 : $count[false];
$score = ($bodycount < 15 ? $bodycount : 15) +
($titlecount < 15 ? $titlecount * 16 : 15 * 16);
$data[] = $dbwords[$word]->id . "\t" . $this->id . "\t" .
$score;
}
if (!pg_copy_from($DB->get_pgsql_connection_id(),
$DB->get_prefix() . $this->get_occurrences_table(), $data)) {
throw new dml_exception(
'fastinserterror', 'local_ousearch');
}
} else {
// Slow insert data for all databases.
foreach ($wordset as $word => $count) {
$titlecount = empty($count[true]) ? 0 : $count[true];
$bodycount = empty($count[false]) ? 0 : $count[false];
$score = ($bodycount < 15 ? $bodycount : 15) +
($titlecount < 15 ? $titlecount * 16 : 15 * 16);
$DB->execute('INSERT INTO {' . $this->get_occurrences_table() . '}' .
'(wordid, documentid, score) VALUES(?,?,?)',
array($dbwords[$word]->id, $this->id, $score));
}
}
}
/**
* Splits text into words.
* Note: This is not really intended to be public as such, but it needs to be called
* within ousearch_search.
* @param string $text Text to split
* @param bool $query If true, text is treated as a query (preserve +, -,
* and ")
* @param bool $positions If true, returns positions
* @return array If $positions is false, returns an array of words. If it
* is true, returns a two-element array, first being an array of words,
* second being a corresponding array of start positions of each word
* (in characters) with one extra value holding end position/length
* in characters
*/
public static function split_words($text, $query=false, $positions=false) {
// Treat single right quote as apostrophe.
$text = str_replace("\xe2\x80\x99", "'", $text ?? '');
// Words include all letters, numbers, and apostrophes. Though this is
// expressed with Unicode it is likely to work properly only for English and
// some other European languages.
$text = preg_replace(
$query ? '/[^\pL\pN\x27+"-]/u' : '/[^\pL\pN\x27]/u',
'_', core_text::strtolower($text));
if (!$positions) {
$text = preg_replace('/\x27+(_|$)/u', '_', $text);
$text = preg_replace('/(^|_)\x27+/u', '_', $text);
$text = preg_replace('/_+/u', '_', $text);
$result = explode('_', $text);
$words = array();
foreach ($result as $word) {
if ($word !== '') {
$words[] = $word;
}
}
return $words;
} else {
$text = self::replace_with_underline('/\x27+(_|$)/u', $text);
$text = self::replace_with_underline('/(^|_)\x27+/u', $text);
$words = array();
$positions = array();
$pos = 0;
while ($pos < core_text::strlen($text)) {
if (core_text::substr($text, $pos, 1) === '_') {
$pos++;
continue;
}
$nextunderline = core_text::strpos($text, '_', $pos + 1);
if ($nextunderline === false) {
$nextunderline = core_text::strlen($text);
}
$words[] = core_text::substr($text, $pos, $nextunderline - $pos);
$positions[] = $pos;
$pos = $nextunderline + 1;
}
$positions[] = core_text::strlen($text);
return array($words, $positions);
}
}
/**
* This preg_replace callback just replaces the match with an equal number
* of underline characters.
* @param $matches Regex matches
*/
private static function internal_replace_callback($matches) {
$underlines = '';
for ($i = 0; $i < core_text::strlen($matches[0]); $i++) {
$underlines .= '_';
}
return $underlines;
}
/**
* Uses preg_replace functions to replace a pattern with the same number of underlines.
* @param string $pattern Pattern to replace
* @param string $text Text to replace in
* @return New text (same length)
*/
private static function replace_with_underline($pattern, $text) {
return preg_replace_callback($pattern,
array('local_ousearch_document', 'internal_replace_callback'),
$text);
}
/**
* Splits the given plain text content into words and adds each word to a
* set along with listing the number of occurrences.
* @param array &$wordset Set from word => title (true/false) =>
* occurrence count
* @param string $text Plain text to add
* @param bool $title Whether to add to title or nontitle occurrence count
*/
private function internal_add_to_wordset(&$wordset, $text, $title=false) {
$words = self::split_words($text);
foreach ($words as $word) {
// Count occurrences in title or content.
$before = isset($wordset[$word][$title]) ? $wordset[$word][$title] : 0;
$wordset[$word][$title] = $before + 1;
}
}
/**
* Deletes this document and all its words.
*/
public function delete() {
// Find document ID.
if (!$this->find()) {
debugging('Failed to find ousearch document');
return false;
}
self::wipe_document($this->id);
}
/**
* Static function that wipes document and words
* @param int $id ID of document to wipe
*/
public function wipe_document($id) {
global $DB;
if (local_ousearch_indexingdisabled()) {
// Do nothing if the OU Search system is turned off.
return false;
}
// Delete existing document and occurrences.
$DB->delete_records($this->get_occurrences_table(), array('documentid' => $id));
$DB->delete_records($this->get_documents_table(), array('id' => $id));
// If the course is currently being transferred we should get rid of it
// from the new table too.
if (isset($this->courseid) &&
year_tables::currently_transferring_course($this->courseid)) {
$course = get_course($this->courseid);
$year = year_tables::get_year_for_course($course);
$otherdoc = new local_ousearch_document();
$otherdoc->init_from_record($this);
unset($otherdoc->id);
if ($otherdoc->find('local_ousearch_docs_' . $year)) {
$DB->delete_records($this->get_occurrences_table(), array('documentid' => $id));
$DB->delete_records($this->get_documents_table(), array('id' => $id));
}
}
}
}
/**
* Represents a search, including the terms being searched for and the context
* searched within.
*/
class local_ousearch_search {
/**
* Number of results to display on default search result pages.
* @var int
*/
const RESULTS_PER_PAGE = 10;
/**
* Number of words in summary.
* @var int
*/
const SUMMARY_LENGTH = 50;
/**
* You can't just set this to true to make it support OR, that would need
* a bunch of work, but it was put in for possible changes.
* @var bool
*/
const SUPPORTS_OR = false;
/**
* Constant used to indicate that a result must have no (something).
* @var string
*/
const NONE = 'none';
public $courseid = 0, $plugin = '', $coursemoduleid = 0, $cmarray, $filter = null;
public $groupids = null, $allownogroup = true, $groupexceptions = null, $userids = null,
$allownouser = true;
public $querytext;
// Search is expressed as follows.
// Terms, array of objects:
// ->words (array of string, possibly length 1)
// ->ids (matching array of int)
// ->required (bool)
// Negative terms, array of objects:
// ->words (array of string, possibly length 1)
// ->ids (matching array of int).
public $terms, $negativeterms;
// True if translate_words has been done.
public $translated = false;
public function __construct($query) {
$this->set_query($query);
}
/**
* Sets the text of the search query from user input.
* @param string $query User input query text
*/
public function set_query($query) {
$this->querytext = $query;
// Clear the existing arrays.
$this->terms = array();
$this->negativeterms = array();
// Refill those arrays from the query text.
$words = local_ousearch_document::split_words($query, true);
$currentquote = array();
$sign = false;
$inquote = false;
foreach ($words as $word) {
// Clean word to get rid of +, ", and - except if it's in the middle.
$cleaned = preg_replace('/(^-)|(-$)/', '',
preg_replace('/[+"]/', '', $word));
// Shorten word if necessary to db length.
$cleaned = core_text::substr($cleaned, 0,
local_ousearch_document::MAX_WORD_LENGTH);
if ($inquote) {
// Handle hyphenated words.
if (strpos($cleaned, '-') !== false) {
foreach (explode('-', $cleaned) as $subword) {
$currentquote[] = $subword;
}
} else {
$currentquote[] = $cleaned;
}
self::internal_end_quote($currentquote, $word, $sign, $inquote);
} else {
// The below are all single-byte characters so we don't need to
// use textlib here.
$firstchar = substr($word, 0, 1);
$secondchar = strlen($word) > 1 ? substr($word, 1, 1) : false;
if ($firstchar == '"') {
// E.g. "a phrase".
$currentquote = self::internal_hyphenated_array($cleaned);
$inquote = true;
$sign = '';
self::internal_end_quote($currentquote, $word, $sign, $inquote);
} else if ($firstchar == '+' && $secondchar == '"') {
// E.g. +"a phrase".
$currentquote = self::internal_hyphenated_array($cleaned);
$inquote = true;
$sign = '+';
self::internal_end_quote($currentquote, $word, $sign, $inquote);
} else if ($firstchar == '-' && $secondchar == '"') {
// E.g. -"a phrase".
$currentquote = self::internal_hyphenated_array($cleaned);
$inquote = true;
$sign = '-';
self::internal_end_quote($currentquote, $word, $sign, $inquote);
} else if ($firstchar == '+' && $cleaned !== '') {
// E.g. +cat.
$term = new StdClass;
$term->words = self::internal_hyphenated_array($cleaned);
$term->required = true;
$this->terms[] = $term;
} else if ($firstchar == '-' && $cleaned !== '') {
// E.g. -cat.
$term = new StdClass;
$term->words = self::internal_hyphenated_array($cleaned);
$this->negativeterms[] = $term;
} else if ($cleaned !== '') {
$term = new StdClass;
$term->words = self::internal_hyphenated_array($cleaned);
$term->required = false;
$this->terms[] = $term;
}
}
}
}
/**
* Called while parsing query, when a quote run may have finished.
* @param array $currentquote Words in quote so far
* @param string $word Current word (looking for quote at end of this)
* @param string $sign Quote sign
* @param bool $inquote True if in quote (OUT: Set to false if quote ended)
*/
private function internal_end_quote($currentquote, $word, $sign, &$inquote) {
if (substr($word, strlen($word) - 1, 1) == '"') {
$term = new StdClass;
$term->words = $currentquote;
switch($sign) {
case '+':
$term->required = true;
$this->terms[] = $term;
break;
case '':
$term->required = false;
$this->terms[] = $term;
break;
case '-':
$term->required = true;
$this->negativeterms[] = $term;
break;
}
$inquote = false;
}
}
private function internal_hyphenated_array($cleaned) {
if (strpos($cleaned, '-') !== false) {
$currentquote = array();
foreach (explode('-', $cleaned) as $subword) {
$currentquote[] = $subword;
}
return $currentquote;
} else {
return array($cleaned);
}
}
/**
* Restricts search to a particular course.
* @param int $courseid Course ID or 0 for no restriction
*/
public function set_course_id($courseid=0) {
$this->courseid = (int)$courseid;
}
/**
* Restricts search to the course-modules that are visible to the current
* user on the given course.
* @param object $course Moodle course object
* @param string $modname If set, restricts to modules of certain name
* e.g. forumng
*/
public function set_visible_modules_in_course($course, $modname = null) {
global $CFG;
$modinfo = get_fast_modinfo($course);
$visiblecms = array();
foreach ($modinfo->cms as $cm) {
if ($modname && $cm->modname != $modname) {
continue;
}
if ($cm->uservisible) {
require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
$getcmfunction = $cm->modname . '_ousearch_add_visible_module';
if (function_exists($getcmfunction)) {
$visiblecms[$cm->id] = $getcmfunction($cm, $course);
} else {
$visiblecms[$cm->id] = $cm;
}
}
}
$this->set_coursemodule_array($visiblecms);
}
/**
* Restricts search to a particular plugin.
* @param string $plugin Plugin name e.g. 'mod/ouwiki' or '' for no
* restriction
*/
public function set_plugin($plugin='') {
$this->plugin = $plugin;
}
/**
* Restricts search to a particular course-module. This cancels any
* multiple coursemodule restrictions.
* @param object $coursemodule Course-module object or null to remove
* course and module restrictions
*/
public function set_coursemodule($cm=null) {
if ($cm == null) {
$this->courseid = 0;
$this->coursemoduleid = 0;
} else {
$this->cmarray = null;
$this->courseid = (int)$cm->course;
$this->coursemoduleid = (int)$cm->id;
}
}
/**
* Restricts search to specified course-modules. Note that this cancels
* any single coursemodule restriction.
* @param object $cmarray Array of course-modules or null to cancel this
* requirement
*/
public function set_coursemodule_array($cmarray) {
if (is_array($cmarray) && empty($cmarray)) {
// Specifying an empty array, meaning there should be no results,
// causes problems. This code ensures that the array is not empty
// but it won't find any results.
$cmarray = array((object)array('id' => -1, 'course' => -1));
}
$this->cmarray = $cmarray;
if ($cmarray) {
$singlecourse = 0;
foreach ($cmarray as $cm) {
if (!$singlecourse) {
$singlecourse = $cm->course;
} else if ($singlecourse != $cm->course) {
$singlecourse = -1;
}
}
$this->courseid = $singlecourse > 0 ? $singlecourse : 0;
$this->coursemoduleid = 0;
}
}
/**
* Restricts search to a particular group.
* @param int $groupid Single required group ID
*/
public function set_group_id($groupid) {
$this->groupids = array($groupid);
$this->allownogroup = false;
}
/**
* Restricts search to a particular set of groups.
* @param mixed $groupids Array of group IDs, or null for any group, or
* local_ousearch_search::NONE to return only results that have no group
* @param bool $ornone If true, also returns results that have no group
* (ignored if first parameter is local_ousearch_search::NONE or null)
*/
public function set_group_ids($groupids, $ornone=true) {
$this->groupids = $groupids;
$this->allownogroup = $ornone;
}
/**
* Adds exceptions to the group restriction (coursemodules in which you
* have accessallgroups permission, usually).
* @see local_ousearch_search::get_group_exceptions
* @param array $cmarray Array of course-module objects (with at least
* id,course) or null to cancel this requirement
*/
public function set_group_exceptions($cmarray) {
$this->groupexceptions = $cmarray;
}
/**
* Restricts search to a particular user.
* @param mixed $userid User ID, or 0 for any user, or
* local_ousearch_search::NONE to return only results that have no user
* @param bool $ornone If true, also returns results that have no user
* (ignored if first parameter is local_ousearch_search::NONE or 0)
*/
public function set_user_id($userid, $ornone = true) {
$this->userids = array($userid);
$this->allownouser = $ornone;
}
/**
* Restricts search to a particular set of users.
*
* @param mixed $userids Array of user IDs, or 0 for any user, or
* local_ousearch_search::NONE to return only results that have no user
* @param bool $ornone If true, also returns results that have no user
* (ignored if first parameter is local_ousearch_search::NONE or null)
*/
public function set_user_ids($userids, $ornone = true) {
if (!is_array($userids)) {
$userids = array($userids);
}
$this->userids = $userids;
$this->allownogroup = $ornone;
}
/**
* Gets restrictions for an SQL query based on search parameters (other
* than terms).
* @return array Two-element array (part of WHERE clause, parameters)
*/
private function internal_get_restrictions() {
global $DB;
$where = '';
$wherearray = array();
if ($this->courseid) {
$where .= "\nAND d.courseid = ?";
$wherearray[] = $this->courseid;
}
if ($this->plugin) {
$where .= "\nAND d.plugin = ?";
$wherearray[] = $this->plugin;
}
$cmrestrictions = false;
if ($this->coursemoduleid) {
$where .= "\nAND d.coursemoduleid = ?";
$wherearray[] = $this->coursemoduleid;
$cmrestrictions = array($this->coursemoduleid => true);
}
if ($this->cmarray) {
// The courses restriction is technically unnecessary except
// that we don't have index on coursemoduleid alone, so
// it is probably better to use course.