-
Notifications
You must be signed in to change notification settings - Fork 255
/
Copy pathSearchApi.php
2356 lines (1986 loc) · 68.8 KB
/
SearchApi.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
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines https://www.simplemachines.org
* @copyright 2024 Simple Machines and individual contributors
* @license https://www.simplemachines.org/about/smf/license.php BSD
*
* @version 3.0 Alpha 2
*/
declare(strict_types=1);
namespace SMF\Search;
use SMF\Actions\Search;
use SMF\BackwardCompatibility;
use SMF\BBCodeParser;
use SMF\Config;
use SMF\Db\DatabaseApi as Db;
use SMF\ErrorHandler;
use SMF\IntegrationHook;
use SMF\Lang;
use SMF\PackageManager\SubsPackage;
use SMF\User;
use SMF\Utils;
/**
* Class SearchApi
*/
abstract class SearchApi implements SearchApiInterface
{
use BackwardCompatibility;
/**
* @var array
*
* BackwardCompatibility settings for this class.
*/
private static $backcompat = [
'prop_names' => [
'loadedApi' => 'searchAPI',
],
];
/*****************
* Class constants
*****************/
// This is the hard coded maximum search string length.
public const MAX_LENGTH = 100;
/*******************
* Public properties
*******************/
/**
* @var string
*
* The maximum SMF version that this will work with.
*/
public string $version_compatible = '3.0.999';
/**
* @var string
*
* The minimum SMF version that this will work with.
*/
public string $min_smf_version = '3.0 Alpha 1';
/**
* @var bool
*
* Whether or not it's supported.
*/
public bool $is_supported = true;
/**
* @var string
*
* The status of this API's index.
*
* Either 'exists', 'partial', or 'none'.
*/
public string $status;
/**
* @var float
*
* Used to calculate relevance.
* Specifically, controls the weight assigned for how recent the post is.
*/
public float $recentPercentage = 0.30;
/**
* @var int
*
* Used to calculate relevance.
* Specifically, caps the weight assigned to huge topics so that they do
* not completely overwhelm the search results.
*/
public int $humungousTopicPosts = 200;
/**
* @var int
*
* If more than this many users match the 'userspec' param, don't bother
* searching by name at all.
*/
public int $maxMembersToSearch = 500;
/**
* @var int
*
* Upper limit when performing an indexedWordQuery().
* Zero for no limit.
*/
public int $maxMessageResults = 0;
/**
* @var array
*
* Words to ignore when searching.
*
* Populated with the contents of:
* - Lang::$txt['search_stopwords']
* - Config::$modSettings['search_stopwords']
* - Config::$modSettings['search_stopwords_custom']
* - All known BBCode tags
*/
public array $blacklisted_words = [];
/**
* @var array
*
* Names of columns that results can be sorted by.
*/
public array $sort_columns = [
'relevance',
'num_replies',
'id_msg',
];
/**
* @var array
*
* The supplied search parameters.
* Any unsupplied values will be set to the values in self::$default_params.
*/
public array $params = [];
/**
* @var string
*
* URL-safe variant of a Base64 string representation of $this->params.
* The encoded string only includes values where $this->params differs from
* the defaults.
*/
public string $compressed_params;
/**
* @var array
*
* Records errors encountered while preparing to search.
*/
public array $errors = [];
/**
* @var array
*
* User-supplied search terms that we have chosen to ignore.
*/
public array $ignored = [];
/**
* @var array
*
* Array of replacements for highlighting.
*/
public array $marked = [];
/**
* @var array
*
* The list of terms to search for.
*/
public array $searchArray = [];
/**
* @var array
*
* Structured list of search term data.
*/
public array $searchWords = [];
/**
* @var array
*
* Terms that the user wants to exclude from the search.
*/
public array $excludedWords = [];
/**
* @var array
*
* Terms to exclude when building a search index.
*/
public array $excludedIndexWords = [];
/**
* @var array
*
* Terms to exclude from a subject search.
*/
public array $excludedSubjectWords = [];
/**
* @var array
*
* Phrases to exclude from the search.
*/
public array $excludedPhrases = [];
/**
* @var array
*
* The results of the search.
* Keys are message IDs, values are arrays of relevance data.
*/
public array $results = [];
/**
* @var array
*
* Info about who participated in the search result's topic.
* Keys are topic IDs, values are booleans about whether the current user
* has posted anything in that topic.
*/
public array $participants = [];
/**************************
* Public static properties
**************************/
/**
* @var object
*
* The loaded search API.
*
* For backward compatibility, also referenced as global $searchAPI.
*/
public static $loadedApi;
/**
* @var array
*
* Default values for $this->params.
*/
public static array $default_params = [
'advanced' => false,
'brd' => [],
'maxage' => 9999,
'minage' => 0,
'search' => '',
'searchtype' => 1,
'show_complete' => false,
'sort' => null,
'sort_dir' => null,
'subject_only' => false,
'topic' => '',
'userspec' => '',
];
/**
* @var array
*
* Info about how to weigh different factors when searching for relevant
* results.
*/
public static array $weight_factors = [
'frequency' => [
'search' => 'COUNT(*) / (MAX(t.num_replies) + 1)',
'results' => '(t.num_replies + 1)',
],
'age' => [
'search' => 'CASE WHEN MAX(m.id_msg) < {int:min_msg} THEN 0 ELSE (MAX(m.id_msg) - {int:min_msg}) / {int:recent_message} END',
'results' => 'CASE WHEN t.id_first_msg < {int:min_msg} THEN 0 ELSE (t.id_first_msg - {int:min_msg}) / {int:recent_message} END',
],
'length' => [
'search' => 'CASE WHEN MAX(t.num_replies) < {int:huge_topic_posts} THEN MAX(t.num_replies) / {int:huge_topic_posts} ELSE 1 END',
'results' => 'CASE WHEN t.num_replies < {int:huge_topic_posts} THEN t.num_replies / {int:huge_topic_posts} ELSE 1 END',
],
'subject' => [
'search' => 0,
'results' => 0,
],
'first_message' => [
'search' => 'CASE WHEN MIN(m.id_msg) = MAX(t.id_first_msg) THEN 1 ELSE 0 END',
],
'sticky' => [
'search' => 'MAX(t.is_sticky)',
'results' => 't.is_sticky',
],
];
/*********************
* Internal properties
*********************/
/**
* @var array
*
* Calculated weight factors.
*/
protected array $weight = [];
/**
* @var int
*
* Weight factor total.
* Used to ensure that calculated factors are given the correct percentage.
*/
protected int $weight_total = 0;
/**
* @var int
*
* Messages with IDs less than this will be ignored in the search.
*/
protected int $minMsgID = 0;
/**
* @var int
*
* Messages with IDs greater than this will be ignored in the search.
*/
protected int $maxMsgID = 0;
/**
* @var int
*
* Messages with IDs less than this will get a 0 for the age weight factor.
*/
protected int $ageMinMsg = 0;
/**
* @var int
*
* ID of the most recent message considered for the age weight factor.
*/
protected int $ageRecentMsg = 0;
/**
* @var array
*
* IDs of members to filter our results by.
*/
protected array $memberlist = [];
/**
* @var string
*
* SQL query string to filter results by author.
*/
protected string $userQuery = '';
/**
* @var string
*
* SQL query string to filter results by board.
*/
protected string $boardQuery = '';
/**
* @var string
*
* The SQL match function to use.
* If 'RLIKE', search will be performed using regular expressions.
* If 'LIKE', search will be performed using simple string matching.
*/
protected string $query_match_type = 'LIKE';
/****************
* Public methods
****************/
/**
* Constructor.
*/
public function __construct()
{
$this->maxMessageResults = empty(Config::$modSettings['search_max_results']) ? 0 : Config::$modSettings['search_max_results'] * 5;
}
/**
* {@inheritDoc}
*/
public function supportsMethod(string $methodName, array $query_params = []): bool
{
switch ($methodName) {
case 'postRemoved':
case 'initializeSearch':
case 'searchQuery':
case 'setParticipants':
case 'compressParams':
case 'getQueryParams':
return true;
// All other methods, too bad dunno you.
default:
return false;
}
}
/**
* {@inheritDoc}
*/
public function isValid(): bool
{
return false;
}
/**
* {@inheritDoc}
*/
public function getSize(): int
{
return 0;
}
/**
* {@inheritDoc}
*/
public function getStatus(): ?string
{
return null;
}
/**
* {@inheritDoc}
*/
public function searchSort(string $a, string $b): int
{
return 0;
}
/**
* {@inheritDoc}
*/
public function prepareIndexes(string $word, array &$wordsSearch, array &$wordsExclude, bool $isExcluded): void
{
}
/**
* {@inheritDoc}
*/
public function indexedWordQuery(array $words, array $search_data): mixed
{
return null;
}
/**
* {@inheritDoc}
*/
public function postCreated(array &$msgOptions, array &$topicOptions, array &$posterOptions): void
{
}
/**
* {@inheritDoc}
*/
public function postModified(array &$msgOptions, array &$topicOptions, array &$posterOptions): void
{
}
/**
* {@inheritDoc}
*/
public function postRemoved(int $id_msg): void
{
$result = Db::$db->query(
'',
'SELECT DISTINCT id_search
FROM {db_prefix}log_search_results
WHERE id_msg = {int:id_msg}',
[
'id_msg' => $id_msg,
],
);
$id_searchs = [];
while ($row = Db::$db->fetch_assoc($result)) {
$id_searchs[] = $row['id_search'];
}
if (count($id_searchs) < 1) {
return;
}
Db::$db->query(
'',
'DELETE FROM {db_prefix}log_search_results
WHERE id_search in ({array_int:id_searchs})',
[
'id_searchs' => $id_searchs,
],
);
Db::$db->query(
'',
'DELETE FROM {db_prefix}log_search_topics
WHERE id_search in ({array_int:id_searchs})',
[
'id_searchs' => $id_searchs,
],
);
Db::$db->query(
'',
'DELETE FROM {db_prefix}log_search_messages
WHERE id_search in ({array_int:id_searchs})',
[
'id_searchs' => $id_searchs,
],
);
}
/**
* {@inheritDoc}
*/
public function topicsRemoved(array $topics): void
{
}
/**
* {@inheritDoc}
*/
public function topicMerge(int $id_topic, array $topics, array $affected_msgs, ?string $subject): void
{
}
/**
* {@inheritDoc}
*/
public function topicSplit(int $id_topic, array $affected_msgs): void
{
}
/**
* {@inheritDoc}
*/
public function topicsMoved(array $topics, int $board_to): void
{
}
/**
* {@inheritDoc}
*/
public function formContext(): void
{
}
/**
* {@inheritDoc}
*/
public function resultsContext(): void
{
}
/**
* {@inheritDoc}
*/
public function initializeSearch(): void
{
$this->calculateWeight();
$this->setParams();
$this->setBlacklistedWords();
$this->setSearchTerms();
}
/**
* {@inheritDoc}
*/
public function searchQuery(array $query_params, array $searchWords, array $excludedIndexWords, array &$participants, array &$searchArray): void
{
$update_cache = empty($_SESSION['search_cache']) || ($_SESSION['search_cache']['params'] != $this->compressParams());
// Are the results fresh?
if (!$update_cache && !empty($_SESSION['search_cache']['id_search'])) {
$request = Db::$db->query(
'',
'SELECT id_search
FROM {db_prefix}log_search_results
WHERE id_search = {int:search_id}
LIMIT 1',
[
'search_id' => $_SESSION['search_cache']['id_search'],
],
);
if (Db::$db->num_rows($request) === 0) {
$update_cache = true;
}
}
if ($update_cache) {
// Increase the pointer...
Config::$modSettings['search_pointer'] = empty(Config::$modSettings['search_pointer']) ? 0 : (int) Config::$modSettings['search_pointer'];
// ...and store it right off.
Config::updateModSettings(['search_pointer' => Config::$modSettings['search_pointer'] >= 255 ? 0 : Config::$modSettings['search_pointer'] + 1]);
// As long as you don't change the parameters, the cache result is yours.
$_SESSION['search_cache'] = [
'id_search' => Config::$modSettings['search_pointer'],
'num_results' => -1,
'params' => $this->compressParams(),
];
// Clear the previous cache of the final results cache.
Db::$db->search_query(
'delete_log_search_results',
'
DELETE FROM {db_prefix}log_search_results
WHERE id_search = {int:search_id}',
[
'search_id' => $_SESSION['search_cache']['id_search'],
],
);
if ($this->params['subject_only']) {
$this->searchSubjectOnly();
} else {
$this->searchSubjectAndMessage();
}
}
$approve_query = '';
if (!empty(Config::$modSettings['postmod_active'])) {
// Exclude unapproved topics, but show ones they started.
if (empty(User::$me->mod_cache['ap'])) {
$approve_query = '
AND (t.approved = {int:is_approved} OR t.id_member_started = {int:current_member})';
}
// Show unapproved topics in boards they have access to.
elseif (User::$me->mod_cache['ap'] !== [0]) {
$approve_query = '
AND (t.approved = {int:is_approved} OR t.id_member_started = {int:current_member} OR t.id_board IN ({array_int:approve_boards}))';
}
}
// *** Retrieve the results to be shown on the page
$request = Db::$db->search_query(
'',
'
SELECT ' . (empty($this->params['topic']) ? 'lsr.id_topic' : $this->params['topic'] . ' AS id_topic') . ', lsr.id_msg, lsr.relevance, lsr.num_matches
FROM {db_prefix}log_search_results AS lsr' . ($this->params['sort'] == 'num_replies' || !empty($approve_query) ? '
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = lsr.id_topic)' : '') . '
WHERE lsr.id_search = {int:id_search}' . $approve_query . '
ORDER BY {raw:sort} {raw:sort_dir}
LIMIT {int:start}, {int:max}',
[
'id_search' => $_SESSION['search_cache']['id_search'],
'sort' => $this->params['sort'],
'sort_dir' => $this->params['sort_dir'],
'start' => $_REQUEST['start'],
'max' => Config::$modSettings['search_results_per_page'],
'is_approved' => 1,
'current_member' => User::$me->id,
'approve_boards' => !empty(Config::$modSettings['postmod_active']) ? User::$me->mod_cache['ap'] : [],
],
);
while ($row = Db::$db->fetch_assoc($request)) {
$this->results[$row['id_msg']] = [
'relevance' => round($row['relevance'] / 10, 1) . '%',
'num_matches' => $row['num_matches'],
'matches' => [],
];
// By default they didn't participate in the topic!
$this->participants[$row['id_topic']] = false;
}
Db::$db->free_result($request);
// Just for the sake of backward compatibility...
$participants = $this->participants;
$searchArray = $this->searchArray;
}
/**
* {@inheritDoc}
*/
public function setParticipants(): void
{
// If we want to know who participated in what then load this now.
if (!empty(Config::$modSettings['enableParticipation']) && !User::$me->is_guest) {
$result = Db::$db->query(
'',
'SELECT id_topic
FROM {db_prefix}messages
WHERE id_topic IN ({array_int:topic_list})
AND id_member = {int:current_member}
GROUP BY id_topic
LIMIT {int:limit}',
[
'current_member' => User::$me->id,
'topic_list' => array_keys($this->participants),
'limit' => count($this->participants),
],
);
while ($row = Db::$db->fetch_assoc($result)) {
$this->participants[$row['id_topic']] = true;
}
Db::$db->free_result($result);
}
}
/**
* {@inheritDoc}
*/
public function compressParams(): string
{
if (isset($this->compressed_params)) {
return $this->compressed_params;
}
$temp_params = $this->params;
foreach ($temp_params as $key => $value) {
if ($temp_params[$key] === self::$default_params[$key]) {
unset($temp_params[$key]);
}
}
if (isset($temp_params['brd'])) {
$temp_params['brd'] = implode(',', $temp_params['brd']);
}
if (!empty($temp_params)) {
foreach ($temp_params as $k => $v) {
$temp_params[$k] = $k . '|\'|' . $v;
}
$temp_params = implode('|"|', $temp_params);
// Due to old IE's 2083 character limit, we try to compress long search strings
if (($compressed = @gzcompress($temp_params)) !== false) {
$temp_params = $compressed;
}
// Base64 encode, then replace +/= with URI safe ones that can be reverted.
$this->compressed_params = str_replace(['+', '/', '='], ['-', '_', '.'], base64_encode($temp_params));
} else {
$this->compressed_params = '';
}
return $this->compressed_params;
}
/**
* Returns a copy of $this->params with a few extra pieces of data added in.
*
* This exists only for the sake of backward compatibility; mods extending
* this class can already access the included data directly.
*
* @return array Data about this search query.
*/
public function getQueryParams(): array
{
return array_merge($this->params, [
'min_msg_id' => $this->minMsgID,
'max_msg_id' => $this->maxMsgID,
'memberlist' => $this->memberlist,
]);
}
/**
* {@inheritDoc}
*/
public function getAdminSubactions(): array
{
return [];
}
/**
* {@inheritDoc}
*/
public function getLabel(): string
{
return 'search_index_' . strtolower(substr(strrchr(get_class($this), '\\'), 1));
}
/**
* {@inheritDoc}
*/
public function getDescription(): string
{
return 'search_index_' . strtolower(substr(strrchr(get_class($this), '\\'), 1)) . '_desc';
}
/***********************
* Public static methods
***********************/
/**
* Creates a search API and returns the object.
*
* @return \SMF\Search\SearchApiInterface An instance of the search API interface.
*/
final public static function load(): object
{
// Load up the search API we are going to use.
Config::$modSettings['search_index'] = empty(Config::$modSettings['search_index']) ? 'standard' : Config::$modSettings['search_index'];
$search_class_name = __NAMESPACE__ . '\\APIs\\' . ucwords(Config::$modSettings['search_index']);
if (!class_exists($search_class_name)) {
ErrorHandler::fatalLang('search_api_missing');
}
// Create an instance of the search API and check it is valid for this version of SMF.
self::$loadedApi = new $search_class_name();
// An invalid Search API.
if (
!self::$loadedApi
|| !(self::$loadedApi instanceof SearchApiInterface)
|| (self::$loadedApi->supportsMethod('isValid') && !self::$loadedApi->isValid())
|| !SubsPackage::matchPackageVersion(SMF_VERSION, self::$loadedApi->min_smf_version . '-' . self::$loadedApi->version_compatible)
) {
// Log the error.
Lang::load('Errors');
ErrorHandler::log(Lang::getTxt('search_api_not_compatible', ['Search/APIs/' . ucwords(Config::$modSettings['search_index']) . '.php']), 'critical');
// Fall back to standard search.
if (Config::$modSettings['search_index'] !== 'standard') {
Config::$modSettings['search_index'] = 'standard';
self::load();
}
// This should never happen, but...
else {
self::$loadedApi = false;
}
}
return self::$loadedApi;
}
/**
* Get the installed Search API implementations.
*
* @return array Info about the detected search APIs.
*/
final public static function detect(): array
{
$loadedApis = [];
$api_classes = new \GlobIterator(__DIR__ . '/APIs/*.php', \FilesystemIterator::NEW_CURRENT_AND_KEY);
foreach ($api_classes as $file_path => $file_info) {
$class_name = $file_info->getBasename('.php');
$index_name = strtolower($class_name);
$fully_qualified_class_name = __NAMESPACE__ . '\\APIs\\' . $class_name;
if (!class_exists($fully_qualified_class_name)) {
continue;
}
$search_api = new $fully_qualified_class_name();
if (!($search_api instanceof SearchApiInterface) || !($search_api instanceof SearchApi)) {
continue;
}
if (!$search_api->is_supported) {
continue;
}
$loadedApis[$index_name] = [
'filename' => 'Search/APIs/' . $file_info->getBasename(),
'class' => $fully_qualified_class_name,
'setting_index' => $index_name,
'has_template' => $index_name === 'standard',
'label' => $search_api->getLabel(),
'desc' => $search_api->getDescription(),
'instance' => $search_api,
];
}
// Check for search APIs using the old SearchAPI-*.php system.
// Kept for backward compatibility.
$source_files = new \GlobIterator(Config::$sourcedir . '/SearchAPI-*.php', \FilesystemIterator::NEW_CURRENT_AND_KEY);
foreach ($source_files as $file_path => $file_info) {
// Skip if not a file.
if (!$file_info->isFile()) {
continue;
}
// Skip if file name doesn't match.
if (!preg_match('~^SearchAPI-([A-Za-z\d_]+)\.php$~', $file_info->getFilename(), $matches)) {
continue;
}
$index_name = strtolower($matches[1]);
$class_name = $index_name . '_search';
// Skip if we already have an API by this name.
if (isset($loadedApis[$index_name])) {
continue;
}
// Check this is definitely a valid API.
$fp = fopen($file_info->getPathname(), 'rb');
$header = fread($fp, 4096);
fclose($fp);
if (!str_contains($header, '* SearchAPI-' . $matches[1] . '.php')) {
continue;
}
require_once $file_info->getPathname();
if (!class_exists($class_name, false)) {
continue;
}
$search_api = new $class_name();
if (!($search_api instanceof SearchApiInterface) || !($search_api instanceof SearchApi)) {
continue;
}
if (!$search_api->is_supported) {
continue;
}
$loadedApis[$index_name] = [
'filename' => $file_info->getFilename(),
'class' => $class_name,
'setting_index' => $index_name,
'has_template' => $index_name === 'standard',
'label' => $search_api->getLabel(),
'desc' => $search_api->getDescription(),
'instance' => $search_api,
];
}
IntegrationHook::call('integrate_load_search_apis', [&$loadedApis]);
// Always list standard and fulltext first.
uksort(
$loadedApis,
function ($a, $b) {
$a = strtr($a, ['standard' => '0', 'fulltext' => 1]);
$b = strtr($b, ['standard' => '0', 'fulltext' => 1]);
return $a <=> $b;
},
);
return $loadedApis;
}
/******************
* Internal methods
******************/
/**
* Calculates the weight values to use when organizing results by relevance.
*/
protected function calculateWeight(): void
{
IntegrationHook::call('integrate_search_weights', [&self::$weight_factors]);
foreach (self::$weight_factors as $weight_factor => $value) {
$this->weight[$weight_factor] = empty(Config::$modSettings['search_weight_' . $weight_factor]) ? 0 : (int) Config::$modSettings['search_weight_' . $weight_factor];
$this->weight_total += $this->weight[$weight_factor];
}
// Zero weight. Weightless :P.
if (empty($this->weight_total)) {
ErrorHandler::fatalLang('search_invalid_weights');
}
}
/**
* Allows changing $this->blacklisted_words.
*/
protected function setBlacklistedWords(): void
{
// Blacklist any stopwords for the current language.