-
Notifications
You must be signed in to change notification settings - Fork 3
/
sphinxapi.php
1829 lines (1574 loc) · 50.4 KB
/
sphinxapi.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
//
// $Id$
//
//
// Copyright (c) 2001-2013, Andrew Aksyonoff
// Copyright (c) 2008-2013, Sphinx Technologies Inc
// All rights reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License. You should have
// received a copy of the GPL license along with this program; if you
// did not, you can find it at http://www.gnu.org/
//
/////////////////////////////////////////////////////////////////////////////
// PHP version of Sphinx searchd client (PHP API)
/////////////////////////////////////////////////////////////////////////////
/// known searchd commands
define ( "SEARCHD_COMMAND_SEARCH", 0 );
define ( "SEARCHD_COMMAND_EXCERPT", 1 );
define ( "SEARCHD_COMMAND_UPDATE", 2 );
define ( "SEARCHD_COMMAND_KEYWORDS", 3 );
define ( "SEARCHD_COMMAND_PERSIST", 4 );
define ( "SEARCHD_COMMAND_STATUS", 5 );
define ( "SEARCHD_COMMAND_FLUSHATTRS", 7 );
/// current client-side command implementation versions
define ( "VER_COMMAND_SEARCH", 0x11E );
define ( "VER_COMMAND_EXCERPT", 0x104 );
define ( "VER_COMMAND_UPDATE", 0x103 );
define ( "VER_COMMAND_KEYWORDS", 0x100 );
define ( "VER_COMMAND_STATUS", 0x101 );
define ( "VER_COMMAND_QUERY", 0x100 );
define ( "VER_COMMAND_FLUSHATTRS", 0x100 );
/// known searchd status codes
define ( "SEARCHD_OK", 0 );
define ( "SEARCHD_ERROR", 1 );
define ( "SEARCHD_RETRY", 2 );
define ( "SEARCHD_WARNING", 3 );
/// known match modes
define ( "SPH_MATCH_ALL", 0 );
define ( "SPH_MATCH_ANY", 1 );
define ( "SPH_MATCH_PHRASE", 2 );
define ( "SPH_MATCH_BOOLEAN", 3 );
define ( "SPH_MATCH_EXTENDED", 4 );
define ( "SPH_MATCH_FULLSCAN", 5 );
define ( "SPH_MATCH_EXTENDED2", 6 ); // extended engine V2 (TEMPORARY, WILL BE REMOVED)
/// known ranking modes (ext2 only)
define ( "SPH_RANK_PROXIMITY_BM25", 0 ); ///< default mode, phrase proximity major factor and BM25 minor one
define ( "SPH_RANK_BM25", 1 ); ///< statistical mode, BM25 ranking only (faster but worse quality)
define ( "SPH_RANK_NONE", 2 ); ///< no ranking, all matches get a weight of 1
define ( "SPH_RANK_WORDCOUNT", 3 ); ///< simple word-count weighting, rank is a weighted sum of per-field keyword occurence counts
define ( "SPH_RANK_PROXIMITY", 4 );
define ( "SPH_RANK_MATCHANY", 5 );
define ( "SPH_RANK_FIELDMASK", 6 );
define ( "SPH_RANK_SPH04", 7 );
define ( "SPH_RANK_EXPR", 8 );
define ( "SPH_RANK_TOTAL", 9 );
/// known sort modes
define ( "SPH_SORT_RELEVANCE", 0 );
define ( "SPH_SORT_ATTR_DESC", 1 );
define ( "SPH_SORT_ATTR_ASC", 2 );
define ( "SPH_SORT_TIME_SEGMENTS", 3 );
define ( "SPH_SORT_EXTENDED", 4 );
define ( "SPH_SORT_EXPR", 5 );
/// known filter types
define ( "SPH_FILTER_VALUES", 0 );
define ( "SPH_FILTER_RANGE", 1 );
define ( "SPH_FILTER_FLOATRANGE", 2 );
define ( "SPH_FILTER_STRING", 3 );
/// known attribute types
define ( "SPH_ATTR_INTEGER", 1 );
define ( "SPH_ATTR_TIMESTAMP", 2 );
define ( "SPH_ATTR_ORDINAL", 3 );
define ( "SPH_ATTR_BOOL", 4 );
define ( "SPH_ATTR_FLOAT", 5 );
define ( "SPH_ATTR_BIGINT", 6 );
define ( "SPH_ATTR_STRING", 7 );
define ( "SPH_ATTR_FACTORS", 1001 );
define ( "SPH_ATTR_MULTI", 0x40000001 );
define ( "SPH_ATTR_MULTI64", 0x40000002 );
/// known grouping functions
define ( "SPH_GROUPBY_DAY", 0 );
define ( "SPH_GROUPBY_WEEK", 1 );
define ( "SPH_GROUPBY_MONTH", 2 );
define ( "SPH_GROUPBY_YEAR", 3 );
define ( "SPH_GROUPBY_ATTR", 4 );
define ( "SPH_GROUPBY_ATTRPAIR", 5 );
// important properties of PHP's integers:
// - always signed (one bit short of PHP_INT_SIZE)
// - conversion from string to int is saturated
// - float is double
// - div converts arguments to floats
// - mod converts arguments to ints
// the packing code below works as follows:
// - when we got an int, just pack it
// if performance is a problem, this is the branch users should aim for
//
// - otherwise, we got a number in string form
// this might be due to different reasons, but we assume that this is
// because it didn't fit into PHP int
//
// - factor the string into high and low ints for packing
// - if we have bcmath, then it is used
// - if we don't, we have to do it manually (this is the fun part)
//
// - x64 branch does factoring using ints
// - x32 (ab)uses floats, since we can't fit unsigned 32-bit number into an int
//
// unpacking routines are pretty much the same.
// - return ints if we can
// - otherwise format number into a string
/// pack 64-bit signed
function sphPackI64 ( $v )
{
assert ( is_numeric($v) );
// x64
if ( PHP_INT_SIZE>=8 )
{
$v = (int)$v;
return pack ( "NN", $v>>32, $v&0xFFFFFFFF );
}
// x32, int
if ( is_int($v) )
return pack ( "NN", $v < 0 ? -1 : 0, $v );
// x32, bcmath
if ( function_exists("bcmul") )
{
if ( bccomp ( $v, 0 ) == -1 )
$v = bcadd ( "18446744073709551616", $v );
$h = bcdiv ( $v, "4294967296", 0 );
$l = bcmod ( $v, "4294967296" );
return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit
}
// x32, no-bcmath
$p = max(0, strlen($v) - 13);
$lo = abs((float)substr($v, $p));
$hi = abs((float)substr($v, 0, $p));
$m = $lo + $hi*1316134912.0; // (10 ^ 13) % (1 << 32) = 1316134912
$q = floor($m/4294967296.0);
$l = $m - ($q*4294967296.0);
$h = $hi*2328.0 + $q; // (10 ^ 13) / (1 << 32) = 2328
if ( $v<0 )
{
if ( $l==0 )
$h = 4294967296.0 - $h;
else
{
$h = 4294967295.0 - $h;
$l = 4294967296.0 - $l;
}
}
return pack ( "NN", $h, $l );
}
/// pack 64-bit unsigned
function sphPackU64 ( $v )
{
assert ( is_numeric($v) );
// x64
if ( PHP_INT_SIZE>=8 )
{
assert ( $v>=0 );
// x64, int
if ( is_int($v) )
return pack ( "NN", $v>>32, $v&0xFFFFFFFF );
// x64, bcmath
if ( function_exists("bcmul") )
{
$h = bcdiv ( $v, 4294967296, 0 );
$l = bcmod ( $v, 4294967296 );
return pack ( "NN", $h, $l );
}
// x64, no-bcmath
$p = max ( 0, strlen($v) - 13 );
$lo = (int)substr ( $v, $p );
$hi = (int)substr ( $v, 0, $p );
$m = $lo + $hi*1316134912;
$l = $m % 4294967296;
$h = $hi*2328 + (int)($m/4294967296);
return pack ( "NN", $h, $l );
}
// x32, int
if ( is_int($v) )
return pack ( "NN", 0, $v );
// x32, bcmath
if ( function_exists("bcmul") )
{
$h = bcdiv ( $v, "4294967296", 0 );
$l = bcmod ( $v, "4294967296" );
return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit
}
// x32, no-bcmath
$p = max(0, strlen($v) - 13);
$lo = (float)substr($v, $p);
$hi = (float)substr($v, 0, $p);
$m = $lo + $hi*1316134912.0;
$q = floor($m / 4294967296.0);
$l = $m - ($q * 4294967296.0);
$h = $hi*2328.0 + $q;
return pack ( "NN", $h, $l );
}
// unpack 64-bit unsigned
function sphUnpackU64 ( $v )
{
list ( $hi, $lo ) = array_values ( unpack ( "N*N*", $v ) );
if ( PHP_INT_SIZE>=8 )
{
if ( $hi<0 ) $hi += (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again
if ( $lo<0 ) $lo += (1<<32);
// x64, int
if ( $hi<=2147483647 )
return ($hi<<32) + $lo;
// x64, bcmath
if ( function_exists("bcmul") )
return bcadd ( $lo, bcmul ( $hi, "4294967296" ) );
// x64, no-bcmath
$C = 100000;
$h = ((int)($hi / $C) << 32) + (int)($lo / $C);
$l = (($hi % $C) << 32) + ($lo % $C);
if ( $l>$C )
{
$h += (int)($l / $C);
$l = $l % $C;
}
if ( $h==0 )
return $l;
return sprintf ( "%d%05d", $h, $l );
}
// x32, int
if ( $hi==0 )
{
if ( $lo>0 )
return $lo;
return sprintf ( "%u", $lo );
}
$hi = sprintf ( "%u", $hi );
$lo = sprintf ( "%u", $lo );
// x32, bcmath
if ( function_exists("bcmul") )
return bcadd ( $lo, bcmul ( $hi, "4294967296" ) );
// x32, no-bcmath
$hi = (float)$hi;
$lo = (float)$lo;
$q = floor($hi/10000000.0);
$r = $hi - $q*10000000.0;
$m = $lo + $r*4967296.0;
$mq = floor($m/10000000.0);
$l = $m - $mq*10000000.0;
$h = $q*4294967296.0 + $r*429.0 + $mq;
$h = sprintf ( "%.0f", $h );
$l = sprintf ( "%07.0f", $l );
if ( $h=="0" )
return sprintf( "%.0f", (float)$l );
return $h . $l;
}
// unpack 64-bit signed
function sphUnpackI64 ( $v )
{
list ( $hi, $lo ) = array_values ( unpack ( "N*N*", $v ) );
// x64
if ( PHP_INT_SIZE>=8 )
{
if ( $hi<0 ) $hi += (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again
if ( $lo<0 ) $lo += (1<<32);
return ($hi<<32) + $lo;
}
// x32, int
if ( $hi==0 )
{
if ( $lo>0 )
return $lo;
return sprintf ( "%u", $lo );
}
// x32, int
elseif ( $hi==-1 )
{
if ( $lo<0 )
return $lo;
return sprintf ( "%.0f", $lo - 4294967296.0 );
}
$neg = "";
$c = 0;
if ( $hi<0 )
{
$hi = ~$hi;
$lo = ~$lo;
$c = 1;
$neg = "-";
}
$hi = sprintf ( "%u", $hi );
$lo = sprintf ( "%u", $lo );
// x32, bcmath
if ( function_exists("bcmul") )
return $neg . bcadd ( bcadd ( $lo, bcmul ( $hi, "4294967296" ) ), $c );
// x32, no-bcmath
$hi = (float)$hi;
$lo = (float)$lo;
$q = floor($hi/10000000.0);
$r = $hi - $q*10000000.0;
$m = $lo + $r*4967296.0;
$mq = floor($m/10000000.0);
$l = $m - $mq*10000000.0 + $c;
$h = $q*4294967296.0 + $r*429.0 + $mq;
if ( $l==10000000 )
{
$l = 0;
$h += 1;
}
$h = sprintf ( "%.0f", $h );
$l = sprintf ( "%07.0f", $l );
if ( $h=="0" )
return $neg . sprintf( "%.0f", (float)$l );
return $neg . $h . $l;
}
function sphFixUint ( $value )
{
if ( PHP_INT_SIZE>=8 )
{
// x64 route, workaround broken unpack() in 5.2.2+
if ( $value<0 ) $value += (1<<32);
return $value;
}
else
{
// x32 route, workaround php signed/unsigned braindamage
return sprintf ( "%u", $value );
}
}
function SetBit ( $flag, $bit, $on )
{
if ( $on )
{
$flag += ( 1<<$bit );
} else
{
$reset = 255 ^ ( 1<<$bit );
$flag = $flag & $reset;
}
return $flag;
}
/// sphinx searchd client class
class SphinxClient
{
var $_host; ///< searchd host (default is "localhost")
var $_port; ///< searchd port (default is 9312)
var $_offset; ///< how many records to seek from result-set start (default is 0)
var $_limit; ///< how many records to return from result-set starting at offset (default is 20)
var $_mode; ///< query matching mode (default is SPH_MATCH_ALL)
var $_weights; ///< per-field weights (default is 1 for all fields)
var $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE)
var $_sortby; ///< attribute to sort by (defualt is "")
var $_min_id; ///< min ID to match (default is 0, which means no limit)
var $_max_id; ///< max ID to match (default is 0, which means no limit)
var $_filters; ///< search filters
var $_groupby; ///< group-by attribute name
var $_groupfunc; ///< group-by function (to pre-process group-by attribute value with)
var $_groupsort; ///< group-by sorting clause (to sort groups in result set with)
var $_groupdistinct;///< group-by count-distinct attribute
var $_maxmatches; ///< max matches to retrieve
var $_cutoff; ///< cutoff to stop searching at (default is 0)
var $_retrycount; ///< distributed retries count
var $_retrydelay; ///< distributed retries delay
var $_anchor; ///< geographical anchor point
var $_indexweights; ///< per-index weights
var $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25)
var $_rankexpr; ///< ranking mode expression (for SPH_RANK_EXPR)
var $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit)
var $_fieldweights; ///< per-field-name weights
var $_overrides; ///< per-query attribute values overrides
var $_select; ///< select-list (attributes or expressions, with optional aliases)
var $_query_flags; ///< per-query various flags
var $_predictedtime; ///< per-query max_predicted_time
var $_outerorderby; ///< outer match sort by
var $_outeroffset; ///< outer offset
var $_outerlimit; ///< outer limit
var $_hasouter;
var $_error; ///< last error message
var $_warning; ///< last warning message
var $_connerror; ///< connection error vs remote error flag
var $_reqs; ///< requests array for multi-query
var $_mbenc; ///< stored mbstring encoding
var $_arrayresult; ///< whether $result["matches"] should be a hash or an array
var $_timeout; ///< connect timeout
/////////////////////////////////////////////////////////////////////////////
// common stuff
/////////////////////////////////////////////////////////////////////////////
/// create a new client object and fill defaults
function __construct ()
{
// per-client-object settings
$this->_host = "localhost";
$this->_port = 9312;
$this->_path = false;
$this->_socket = false;
// per-query settings
$this->_offset = 0;
$this->_limit = 20;
$this->_mode = SPH_MATCH_ALL;
$this->_weights = array ();
$this->_sort = SPH_SORT_RELEVANCE;
$this->_sortby = "";
$this->_min_id = 0;
$this->_max_id = 0;
$this->_filters = array ();
$this->_groupby = "";
$this->_groupfunc = SPH_GROUPBY_DAY;
$this->_groupsort = "@group desc";
$this->_groupdistinct= "";
$this->_maxmatches = 1000;
$this->_cutoff = 0;
$this->_retrycount = 0;
$this->_retrydelay = 0;
$this->_anchor = array ();
$this->_indexweights= array ();
$this->_ranker = SPH_RANK_PROXIMITY_BM25;
$this->_rankexpr = "";
$this->_maxquerytime= 0;
$this->_fieldweights= array();
$this->_overrides = array();
$this->_select = "*";
$this->_query_flags = SetBit ( 0, 6, true ); // default idf=tfidf_normalized
$this->_predictedtime = 0;
$this->_outerorderby = "";
$this->_outeroffset = 0;
$this->_outerlimit = 0;
$this->_hasouter = false;
$this->_error = ""; // per-reply fields (for single-query case)
$this->_warning = "";
$this->_connerror = false;
$this->_reqs = array (); // requests storage (for multi-query case)
$this->_mbenc = "";
$this->_arrayresult = false;
$this->_timeout = 0;
}
function __destruct()
{
if ( $this->_socket !== false )
fclose ( $this->_socket );
}
/// get last error message (string)
function GetLastError ()
{
return $this->_error;
}
/// get last warning message (string)
function GetLastWarning ()
{
return $this->_warning;
}
/// get last error flag (to tell network connection errors from searchd errors or broken responses)
function IsConnectError()
{
return $this->_connerror;
}
/// set searchd host name (string) and port (integer)
function SetServer ( $host, $port = 0 )
{
assert ( is_string($host) );
if ( $host[0] == '/')
{
$this->_path = 'unix://' . $host;
return;
}
if ( substr ( $host, 0, 7 )=="unix://" )
{
$this->_path = $host;
return;
}
$this->_host = $host;
$port = intval($port);
assert ( 0<=$port && $port<65536 );
$this->_port = ( $port==0 ) ? 9312 : $port;
$this->_path = '';
}
/// set server connection timeout (0 to remove)
function SetConnectTimeout ( $timeout )
{
assert ( is_numeric($timeout) );
$this->_timeout = $timeout;
}
function _Send ( $handle, $data, $length )
{
if ( feof($handle) || fwrite ( $handle, $data, $length ) !== $length )
{
$this->_error = 'connection unexpectedly closed (timed out?)';
$this->_connerror = true;
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////
/// enter mbstring workaround mode
function _MBPush ()
{
$this->_mbenc = "";
if ( ini_get ( "mbstring.func_overload" ) & 2 )
{
$this->_mbenc = mb_internal_encoding();
mb_internal_encoding ( "latin1" );
}
}
/// leave mbstring workaround mode
function _MBPop ()
{
if ( $this->_mbenc )
mb_internal_encoding ( $this->_mbenc );
}
/// connect to searchd server
function _Connect ()
{
if ( $this->_socket!==false )
{
// we are in persistent connection mode, so we have a socket
// however, need to check whether it's still alive
if ( !@feof ( $this->_socket ) )
return $this->_socket;
// force reopen
$this->_socket = false;
}
$errno = 0;
$errstr = "";
$this->_connerror = false;
if ( $this->_path )
{
$host = $this->_path;
$port = 0;
}
else
{
$host = $this->_host;
$port = $this->_port;
}
if ( $this->_timeout<=0 )
$fp = @fsockopen ( $host, $port, $errno, $errstr );
else
$fp = @fsockopen ( $host, $port, $errno, $errstr, $this->_timeout );
if ( !$fp )
{
if ( $this->_path )
$location = $this->_path;
else
$location = "{$this->_host}:{$this->_port}";
$errstr = trim ( $errstr );
$this->_error = "connection to $location failed (errno=$errno, msg=$errstr)";
$this->_connerror = true;
return false;
}
// send my version
// this is a subtle part. we must do it before (!) reading back from searchd.
// because otherwise under some conditions (reported on FreeBSD for instance)
// TCP stack could throttle write-write-read pattern because of Nagle.
if ( !$this->_Send ( $fp, pack ( "N", 1 ), 4 ) )
{
fclose ( $fp );
$this->_error = "failed to send client protocol version";
return false;
}
// check version
list(,$v) = unpack ( "N*", fread ( $fp, 4 ) );
$v = (int)$v;
if ( $v<1 )
{
fclose ( $fp );
$this->_error = "expected searchd protocol version 1+, got version '$v'";
return false;
}
return $fp;
}
/// get and check response packet from searchd server
function _GetResponse ( $fp, $client_ver )
{
$response = "";
$len = 0;
$header = fread ( $fp, 8 );
if ( strlen($header)==8 )
{
list ( $status, $ver, $len ) = array_values ( unpack ( "n2a/Nb", $header ) );
$left = $len;
while ( $left>0 && !feof($fp) )
{
$chunk = fread ( $fp, min ( 8192, $left ) );
if ( $chunk )
{
$response .= $chunk;
$left -= strlen($chunk);
}
}
}
if ( $this->_socket === false )
fclose ( $fp );
// check response
$read = strlen ( $response );
if ( !$response || $read!=$len )
{
$this->_error = $len
? "failed to read searchd response (status=$status, ver=$ver, len=$len, read=$read)"
: "received zero-sized searchd response";
return false;
}
// check status
if ( $status==SEARCHD_WARNING )
{
list(,$wlen) = unpack ( "N*", substr ( $response, 0, 4 ) );
$this->_warning = substr ( $response, 4, $wlen );
return substr ( $response, 4+$wlen );
}
if ( $status==SEARCHD_ERROR )
{
$this->_error = "searchd error: " . substr ( $response, 4 );
return false;
}
if ( $status==SEARCHD_RETRY )
{
$this->_error = "temporary searchd error: " . substr ( $response, 4 );
return false;
}
if ( $status!=SEARCHD_OK )
{
$this->_error = "unknown status code '$status'";
return false;
}
// check version
if ( $ver<$client_ver )
{
$this->_warning = sprintf ( "searchd command v.%d.%d older than client's v.%d.%d, some options might not work",
$ver>>8, $ver&0xff, $client_ver>>8, $client_ver&0xff );
}
return $response;
}
/////////////////////////////////////////////////////////////////////////////
// searching
/////////////////////////////////////////////////////////////////////////////
/// set offset and count into result set,
/// and optionally set max-matches and cutoff limits
function SetLimits ( $offset, $limit, $max=0, $cutoff=0 )
{
assert ( is_int($offset) );
assert ( is_int($limit) );
assert ( $offset>=0 );
assert ( $limit>0 );
assert ( $max>=0 );
$this->_offset = $offset;
$this->_limit = $limit;
if ( $max>0 )
$this->_maxmatches = $max;
if ( $cutoff>0 )
$this->_cutoff = $cutoff;
}
/// set maximum query time, in milliseconds, per-index
/// integer, 0 means "do not limit"
function SetMaxQueryTime ( $max )
{
assert ( is_int($max) );
assert ( $max>=0 );
$this->_maxquerytime = $max;
}
/// set matching mode
function SetMatchMode ( $mode )
{
assert ( $mode==SPH_MATCH_ALL
|| $mode==SPH_MATCH_ANY
|| $mode==SPH_MATCH_PHRASE
|| $mode==SPH_MATCH_BOOLEAN
|| $mode==SPH_MATCH_EXTENDED
|| $mode==SPH_MATCH_FULLSCAN
|| $mode==SPH_MATCH_EXTENDED2 );
$this->_mode = $mode;
}
/// set ranking mode
function SetRankingMode ( $ranker, $rankexpr="" )
{
assert ( $ranker===0 || $ranker>=1 && $ranker<SPH_RANK_TOTAL );
assert ( is_string($rankexpr) );
$this->_ranker = $ranker;
$this->_rankexpr = $rankexpr;
}
/// set matches sorting mode
function SetSortMode ( $mode, $sortby="" )
{
assert (
$mode==SPH_SORT_RELEVANCE ||
$mode==SPH_SORT_ATTR_DESC ||
$mode==SPH_SORT_ATTR_ASC ||
$mode==SPH_SORT_TIME_SEGMENTS ||
$mode==SPH_SORT_EXTENDED ||
$mode==SPH_SORT_EXPR );
assert ( is_string($sortby) );
assert ( $mode==SPH_SORT_RELEVANCE || strlen($sortby)>0 );
$this->_sort = $mode;
$this->_sortby = $sortby;
}
/// bind per-field weights by order
/// DEPRECATED; use SetFieldWeights() instead
function SetWeights ( $weights )
{
assert ( is_array($weights) );
foreach ( $weights as $weight )
assert ( is_int($weight) );
$this->_weights = $weights;
}
/// bind per-field weights by name
function SetFieldWeights ( $weights )
{
assert ( is_array($weights) );
foreach ( $weights as $name=>$weight )
{
assert ( is_string($name) );
assert ( is_int($weight) );
}
$this->_fieldweights = $weights;
}
/// bind per-index weights by name
function SetIndexWeights ( $weights )
{
assert ( is_array($weights) );
foreach ( $weights as $index=>$weight )
{
assert ( is_string($index) );
assert ( is_int($weight) );
}
$this->_indexweights = $weights;
}
/// set IDs range to match
/// only match records if document ID is beetwen $min and $max (inclusive)
function SetIDRange ( $min, $max )
{
assert ( is_numeric($min) );
assert ( is_numeric($max) );
assert ( $min<=$max );
$this->_min_id = $min;
$this->_max_id = $max;
}
/// set values set filter
/// only match records where $attribute value is in given set
function SetFilter ( $attribute, $values, $exclude=false )
{
assert ( is_string($attribute) );
assert ( is_array($values) );
assert ( count($values) );
if ( is_array($values) && count($values) )
{
foreach ( $values as $value )
assert ( is_numeric($value) );
$this->_filters[] = array ( "type"=>SPH_FILTER_VALUES, "attr"=>$attribute, "exclude"=>$exclude, "values"=>$values );
}
}
/// set string filter
/// only match records where $attribute value is equal
function SetFilterString ( $attribute, $value, $exclude=false )
{
assert ( is_string($attribute) );
assert ( is_string($value) );
$this->_filters[] = array ( "type"=>SPH_FILTER_STRING, "attr"=>$attribute, "exclude"=>$exclude, "value"=>$value );
}
/// set range filter
/// only match records if $attribute value is beetwen $min and $max (inclusive)
function SetFilterRange ( $attribute, $min, $max, $exclude=false )
{
assert ( is_string($attribute) );
assert ( is_numeric($min) );
assert ( is_numeric($max) );
assert ( $min<=$max );
$this->_filters[] = array ( "type"=>SPH_FILTER_RANGE, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max );
}
/// set float range filter
/// only match records if $attribute value is beetwen $min and $max (inclusive)
function SetFilterFloatRange ( $attribute, $min, $max, $exclude=false )
{
assert ( is_string($attribute) );
assert ( is_float($min) );
assert ( is_float($max) );
assert ( $min<=$max );
$this->_filters[] = array ( "type"=>SPH_FILTER_FLOATRANGE, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max );
}
/// setup anchor point for geosphere distance calculations
/// required to use @geodist in filters and sorting
/// latitude and longitude must be in radians
function SetGeoAnchor ( $attrlat, $attrlong, $lat, $long )
{
assert ( is_string($attrlat) );
assert ( is_string($attrlong) );
assert ( is_float($lat) );
assert ( is_float($long) );
$this->_anchor = array ( "attrlat"=>$attrlat, "attrlong"=>$attrlong, "lat"=>$lat, "long"=>$long );
}
/// set grouping attribute and function
function SetGroupBy ( $attribute, $func, $groupsort="@group desc" )
{
assert ( is_string($attribute) );
assert ( is_string($groupsort) );
assert ( $func==SPH_GROUPBY_DAY
|| $func==SPH_GROUPBY_WEEK
|| $func==SPH_GROUPBY_MONTH
|| $func==SPH_GROUPBY_YEAR
|| $func==SPH_GROUPBY_ATTR
|| $func==SPH_GROUPBY_ATTRPAIR );
$this->_groupby = $attribute;
$this->_groupfunc = $func;
$this->_groupsort = $groupsort;
}
/// set count-distinct attribute for group-by queries
function SetGroupDistinct ( $attribute )
{
assert ( is_string($attribute) );
$this->_groupdistinct = $attribute;
}
/// set distributed retries count and delay
function SetRetries ( $count, $delay=0 )
{
assert ( is_int($count) && $count>=0 );
assert ( is_int($delay) && $delay>=0 );
$this->_retrycount = $count;
$this->_retrydelay = $delay;
}
/// set result set format (hash or array; hash by default)
/// PHP specific; needed for group-by-MVA result sets that may contain duplicate IDs
function SetArrayResult ( $arrayresult )
{
assert ( is_bool($arrayresult) );
$this->_arrayresult = $arrayresult;
}
/// set attribute values override
/// there can be only one override per attribute
/// $values must be a hash that maps document IDs to attribute values
function SetOverride ( $attrname, $attrtype, $values )
{
assert ( is_string ( $attrname ) );
assert ( in_array ( $attrtype, array ( SPH_ATTR_INTEGER, SPH_ATTR_TIMESTAMP, SPH_ATTR_BOOL, SPH_ATTR_FLOAT, SPH_ATTR_BIGINT ) ) );
assert ( is_array ( $values ) );
$this->_overrides[$attrname] = array ( "attr"=>$attrname, "type"=>$attrtype, "values"=>$values );
}
/// set select-list (attributes or expressions), SQL-like syntax
function SetSelect ( $select )
{
assert ( is_string ( $select ) );
$this->_select = $select;
}
function SetQueryFlag ( $flag_name, $flag_value )
{
$known_names = array ( "reverse_scan", "sort_method", "max_predicted_time", "boolean_simplify", "idf", "global_idf" );
$flags = array (
"reverse_scan" => array ( 0, 1 ),
"sort_method" => array ( "pq", "kbuffer" ),
"max_predicted_time" => array ( 0 ),
"boolean_simplify" => array ( true, false ),
"idf" => array ("normalized", "plain", "tfidf_normalized", "tfidf_unnormalized" ),
"global_idf" => array ( true, false ),
);
assert ( isset ( $flag_name, $known_names ) );
assert ( in_array( $flag_value, $flags[$flag_name], true ) || ( $flag_name=="max_predicted_time" && is_int ( $flag_value ) && $flag_value>=0 ) );
if ( $flag_name=="reverse_scan" ) $this->_query_flags = SetBit ( $this->_query_flags, 0, $flag_value==1 );
if ( $flag_name=="sort_method" ) $this->_query_flags = SetBit ( $this->_query_flags, 1, $flag_value=="kbuffer" );
if ( $flag_name=="max_predicted_time" )
{
$this->_query_flags = SetBit ( $this->_query_flags, 2, $flag_value>0 );
$this->_predictedtime = (int)$flag_value;
}
if ( $flag_name=="boolean_simplify" ) $this->_query_flags = SetBit ( $this->_query_flags, 3, $flag_value );
if ( $flag_name=="idf" && ( $flag_value=="normalized" || $flag_value=="plain" ) ) $this->_query_flags = SetBit ( $this->_query_flags, 4, $flag_value=="plain" );
if ( $flag_name=="global_idf" ) $this->_query_flags = SetBit ( $this->_query_flags, 5, $flag_value );
if ( $flag_name=="idf" && ( $flag_value=="tfidf_normalized" || $flag_value=="tfidf_unnormalized" ) ) $this->_query_flags = SetBit ( $this->_query_flags, 6, $flag_value=="tfidf_normalized" );
}
/// set outer order by parameters
function SetOuterSelect ( $orderby, $offset, $limit )
{
assert ( is_string($orderby) );
assert ( is_int($offset) );
assert ( is_int($limit) );
assert ( $offset>=0 );
assert ( $limit>0 );
$this->_outerorderby = $orderby;