-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSearchAPI-Sphinxql.php
More file actions
1232 lines (1057 loc) · 39.4 KB
/
SearchAPI-Sphinxql.php
File metadata and controls
1232 lines (1057 loc) · 39.4 KB
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 2023 Simple Machines and individual contributors
* @license https://www.simplemachines.org/about/smf/license.php BSD
*
* The Following fixes a bug in SMF to show this in the settings section.
* SearchAPI-Sphinxql.php
* @version 2.1.3
*/
if (!defined('SMF'))
die('Hacking attempt...');
/**
* Our Search API class
* @package SearchAPI
*/
class sphinxql_search extends search_api
{
/**
* @var string The last version of SMF that this was tested on. Helps protect against API changes.
*/
public $version_compatible = 'SMF 2.1.99';
/**
* @var string The minimum SMF version that this will work with
*/
public $min_smf_version = 'SMF 2.1 RC4';
/**
* @var bool Whether or not it's supported
*/
public $is_supported = true;
/**
* @var array What databases support the sphinx index
*/
protected $supported_databases = array('mysql', 'mysqli');
/**
* @var string The database type we are using.
* We do not follow SMF's database abstraction here as SphinxQL is its own language and while
* similar is not 100% directly compatible with MySQL syntax.
*/
private $db_type = 'mysql';
/**
* Gets things started, figures out if this is supported and setups mysqli if needed.
*
* @access public
*/
public function __construct()
{
global $db_type, $txt, $modSettings;
loadLanguage('Admin-Sphinx');
// Is this database supported?
if (!in_array($db_type, $this->supported_databases))
{
$this->is_supported = false;
return;
}
// We sorta support mysqli at this point.
if ($db_type == 'mysqli' || (function_exists('mysqli_connect') && !function_exists('mysql_connect')))
$this->db_type = 'mysqli';
}
/**
* Check whether the search can be performed by this API.
*
* @access public
* @param string $methodName The method we would like to use.
* @param mixed $query_params The query parameters used for advanced or more defined support checking.
* @return bool true or false whether this is supported.
*/
public function supportsMethod($methodName, $query_params = null)
{
switch ($methodName)
{
case 'searchSort':
case 'prepareIndexes':
case 'indexedWordQuery':
case 'searchQuery':
case 'isValid':
return true;
break;
// We don't support these yet.
case 'topicsMoved':
case 'topicsRemoved':
case 'postRemoved':
case 'postModified':
case 'postCreated':
return false;
break;
default:
// All other methods, too bad dunno you.
return false;
return false;
}
}
public function isValid()
{
return true;
}
/**
* The Admin Search Settings calls this in order to define extra API settings.
*
* @access public
* @param array $config_vars All the configuration variables, we have to append or merge these.
*/
public static function searchSettings(&$config_vars)
{
global $txt, $scripturl, $context, $settings, $sc, $modSettings;
loadLanguage('Admin-Sphinx');
if (isset($_GET['generateConfig']))
generateSphinxConfig();
$local_config_vars = array(
array('title', 'sphinx_server_config_tittle'),
'</strong><small><em>' . $txt['sphinx_server_config_note'] . '</em></small><strong>',
array('text', 'sphinx_index_name', 65, 'default_value' => 'smf', 'subtext' => $txt['sphinx_index_name_subtext']),
array('text', 'sphinx_base_path', 65, 'default_value' => '/var/sphinx/data', 'subtext' => $txt['sphinx_base_path_subtext']),
array('text', 'sphinx_conf_path', 65, 'default_value' => '/etc/sphinxsearch', 'subtext' => $txt['sphinx_conf_path_subtext']),
array('text', 'sphinx_bin_path', 65, 'default_value' => '/usr/bin', 'subtext' => $txt['sphinx_bin_path_subtext']),
array('int', 'sphinx_indexer_mem', 6, 'default_value' => '32', 'subtext' => $txt['sphinx_indexer_mem_subtext'], 'postinput' => $txt['sphinx_indexer_mem_postinput']),
// SMF Configuration Settings.
array('title', 'sphinx_smf_sphinx_tittle'),
array('text', 'sphinx_searchd_server', 32, 'default_value' => 'localhost', 'subtext' => $txt['sphinx_searchd_server_subtext']),
array('check', 'sphinx_searchd_bind', 0, 'subtext' => $txt['sphinx_searchd_bind_subtext']),
array('int', 'sphinxql_searchd_port', 6, 'default_value' => '9306', 'subtext' => $txt['sphinxql_searchd_port_subtext']),
array('int', 'sphinx_version', 6, 'default_value' => '3.0', 'subtext' => $txt['sphinx_version_subtext']),
array('int', 'sphinx_max_results', 6, 'default_value' => '1000', 'subtext' => $txt['sphinx_max_results_subtext']),
// Just a hints section.
array('title', 'sphinx_config_hints_title'),
array('callback', 'SMFAction_Sphinx_Hints'),
);
$context['post_url'] = $scripturl . '?action=admin;area=modsettings;save;sa=sphinx';
$context['settings_title'] = $txt['sphinx_server_config_tittle'];
$context['sphinx_version'] = self::sphinxversion();
// Try to fall back.
if (empty($context['sphinx_version']) && !empty($context['sphinx_version']))
$context['sphinx_version'] = $modSettings['sphinx_version'];
else if (!empty($context['sphinx_version']) && empty($context['sphinx_version']))
$modSettings['sphinx_version'] = $context['sphinx_version'];
else
$context['sphinx_version'] = '3.0';
// Change settings for older sphinxs
if (!empty($context['sphinx_version']) && version_compare($context['sphinx_version'], '3.5', '>'))
{
$part1 = array_slice($local_config_vars, 0, 3);
$part2 = array_slice($local_config_vars, 4, 5);
$part3 = array_slice($local_config_vars, 7);
$local_config_vars = array_merge(
$part1,
array(
array('text', 'sphinx_data_path', 65, 'default_value' => '/var/sphinx/data', 'subtext' => $txt['sphinx_data_path_subtext']),
array('text', 'sphinx_log_path', 65, 'default_value' => '/var/sphinx/log', 'subtext' => $txt['sphinx_log_path_subtext']),
array('text', 'sphinx_stopword_path', 65, 'default_value' => '', 'subtext' => $txt['sphinx_stopword_path_subtext']),
),
$part2,
$part3
);
}
// Merge them in.
$config_vars = array_merge($config_vars, $local_config_vars);
// Saving?
if (isset($_GET['save']))
{
// Make sure this exists, but just push it with the other changes.
if (!isset($modSettings['sphinx_indexed_msg_until']))
$config_vars[] = array('int', 'sphinx_indexed_msg_until', 'default_value' => 1);
// We still need a port.
if (empty($_POST['sphinxql_searchd_port']))
$_POST['sphinxql_searchd_port'] = 9306;
}
// This hacks in some defaults that are needed to generate a proper configuration file.
foreach ($config_vars as $id => $cv)
if (is_array($cv) && isset($cv[1], $cv['default_value']) && !isset($modSettings[$cv[1]]))
$config_vars[$id]['value'] = $cv['default_value'];
}
/**
* Callback function for usort used to sort the fulltext results.
* the order of sorting is: large words, small words, large words that
* are excluded from the search, small words that are excluded.
*
* @access public
* @param string $a Word A
* @param string $b Word B
* @return int An integer indicating how the words should be sorted
*/
public function searchSort($a, $b)
{
global $modSettings, $excludedWords;
$x = strlen($a) - (in_array($a, $excludedWords) ? 1000 : 0);
$y = strlen($b) - (in_array($b, $excludedWords) ? 1000 : 0);
return $x < $y ? 1 : ($x > $y ? -1 : 0);
}
/**
* Callback while preparing indexes for searching
*
* @access public
* @param string $word A word to index
* @param array $wordsSearch Search words
* @param array $wordsExclude Words to exclude
* @param bool $isExcluded Whether the specfied word should be excluded
*/
public function prepareIndexes($word, array &$wordsSearch, array &$wordsExclude, $isExcluded)
{
global $modSettings;
$subwords = text2words($word, null, false);
$fulltextWord = count($subwords) === 1 ? $word : '"' . $word . '"';
$wordsSearch['indexed_words'][] = $fulltextWord;
if ($isExcluded)
$wordsExclude[] = $fulltextWord;
}
/**
* Callback for actually performing the search query
*
* @access public
* @param array $query_params An array of parameters for the query
* @param array $searchWords The words that were searched for
* @param array $excludedIndexWords Indexed words that should be excluded
* @param array $participants - Only used if we have enabled participation.
* @param array $searchArray - Builds $context['key_words'] used for highlighting
* @return mixed
- Both $participants and $searchArray are updated by reference
- $context['topics'] is populated with a id_msg => array(
'id' => id_topic
'relevance' => round(relevance / 10000, 1) . '%',
'num_matches' => A topic is specififed (ie, searching one topic only) ? $num_rows : 0,
'matches' => array(),
),
*/
public function searchQuery(array $query_params, array $searchWords, array $excludedIndexWords, array &$participants, array &$searchArray)
{
global $user_info, $context, $modSettings;
// Only request the results if they haven't been cached yet.
if (($cached_results = cache_get_data('Xsearch_results_' . md5($user_info['query_see_board'] . '_' . $context['params']))) === null)
{
// Create an instance of the sphinx client.
$mySphinx = $this->dbfunc_connect();
// Make sure we have a max results.
if (!isset($modSettings['sphinx_max_results']))
$modSettings['sphinx_max_results'] = '1000';
// Compile different options for our query
$query = 'SELECT * FROM ' . self::indexName() . '_index';
// Construct the (binary mode) query.
$where_match = $this->_constructQuery($query_params['search']);
// Nothing to search, return zero results
if (trim($where_match) == '')
return 0;
if ($query_params['subject_only'])
$where_match = '@subject ' . $where_match;
$query .= ' WHERE MATCH(\'' . $where_match . '\')';
// Set the limits based on the search parameters.
$extra_where = array();
if (!empty($query_params['min_msg_id']) || !empty($query_params['max_msg_id']))
$extra_where[] = 'id >= ' . $query_params['min_msg_id'] . ' AND id <=' . (empty($query_params['max_msg_id']) ? (int) $modSettings['maxMsgID'] : $query_params['max_msg_id']);
if (!empty($query_params['topic']))
$extra_where[] = 'id_topic = ' . (int) $query_params['topic'];
if (!empty($query_params['brd']) && is_array($query_params['brd']))
$extra_where[] = 'id_board IN (' . implode(',', $query_params['brd']) . ')';
if (!empty($query_params['memberlist']) && is_array($query_params['memberlist']))
$extra_where[] = 'id_member IN (' . implode(',', $query_params['memberlist']) . ')';
if (!empty($extra_where) && is_array($extra_where))
$query .= ' AND ' . implode(' AND ', $extra_where);
// Put together a sort string; besides the main column sort (relevance, id_topic, or num_replies), add secondary sorting based on relevance value (if not the main sort method) and age
$sphinx_sort = ($query_params['sort'] === 'id_msg' ? 'id_topic' : $query_params['sort']) . ' ' . strtoupper($query_params['sort_dir']) . ($query_params['sort'] === 'relevance' ? '' : ', relevance desc') . ', poster_time DESC';
// Grouping by topic id makes it return only one result per topic, so don't set that for in-topic searches
if (empty($query_params['topic']))
$query .= ' GROUP BY id_topic WITHIN GROUP ORDER BY ' . $sphinx_sort;
$query .= ' ORDER BY ' . $sphinx_sort;
$query .= ' LIMIT 0,' . (int) $modSettings['sphinx_max_results'];
// Any limitations we need to add?
if (!empty($modSettings['sphinx_max_results']) && (int) $modSettings['sphinx_max_results'] > 0)
$query .= ' OPTION max_matches=' . (int) $modSettings['sphinx_max_results'];
// Execute the search query.
$request = $this->dbfunc_query($query, $mySphinx);
// Can a connection to the daemon be made?
if ($request === false)
{
// Just log the error.
if ($this->dbfunc_error($mySphinx))
log_error($this->dbfunc_error($mySphinx));
fatal_lang_error('error_no_search_daemon');
}
// Get the relevant information from the search results.
$cached_results = array(
'matches' => array(),
);
$num_rows = $this->dbfunc_num_rows($request);
if ($num_rows != 0)
while($match = $this->dbfunc_fetch_assoc($request))
$cached_results['matches'][$match['id']] = array(
'id' => $match['id_topic'],
'relevance' => round($match['relevance'] / 10000, 1) . '%',
'num_matches' => empty($query_params['topic']) ? $num_rows : 0,
'matches' => array(),
);
$this->dbfunc_free_result($request);
$this->dbfunc_close($mySphinx);
$cached_results['total'] = count($cached_results['matches']);
// Store the search results in the cache.
cache_put_data('search_results_' . md5($user_info['query_see_board'] . '_' . $context['params']), $cached_results, 600);
}
$participants = array();
foreach (array_slice(array_keys($cached_results['matches']), (int) $_REQUEST['start'], $modSettings['search_results_per_page']) as $msgID)
{
$context['topics'][$msgID] = $cached_results['matches'][$msgID];
$participants[$cached_results['matches'][$msgID]['id']] = false;
}
// Sentences need to be broken up in words for proper highlighting.
$searchArray = array();
foreach ($searchWords as $orIndex => $words)
$searchArray = array_merge($searchArray, $searchWords[$orIndex]['subject_words']);
// Work around SMF bug causing multiple pages to not work right.
if (!isset($_SESSION['search_cache']['num_results']))
$_SESSION['search_cache'] = [
'num_results' => $cached_results['total']
];
return $cached_results['total'];
}
/**
* Constructs a binary mode query to pass back to sphinx
*
* @param string $string The user entered query to construct with
* @return string A binary mode query
*/
private function _constructQuery($string)
{
$keywords = array('include' => array(), 'exclude' => array());
// Split our search string and return an empty string if no matches
if (!preg_match_all('~ (-?)("[^"]+"|[^" ]+)~', ' ' . $string , $tokens, PREG_SET_ORDER))
return '';
// First we split our string into included and excluded words and phrases
$or_part = FALSE;
foreach ($tokens as $token)
{
// Strip the quotes off of a phrase
if ($token[2][0] == '"')
{
$token[2] = substr($token[2], 1, -1);
$phrase = TRUE;
}
else
$phrase = FALSE;
// Prepare this token
$cleanWords = $this->_cleanString($token[2]);
// Explode the cleanWords again incase the cleaning put more spaces into it
$addWords = $phrase ? array('"' . $cleanWords . '"') : preg_split('~ ~u', $cleanWords, -1, PREG_SPLIT_NO_EMPTY);
if ($token[1] == '-')
$keywords['exclude'] = array_merge($keywords['exclude'], $addWords);
// OR'd keywords (we only do this if we have something to OR with)
elseif (($token[2] == 'OR' || $token[2] == '|') && count($keywords['include']))
{
$last = array_pop($keywords['include']);
if (!is_array($last))
$last = array($last);
$keywords['include'][] = $last;
$or_part = TRUE;
continue;
}
// AND is implied in a Sphinx Search
elseif ($token[2] == 'AND' || $token[2] == '&')
continue;
// If this part of the query ended up being blank, skip it
elseif (trim($cleanWords) == '')
continue;
// Must be something they want to search for!
else
{
// If this was part of an OR branch, add it to the proper section
if ($or_part)
$keywords['include'][count($keywords['include']) - 1] = array_merge($keywords['include'][count($keywords['include']) - 1], $addWords);
else
$keywords['include'] = array_merge($keywords['include'], $addWords);
}
// Start fresh on this...
$or_part = FALSE;
}
// Let's make sure they're not canceling each other out
if (!count(array_diff($keywords['include'], $keywords['exclude'])))
return '';
// Now we compile our arrays into a valid search string
$query_parts = array();
foreach ($keywords['include'] as $keyword)
$query_parts[] = is_array($keyword) ? '(' . implode(' | ', $keyword) . ')' : $keyword;
foreach ($keywords['exclude'] as $keyword)
$query_parts[] = '-' . $keyword;
return implode(' ', $query_parts);
}
/**
* Cleans a string of everything but alphanumeric characters
*
* @param string $string A string to clean
* @return string A cleaned up string
*/
private function _cleanString($string)
{
global $smcFunc;
// Decode the entities first
$string = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
// Lowercase string
$string = $smcFunc['strtolower']($string);
// Fix numbers so they search easier (phone numbers, SSN, dates, etc)
$string = preg_replace('~([[:digit:]]+)\pP+(?=[[:digit:]])~u', '', $string);
// Last but not least, strip everything out that's not alphanumeric or a underscore.
$string = preg_replace('~[^\pL\pN_]+~u', ' ', $string);
return $string;
}
/**
* Callback when a post is created
* @see createPost()
*
* @access public
* @param array $msgOptions An array of post data
* @param array $topicOptions An array of topic data
* @param array $posterOptions An array of info about the person who made this post
* @return void
*/
public function postCreated(array &$msgOptions, array &$topicOptions, array &$posterOptions)
{
return true;
// !! SphinxQL Does support updating the search index from its QL interface.
// !! Sphinx for SMF does not support this at this time. Code is provided
// !! here as examples/testing purposes.
global $smcFunc, $modSettings;
// Create an instance of the sphinx client.
$mySphinx = $this->dbfunc_connect();
// Figure out our weights.
$weight_factors = array(
'age',
'length',
'first_message',
'sticky',
);
$weight = array();
$weight_total = 0;
foreach ($weight_factors as $weight_factor)
{
$weight[$weight_factor] = empty($modSettings['search_weight_' . $weight_factor]) ? 0 : (int) $modSettings['search_weight_' . $weight_factor];
$weight_total += $weight[$weight_factor];
}
if ($weight_total === 0)
{
$weight = array(
'age' => 25,
'length' => 25,
'first_message' => 25,
'sticky' => 25,
);
$weight_total = 100;
}
// The data was inserted at this point, lets get some data as the passed variables don't contain all we need.
$request = $smcFunc['db_query']('', '
SELECT
m.id_msg, m.id_topic, m.id_board, IF(m.id_member = 0, 4294967295, m.id_member) AS id_member, m.poster_time, m.body, m.subject,
t.num_replies + 1 AS num_replies,
CEILING(1000000 * (
IF(m.id_msg < 0.7 * s.value, 0, (m.id_msg - 0.7 * s.value) / (0.3 * s.value)) * {int:weight_age} +
IF(t.num_replies < 200, t.num_replies / 200, 1) * {int:weight_length} +
IF(m.id_msg = t.id_first_msg, 1, 0) * {int:weight_first_msg} +
IF(t.is_sticky = 0, 0, 1) * {int:weight_sticky}
) / {int:weight_total) AS relevance
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
WHERE m.id_msg = {int:newMessage}',
array(
'newMessage' => $msgOptions['id'],
'weight_age' => $weight['age'],
'weight_length' => $weight['length'],
'weight_first_msg' => $weight['first_message'],
'weight_sticky' => $weight['sticky'],
'weight_total' => $weight_total,
)
);
$tempMessage = $smcFunc['db_fetch_assoc']($request);
$smcFunc['db_free_result']($request);
$insertValues = array(
'id_msg' => $tempMessage['id_msg'],
'id_topic' => $tempMessage['id_topic'],
'id_board' => $tempMessage['id_board'],
'id_member' => $tempMessage['id_member'],
'poster_time' => $tempMessage['poster_time'],
'body' => '"' . $tempMessage['body'] . '"',
'subject' => '"' . $tempMessage['subject'] . '"',
'num_replies' => $tempMessage['num_replies'],
'relevance' => $tempMessage['relevance'],
);
// The insert query, use replace to make sure we don't get duplicates.
$query = '
REPLACE INTO ' . self::indexName() . '_index (' . implode(', ', array_keys($insertValues)) . ')
VALUES (' . implode(', ', array_values($insertValues)) . ')';
// Execute the search query.
$request = $this->dbfunc_query($query, $mySphinx);
// Can a connection to the daemon be made?
if ($request === false)
{
// Just log the error.
if ($this->dbfunc_error($mySphinx))
log_error($this->dbfunc_error($mySphinx));
// Silently bail out, We can let the reindex cron take care of fixing this.
return true;
}
return true;
}
/**
* Callback when a post is modified
* @see modifyPost()
*
* @access public
* @param array $msgOptions An array of post data
* @param array $topicOptions An array of topic data
* @param array $posterOptions An array of info about the person who made this post
* @return void
*/
public function postModified(array &$msgOptions, array &$topicOptions, array &$posterOptions)
{
return true;
// !! SphinxQL Does support updating the search index from its QL interface.
// !! Sphinx for SMF does not support this at this time. Code is provided
// !! here as examples/testing purposes.
// Just call the postCreated as it does a replace.
$this->postCreated($msgOptions, $topicOptions, $posterOptions);
}
/**
* Callback when a post is removed, not recycled.
*
* @access public
* @param int $id_msg The ID of the post that was removed
* @return void
*/
public function postRemoved($id_msg)
{
return true;
// !! SphinxQL Does support updating the search index from its QL interface.
// !! Sphinx for SMF does not support this at this time. Code is provided
// !! here as examples/testing purposes.
global $smcFunc, $modSettings;
// Create an instance of the sphinx client.
$mySphinx = $this->dbfunc_connect();
// SMF only calls this search API when we delete, not recycle. So this will always be a remove.
$query = '
DELETE FROM ' . self::indexName() . '_index
WHERE id_msg = ' . $id_msg;
// Execute the search query.
$request = $this->dbfunc_query($query, $mySphinx);
// Can a connection to the daemon be made?
if ($request === false)
{
// Just log the error.
if ($this->dbfunc_error($mySphinx))
log_error($this->dbfunc_error($mySphinx));
// Silently bail out, We can let the reindex cron take care of fixing this.
return true;
}
return true;
}
/**
* Callback when a topic is removed
*
* @access public
* @param array $topics The ID(s) of the removed topic(s)
* @return void
*/
public function topicsRemoved(array $topics)
{
return true;
// !! SphinxQL Does support updating the search index from its QL interface.
// !! Sphinx for SMF does not support this at this time. Code is provided
// !! here as examples/testing purposes.
global $smcFunc, $modSettings;
// Create an instance of the sphinx client.
$mySphinx = $this->dbfunc_connect();
// SMF only calls this search API when we delete, not recycle. So this will always be a remove.
$query = '
DELETE FROM ' . self::indexName() . '_index
WHERE id_topic IN (' . implode(', ', $topics) . ')';
// Execute the search query.
$request = $this->dbfunc_query($query, $mySphinx);
// Can a connection to the daemon be made?
if ($request === false)
{
// Just log the error.
if ($this->dbfunc_error($mySphinx))
log_error($this->dbfunc_error($mySphinx));
// Silently bail out, We can let the reindex cron take care of fixing this.
return true;
}
return true;
}
/**
* Callback when a topic is moved
*
* @access public
* @param array $topics The ID(s) of the moved topic(s)
* @param int $board_to The board that the topics were moved to
* @return void
*/
public function topicsMoved(array $topics, $board_to)
{
return true;
// !! SphinxQL Does support updating the search index from its QL interface.
// !! Sphinx for SMF does not support this at this time. Code is provided
// !! here as examples/testing purposes.
global $smcFunc, $modSettings;
// Create an instance of the sphinx client.
$mySphinx = $this->dbfunc_connect();
// SMF only calls this search API when we delete, not recycle. So this will always be a remove.
$query = '
UPDATE ' . self::indexName() . '_index
SET id_board = ' . $board_to . '
WHERE id_topic IN (' . implode(', ', $topics) . ')';
// Execute the search query.
$request = $this->dbfunc_query($query, $mySphinx);
// Can a connection to the daemon be made?
if ($request === false)
{
// Just log the error.
if ($this->dbfunc_error($mySphinx))
log_error($this->dbfunc_error($mySphinx));
// Silently bail out, We can let the reindex cron take care of fixing this.
return true;
}
return true;
}
/**
* Sphinx Database Support API: connect
*
* @access private
* @param string $host The sphinx search address, this will default to $modSettings['sphinx_searchd_server'].
* @param string $port The port Sphinx runs on, this will default to $modSettings['sphinxql_searchd_port'].
* @return resource
*/
private function dbfunc_connect(string $host = '', string $port = '')
{
global $modSettings, $txt;
// Fill out our host and port if needed.
if (empty($host))
$host = $modSettings['sphinx_searchd_server'] == 'localhost' ? '127.0.0.1' : $modSettings['sphinx_searchd_server'];
if (empty($port))
$port = empty($modSettings['sphinxql_searchd_port']) ? 9306 : (int) $modSettings['sphinxql_searchd_port'];
if ($this->db_type == 'mysqli')
{
$mySphinx = @mysqli_connect($host, '', '', '', $port);
// Mysqli is never a resource, but an object.
if (!is_object($mySphinx) || $mySphinx->connect_errno > 0)
{
loadLanguage('Errors');
fatal_error($txt['error_no_search_daemon']);
}
}
else
{
// I tried to do this properly by changing error_reporting, but PHP ignores that. So surpress!
$mySphinx = @mysql_connect($host . ':' . $port);
if (!is_resource($mySphinx))
{
loadLanguage('Errors');
fatal_error($txt['error_no_search_daemon']);
}
}
return $mySphinx;
}
/**
* Sphinx Database Support API: query
*
* @access private
* @param string $query The query to run.
* @param resource $mySphinx A SphinxQL connection resource.
* @return resource
*/
private function dbfunc_query(string $query, $mySphinx)
{
// MySQLI Procedural Style has the resource first then the query.
if ($this->db_type == 'mysqli')
return mysqli_query($mySphinx, $query);
else
return mysql_query($query, $mySphinx);
}
/**
* Sphinx Database Support API: num_rows
*
* @access private
* @param resource $mySphinx A SphinxQL request resource.
* @return int|string
*/
private function dbfunc_num_rows($mySphinx)
{
if ($this->db_type == 'mysqli')
return mysqli_num_rows($mySphinx);
else
return mysql_num_rows($mySphinx);
}
/**
* Sphinx Database Support API: fetch_assoc
*
* @access private
* @param resource $mySphinx A SphinxQL request resource.
* @return array
*/
private function dbfunc_fetch_assoc($mySphinx)
{
if ($this->db_type == 'mysqli')
return mysqli_fetch_assoc($mySphinx);
else
return mysql_fetch_assoc($mySphinx);
}
/**
* Sphinx Database Support API: free_result
*
* @access private
* @param resource $mySphinx A SphinxQL request resource.
* @return void
*/
private function dbfunc_free_result($mySphinx)
{
if ($this->db_type == 'mysqli')
return mysqli_free_result($mySphinx);
else
return mysql_free_result($mySphinx);
}
/**
* Sphinx Database Support API: free_result
*
* @access private
* @param resource $mySphinx A SphinxQL connection resource.
* @return bool
*/
private function dbfunc_close($mySphinx)
{
if ($this->db_type == 'mysqli')
return mysqli_close($mySphinx);
else
return mysql_close($mySphinx);
}
/**
* Sphinx Database Support API: error
*
* @access private
* @param resource $mySphinx A SphinxQL connection resource.
* @return string
*/
private function dbfunc_error($mySphinx)
{
if ($this->db_type == 'mysqli')
return mysqli_error($mySphinx);
else
return mysql_error($mySphinx);
}
/**
* Sphinx Version
*
* @access private
* @return decimal The Major + minor version of Sphinx.
*/
private static function sphinxversion()
{
global $modSettings;
if (empty($modSettings['sphinx_bin_path']))
$modSettings['sphinx_bin_path'] = '/usr/bin';
// Try to safely check for the indexer file, but do this in a way we can catch the error so PHP doesn't output it.
try {
set_error_handler(static function ($severity, $message, $file, $line) {
throw new \ErrorException($message, 0, $severity, $file, $line);
});
if (!file_exists(realpath($modSettings['sphinx_bin_path'] . '/indexer')))
return;
} catch (\Throwable $e) {
return;
} finally {
restore_error_handler();
}
$binary = realpath($modSettings['sphinx_bin_path'] . '/indexer');
$raw_version = shell_exec($binary . ' -v');
if (empty($raw_version))
return;
preg_match('~Sphinx (\d+)\.(\d+)~i', $raw_version, $m);
// No version?
if (empty($m) || empty($m[1]) || empty($m[2]))
return;
return $m[1] . '.' . $m[2];
}
/**
* Index name
*
* @access private
* @return string The name of the idnex.
*/
private static function indexName()
{
global $modSettings;
return !empty($modSettings['sphinx_index_name']) ? $modSettings['sphinx_index_name'] : 'smf';
}
}
/**
* Callback to a template from our admin search settings page.
* This is used to generate hints and links to generate the Sphinx
* configuration file.
*
* @access public
*/
function template_callback_SMFAction_Sphinx_Hints()
{
global $db_type, $scripturl, $txt, $modSettings;
if (!isset($modSettings['sphinx_data_path'], $modSettings['sphinx_log_path']))
{
echo '
<dt></dt>
<dd>', $txt['sphinx_config_hints_save'], '</dd>';
return;
}
// Ensure these exist.
$index_name = !empty($modSettings['sphinx_index_name']) ? $modSettings['sphinx_index_name'] : 'smf';
if (empty($modSettings['sphinx_conf_path']))
$modSettings['sphinx_conf_path'] = '/etc/sphinxsearch';
if (empty($modSettings['sphinx_bin_path']))
$modSettings['sphinx_bin_path'] = '/usr/bin';
echo '
<dt></dt>
<dd><a href="', $scripturl, '?action=admin;area=managesearch;sa=weights">', $txt['search_weights'], '</a></dd>
<dd>[<a href="', $scripturl, '?action=admin;area=managesearch;sa=settings;generateConfig;view" target="_blank">', $txt['sphinx_view_config'], '</a> | <a href="', $scripturl, '?action=admin;area=managesearch;sa=settings;generateConfig">', $txt['sphinx_download_config'], '</a>] (', $txt['sphinx_config_hints_save'], ')</dd>
</dl>';
$message = '
' . sprintf($txt['sphinx_config_hints_desc'], $modSettings['sphinx_data_path']) . '[pre]mkdir -p ' . $modSettings['sphinx_data_path'] . '
chmod a+w ' . $modSettings['sphinx_data_path'];
if (!empty($context['sphinx_version']) && version_compare($context['sphinx_version'], '3.5', '>'))
$message .= '
mkdir -p ' . $modSettings['sphinx_log_path'] . '
chmod a+w ' . $modSettings['sphinx_log_path'] . '[/pre]';
// Add a extra step for postgresql.
if ($db_type == 'postgresql')
$message .= '
[hr]
' . $txt['sphinx_config_hints_pgsql_func'] . '
[code]
CREATE FUNCTION update_settings(var TEXT, val INT) RETURNS VOID AS $$
BEGIN
LOOP
-- first try to update the key
UPDATE PREFIX_settings SET value = val WHERE variable = var;
IF found THEN
RETURN;
END IF;
-- not there so try to insert the key
BEGIN
INSERT INTO PREFIX_settings(variable,value) VALUES (var,val);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- do nothing, loop again to try the UPDATE
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;[/code]';
$message .= '
[hr]
' . $txt['sphinx_config_hints_index_start'] . '[pre]' . $modSettings['sphinx_bin_path'] . '/indexer --config ' . $modSettings['sphinx_conf_path'] . '/sphinx.conf --all
' . $modSettings['sphinx_bin_path'] . '/searchd --config ' . $modSettings['sphinx_conf_path'] . '/sphinx.conf[/pre]
' . $txt['sphinx_config_hints_index_finish'] . '
[hr]