4 // $Id: sphinxapi.php 2758 2011-04-04 11:10:44Z kevg $
8 // Copyright (c) 2001-2011, Andrew Aksyonoff
9 // Copyright (c) 2008-2011, Sphinx Technologies Inc
10 // All rights reserved
12 // This program is free software; you can redistribute it and/or modify
13 // it under the terms of the GNU General Public License. You should have
14 // received a copy of the GPL license along with this program; if you
15 // did not, you can find it at http://www.gnu.org/
18 /////////////////////////////////////////////////////////////////////////////
19 // PHP version of Sphinx searchd client (PHP API)
20 /////////////////////////////////////////////////////////////////////////////
22 /// known searchd commands
23 define ( "SEARCHD_COMMAND_SEARCH", 0 );
24 define ( "SEARCHD_COMMAND_EXCERPT", 1 );
25 define ( "SEARCHD_COMMAND_UPDATE", 2 );
26 define ( "SEARCHD_COMMAND_KEYWORDS", 3 );
27 define ( "SEARCHD_COMMAND_PERSIST", 4 );
28 define ( "SEARCHD_COMMAND_STATUS", 5 );
29 define ( "SEARCHD_COMMAND_FLUSHATTRS", 7 );
31 /// current client-side command implementation versions
32 define ( "VER_COMMAND_SEARCH", 0x118 );
33 define ( "VER_COMMAND_EXCERPT", 0x103 );
34 define ( "VER_COMMAND_UPDATE", 0x102 );
35 define ( "VER_COMMAND_KEYWORDS", 0x100 );
36 define ( "VER_COMMAND_STATUS", 0x100 );
37 define ( "VER_COMMAND_QUERY", 0x100 );
38 define ( "VER_COMMAND_FLUSHATTRS", 0x100 );
40 /// known searchd status codes
41 define ( "SEARCHD_OK", 0 );
42 define ( "SEARCHD_ERROR", 1 );
43 define ( "SEARCHD_RETRY", 2 );
44 define ( "SEARCHD_WARNING", 3 );
47 define ( "SPH_MATCH_ALL", 0 );
48 define ( "SPH_MATCH_ANY", 1 );
49 define ( "SPH_MATCH_PHRASE", 2 );
50 define ( "SPH_MATCH_BOOLEAN", 3 );
51 define ( "SPH_MATCH_EXTENDED", 4 );
52 define ( "SPH_MATCH_FULLSCAN", 5 );
53 define ( "SPH_MATCH_EXTENDED2", 6 ); // extended engine V2 (TEMPORARY, WILL BE REMOVED)
55 /// known ranking modes (ext2 only)
56 define ( "SPH_RANK_PROXIMITY_BM25", 0 ); ///< default mode, phrase proximity major factor and BM25 minor one
57 define ( "SPH_RANK_BM25", 1 ); ///< statistical mode, BM25 ranking only (faster but worse quality)
58 define ( "SPH_RANK_NONE", 2 ); ///< no ranking, all matches get a weight of 1
59 define ( "SPH_RANK_WORDCOUNT", 3 ); ///< simple word-count weighting, rank is a weighted sum of per-field keyword occurence counts
60 define ( "SPH_RANK_PROXIMITY", 4 );
61 define ( "SPH_RANK_MATCHANY", 5 );
62 define ( "SPH_RANK_FIELDMASK", 6 );
63 define ( "SPH_RANK_SPH04", 7 );
64 define ( "SPH_RANK_TOTAL", 8 );
67 define ( "SPH_SORT_RELEVANCE", 0 );
68 define ( "SPH_SORT_ATTR_DESC", 1 );
69 define ( "SPH_SORT_ATTR_ASC", 2 );
70 define ( "SPH_SORT_TIME_SEGMENTS", 3 );
71 define ( "SPH_SORT_EXTENDED", 4 );
72 define ( "SPH_SORT_EXPR", 5 );
74 /// known filter types
75 define ( "SPH_FILTER_VALUES", 0 );
76 define ( "SPH_FILTER_RANGE", 1 );
77 define ( "SPH_FILTER_FLOATRANGE", 2 );
79 /// known attribute types
80 define ( "SPH_ATTR_INTEGER", 1 );
81 define ( "SPH_ATTR_TIMESTAMP", 2 );
82 define ( "SPH_ATTR_ORDINAL", 3 );
83 define ( "SPH_ATTR_BOOL", 4 );
84 define ( "SPH_ATTR_FLOAT", 5 );
85 define ( "SPH_ATTR_BIGINT", 6 );
86 define ( "SPH_ATTR_STRING", 7 );
87 define ( "SPH_ATTR_MULTI", 0x40000000 );
89 /// known grouping functions
90 define ( "SPH_GROUPBY_DAY", 0 );
91 define ( "SPH_GROUPBY_WEEK", 1 );
92 define ( "SPH_GROUPBY_MONTH", 2 );
93 define ( "SPH_GROUPBY_YEAR", 3 );
94 define ( "SPH_GROUPBY_ATTR", 4 );
95 define ( "SPH_GROUPBY_ATTRPAIR", 5 );
97 // important properties of PHP's integers:
98 // - always signed (one bit short of PHP_INT_SIZE)
99 // - conversion from string to int is saturated
101 // - div converts arguments to floats
102 // - mod converts arguments to ints
104 // the packing code below works as follows:
105 // - when we got an int, just pack it
106 // if performance is a problem, this is the branch users should aim for
108 // - otherwise, we got a number in string form
109 // this might be due to different reasons, but we assume that this is
110 // because it didn't fit into PHP int
112 // - factor the string into high and low ints for packing
113 // - if we have bcmath, then it is used
114 // - if we don't, we have to do it manually (this is the fun part)
116 // - x64 branch does factoring using ints
117 // - x32 (ab)uses floats, since we can't fit unsigned 32-bit number into an int
119 // unpacking routines are pretty much the same.
120 // - return ints if we can
121 // - otherwise format number into a string
123 /// pack 64-bit signed
124 function sphPackI64 ( $v )
126 assert ( is_numeric($v) );
129 if ( PHP_INT_SIZE
>=8 )
132 return pack ( "NN", $v>>32, $v&0xFFFFFFFF );
137 return pack ( "NN", $v < 0 ?
-1 : 0, $v );
140 if ( function_exists("bcmul") )
142 if ( bccomp ( $v, 0 ) == -1 )
143 $v = bcadd ( "18446744073709551616", $v );
144 $h = bcdiv ( $v, "4294967296", 0 );
145 $l = bcmod ( $v, "4294967296" );
146 return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit
150 $p = max(0, strlen($v) - 13);
151 $lo = abs((float)substr($v, $p));
152 $hi = abs((float)substr($v, 0, $p));
154 $m = $lo +
$hi*1316134912.0; // (10 ^ 13) % (1 << 32) = 1316134912
155 $q = floor($m/4294967296.0);
156 $l = $m - ($q*4294967296.0);
157 $h = $hi*2328.0 +
$q; // (10 ^ 13) / (1 << 32) = 2328
162 $h = 4294967296.0 - $h;
165 $h = 4294967295.0 - $h;
166 $l = 4294967296.0 - $l;
169 return pack ( "NN", $h, $l );
172 /// pack 64-bit unsigned
173 function sphPackU64 ( $v )
175 assert ( is_numeric($v) );
178 if ( PHP_INT_SIZE
>=8 )
184 return pack ( "NN", $v>>32, $v&0xFFFFFFFF );
187 if ( function_exists("bcmul") )
189 $h = bcdiv ( $v, 4294967296, 0 );
190 $l = bcmod ( $v, 4294967296 );
191 return pack ( "NN", $h, $l );
195 $p = max ( 0, strlen($v) - 13 );
196 $lo = (int)substr ( $v, $p );
197 $hi = (int)substr ( $v, 0, $p );
199 $m = $lo +
$hi*1316134912;
200 $l = $m %
4294967296;
201 $h = $hi*2328 +
(int)($m/4294967296);
203 return pack ( "NN", $h, $l );
208 return pack ( "NN", 0, $v );
211 if ( function_exists("bcmul") )
213 $h = bcdiv ( $v, "4294967296", 0 );
214 $l = bcmod ( $v, "4294967296" );
215 return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit
219 $p = max(0, strlen($v) - 13);
220 $lo = (float)substr($v, $p);
221 $hi = (float)substr($v, 0, $p);
223 $m = $lo +
$hi*1316134912.0;
224 $q = floor($m / 4294967296.0);
225 $l = $m - ($q * 4294967296.0);
226 $h = $hi*2328.0 +
$q;
228 return pack ( "NN", $h, $l );
231 // unpack 64-bit unsigned
232 function sphUnpackU64 ( $v )
234 list ( $hi, $lo ) = array_values ( unpack ( "N*N*", $v ) );
236 if ( PHP_INT_SIZE
>=8 )
238 if ( $hi<0 ) $hi +
= (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again
239 if ( $lo<0 ) $lo +
= (1<<32);
242 if ( $hi<=2147483647 )
243 return ($hi<<32) +
$lo;
246 if ( function_exists("bcmul") )
247 return bcadd ( $lo, bcmul ( $hi, "4294967296" ) );
251 $h = ((int)($hi / $C) << 32) +
(int)($lo / $C);
252 $l = (($hi %
$C) << 32) +
($lo %
$C);
255 $h +
= (int)($l / $C);
261 return sprintf ( "%d%05d", $h, $l );
269 return sprintf ( "%u", $lo );
272 $hi = sprintf ( "%u", $hi );
273 $lo = sprintf ( "%u", $lo );
276 if ( function_exists("bcmul") )
277 return bcadd ( $lo, bcmul ( $hi, "4294967296" ) );
283 $q = floor($hi/10000000.0);
284 $r = $hi - $q*10000000.0;
285 $m = $lo +
$r*4967296.0;
286 $mq = floor($m/10000000.0);
287 $l = $m - $mq*10000000.0;
288 $h = $q*4294967296.0 +
$r*429.0 +
$mq;
290 $h = sprintf ( "%.0f", $h );
291 $l = sprintf ( "%07.0f", $l );
293 return sprintf( "%.0f", (float)$l );
297 // unpack 64-bit signed
298 function sphUnpackI64 ( $v )
300 list ( $hi, $lo ) = array_values ( unpack ( "N*N*", $v ) );
303 if ( PHP_INT_SIZE
>=8 )
305 if ( $hi<0 ) $hi +
= (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again
306 if ( $lo<0 ) $lo +
= (1<<32);
308 return ($hi<<32) +
$lo;
316 return sprintf ( "%u", $lo );
323 return sprintf ( "%.0f", $lo - 4294967296.0 );
336 $hi = sprintf ( "%u", $hi );
337 $lo = sprintf ( "%u", $lo );
340 if ( function_exists("bcmul") )
341 return $neg . bcadd ( bcadd ( $lo, bcmul ( $hi, "4294967296" ) ), $c );
347 $q = floor($hi/10000000.0);
348 $r = $hi - $q*10000000.0;
349 $m = $lo +
$r*4967296.0;
350 $mq = floor($m/10000000.0);
351 $l = $m - $mq*10000000.0 +
$c;
352 $h = $q*4294967296.0 +
$r*429.0 +
$mq;
359 $h = sprintf ( "%.0f", $h );
360 $l = sprintf ( "%07.0f", $l );
362 return $neg . sprintf( "%.0f", (float)$l );
363 return $neg . $h . $l;
367 function sphFixUint ( $value )
369 if ( PHP_INT_SIZE
>=8 )
371 // x64 route, workaround broken unpack() in 5.2.2+
372 if ( $value<0 ) $value +
= (1<<32);
377 // x32 route, workaround php signed/unsigned braindamage
378 return sprintf ( "%u", $value );
383 /// sphinx searchd client class
386 var $_host; ///< searchd host (default is "localhost")
387 var $_port; ///< searchd port (default is 9312)
388 var $_offset; ///< how many records to seek from result-set start (default is 0)
389 var $_limit; ///< how many records to return from result-set starting at offset (default is 20)
390 var $_mode; ///< query matching mode (default is SPH_MATCH_ALL)
391 var $_weights; ///< per-field weights (default is 1 for all fields)
392 var $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE)
393 var $_sortby; ///< attribute to sort by (defualt is "")
394 var $_min_id; ///< min ID to match (default is 0, which means no limit)
395 var $_max_id; ///< max ID to match (default is 0, which means no limit)
396 var $_filters; ///< search filters
397 var $_groupby; ///< group-by attribute name
398 var $_groupfunc; ///< group-by function (to pre-process group-by attribute value with)
399 var $_groupsort; ///< group-by sorting clause (to sort groups in result set with)
400 var $_groupdistinct;///< group-by count-distinct attribute
401 var $_maxmatches; ///< max matches to retrieve
402 var $_cutoff; ///< cutoff to stop searching at (default is 0)
403 var $_retrycount; ///< distributed retries count
404 var $_retrydelay; ///< distributed retries delay
405 var $_anchor; ///< geographical anchor point
406 var $_indexweights; ///< per-index weights
407 var $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25)
408 var $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit)
409 var $_fieldweights; ///< per-field-name weights
410 var $_overrides; ///< per-query attribute values overrides
411 var $_select; ///< select-list (attributes or expressions, with optional aliases)
413 var $_error; ///< last error message
414 var $_warning; ///< last warning message
415 var $_connerror; ///< connection error vs remote error flag
417 var $_reqs; ///< requests array for multi-query
418 var $_mbenc; ///< stored mbstring encoding
419 var $_arrayresult; ///< whether $result["matches"] should be a hash or an array
420 var $_timeout; ///< connect timeout
422 /////////////////////////////////////////////////////////////////////////////
424 /////////////////////////////////////////////////////////////////////////////
426 /// create a new client object and fill defaults
427 function SphinxClient ()
429 // per-client-object settings
430 $this->_host
= "localhost";
432 $this->_path
= false;
433 $this->_socket
= false;
435 // per-query settings
438 $this->_mode
= SPH_MATCH_ALL
;
439 $this->_weights
= array ();
440 $this->_sort
= SPH_SORT_RELEVANCE
;
444 $this->_filters
= array ();
445 $this->_groupby
= "";
446 $this->_groupfunc
= SPH_GROUPBY_DAY
;
447 $this->_groupsort
= "@group desc";
448 $this->_groupdistinct
= "";
449 $this->_maxmatches
= 1000;
451 $this->_retrycount
= 0;
452 $this->_retrydelay
= 0;
453 $this->_anchor
= array ();
454 $this->_indexweights
= array ();
455 $this->_ranker
= SPH_RANK_PROXIMITY_BM25
;
456 $this->_maxquerytime
= 0;
457 $this->_fieldweights
= array();
458 $this->_overrides
= array();
459 $this->_select
= "*";
461 $this->_error
= ""; // per-reply fields (for single-query case)
462 $this->_warning
= "";
463 $this->_connerror
= false;
465 $this->_reqs
= array (); // requests storage (for multi-query case)
467 $this->_arrayresult
= false;
471 function __destruct()
473 if ( $this->_socket
!== false )
474 fclose ( $this->_socket
);
477 /// get last error message (string)
478 function GetLastError ()
480 return $this->_error
;
483 /// get last warning message (string)
484 function GetLastWarning ()
486 return $this->_warning
;
489 /// get last error flag (to tell network connection errors from searchd errors or broken responses)
490 function IsConnectError()
492 return $this->_connerror
;
495 /// set searchd host name (string) and port (integer)
496 function SetServer ( $host, $port = 0 )
498 assert ( is_string($host) );
499 if ( $host[0] == '/')
501 $this->_path
= 'unix://' . $host;
504 if ( substr ( $host, 0, 7 )=="unix://" )
506 $this->_path
= $host;
510 assert ( is_int($port) );
511 $this->_host
= $host;
512 $this->_port
= $port;
517 /// set server connection timeout (0 to remove)
518 function SetConnectTimeout ( $timeout )
520 assert ( is_numeric($timeout) );
521 $this->_timeout
= $timeout;
525 function _Send ( $handle, $data, $length )
527 if ( feof($handle) ||
fwrite ( $handle, $data, $length ) !== $length )
529 $this->_error
= 'connection unexpectedly closed (timed out?)';
530 $this->_connerror
= true;
536 /////////////////////////////////////////////////////////////////////////////
538 /// enter mbstring workaround mode
542 if ( ini_get ( "mbstring.func_overload" ) & 2 )
544 $this->_mbenc
= mb_internal_encoding();
545 mb_internal_encoding ( "latin1" );
549 /// leave mbstring workaround mode
553 mb_internal_encoding ( $this->_mbenc
);
556 /// connect to searchd server
559 if ( $this->_socket
!==false )
561 // we are in persistent connection mode, so we have a socket
562 // however, need to check whether it's still alive
563 if ( !@feof
( $this->_socket
) )
564 return $this->_socket
;
567 $this->_socket
= false;
572 $this->_connerror
= false;
576 $host = $this->_path
;
581 $host = $this->_host
;
582 $port = $this->_port
;
585 if ( $this->_timeout
<=0 )
586 $fp = @fsockopen
( $host, $port, $errno, $errstr );
588 $fp = @fsockopen
( $host, $port, $errno, $errstr, $this->_timeout
);
593 $location = $this->_path
;
595 $location = "{$this->_host}:{$this->_port}";
597 $errstr = trim ( $errstr );
598 $this->_error
= "connection to $location failed (errno=$errno, msg=$errstr)";
599 $this->_connerror
= true;
604 // this is a subtle part. we must do it before (!) reading back from searchd.
605 // because otherwise under some conditions (reported on FreeBSD for instance)
606 // TCP stack could throttle write-write-read pattern because of Nagle.
607 if ( !$this->_Send ( $fp, pack ( "N", 1 ), 4 ) )
610 $this->_error
= "failed to send client protocol version";
615 list(,$v) = unpack ( "N*", fread ( $fp, 4 ) );
620 $this->_error
= "expected searchd protocol version 1+, got version '$v'";
627 /// get and check response packet from searchd server
628 function _GetResponse ( $fp, $client_ver )
633 $header = fread ( $fp, 8 );
634 if ( strlen($header)==8 )
636 list ( $status, $ver, $len ) = array_values ( unpack ( "n2a/Nb", $header ) );
638 while ( $left>0 && !feof($fp) )
640 $chunk = fread ( $fp, min ( 8192, $left ) );
644 $left -= strlen($chunk);
648 if ( $this->_socket
=== false )
652 $read = strlen ( $response );
653 if ( !$response ||
$read!=$len )
656 ?
"failed to read searchd response (status=$status, ver=$ver, len=$len, read=$read)"
657 : "received zero-sized searchd response";
662 if ( $status==SEARCHD_WARNING
)
664 list(,$wlen) = unpack ( "N*", substr ( $response, 0, 4 ) );
665 $this->_warning
= substr ( $response, 4, $wlen );
666 return substr ( $response, 4+
$wlen );
668 if ( $status==SEARCHD_ERROR
)
670 $this->_error
= "searchd error: " . substr ( $response, 4 );
673 if ( $status==SEARCHD_RETRY
)
675 $this->_error
= "temporary searchd error: " . substr ( $response, 4 );
678 if ( $status!=SEARCHD_OK
)
680 $this->_error
= "unknown status code '$status'";
685 if ( $ver<$client_ver )
687 $this->_warning
= sprintf ( "searchd command v.%d.%d older than client's v.%d.%d, some options might not work",
688 $ver>>8, $ver&0xff, $client_ver>>8, $client_ver&0xff );
694 /////////////////////////////////////////////////////////////////////////////
696 /////////////////////////////////////////////////////////////////////////////
698 /// set offset and count into result set,
699 /// and optionally set max-matches and cutoff limits
700 function SetLimits ( $offset, $limit, $max=0, $cutoff=0 )
702 assert ( is_int($offset) );
703 assert ( is_int($limit) );
704 assert ( $offset>=0 );
707 $this->_offset
= $offset;
708 $this->_limit
= $limit;
710 $this->_maxmatches
= $max;
712 $this->_cutoff
= $cutoff;
715 /// set maximum query time, in milliseconds, per-index
716 /// integer, 0 means "do not limit"
717 function SetMaxQueryTime ( $max )
719 assert ( is_int($max) );
721 $this->_maxquerytime
= $max;
724 /// set matching mode
725 function SetMatchMode ( $mode )
727 assert ( $mode==SPH_MATCH_ALL
728 ||
$mode==SPH_MATCH_ANY
729 ||
$mode==SPH_MATCH_PHRASE
730 ||
$mode==SPH_MATCH_BOOLEAN
731 ||
$mode==SPH_MATCH_EXTENDED
732 ||
$mode==SPH_MATCH_FULLSCAN
733 ||
$mode==SPH_MATCH_EXTENDED2
);
734 $this->_mode
= $mode;
738 function SetRankingMode ( $ranker )
740 assert ( $ranker>=0 && $ranker<SPH_RANK_TOTAL
);
741 $this->_ranker
= $ranker;
744 /// set matches sorting mode
745 function SetSortMode ( $mode, $sortby="" )
748 $mode==SPH_SORT_RELEVANCE ||
749 $mode==SPH_SORT_ATTR_DESC ||
750 $mode==SPH_SORT_ATTR_ASC ||
751 $mode==SPH_SORT_TIME_SEGMENTS ||
752 $mode==SPH_SORT_EXTENDED ||
753 $mode==SPH_SORT_EXPR
);
754 assert ( is_string($sortby) );
755 assert ( $mode==SPH_SORT_RELEVANCE ||
strlen($sortby)>0 );
757 $this->_sort
= $mode;
758 $this->_sortby
= $sortby;
761 /// bind per-field weights by order
762 /// DEPRECATED; use SetFieldWeights() instead
763 function SetWeights ( $weights )
765 assert ( is_array($weights) );
766 foreach ( $weights as $weight )
767 assert ( is_int($weight) );
769 $this->_weights
= $weights;
772 /// bind per-field weights by name
773 function SetFieldWeights ( $weights )
775 assert ( is_array($weights) );
776 foreach ( $weights as $name=>$weight )
778 assert ( is_string($name) );
779 assert ( is_int($weight) );
781 $this->_fieldweights
= $weights;
784 /// bind per-index weights by name
785 function SetIndexWeights ( $weights )
787 assert ( is_array($weights) );
788 foreach ( $weights as $index=>$weight )
790 assert ( is_string($index) );
791 assert ( is_int($weight) );
793 $this->_indexweights
= $weights;
796 /// set IDs range to match
797 /// only match records if document ID is beetwen $min and $max (inclusive)
798 function SetIDRange ( $min, $max )
800 assert ( is_numeric($min) );
801 assert ( is_numeric($max) );
802 assert ( $min<=$max );
803 $this->_min_id
= $min;
804 $this->_max_id
= $max;
807 /// set values set filter
808 /// only match records where $attribute value is in given set
809 function SetFilter ( $attribute, $values, $exclude=false )
811 assert ( is_string($attribute) );
812 assert ( is_array($values) );
813 assert ( count($values) );
815 if ( is_array($values) && count($values) )
817 foreach ( $values as $value )
818 assert ( is_numeric($value) );
820 $this->_filters
[] = array ( "type"=>SPH_FILTER_VALUES
, "attr"=>$attribute, "exclude"=>$exclude, "values"=>$values );
825 /// only match records if $attribute value is beetwen $min and $max (inclusive)
826 function SetFilterRange ( $attribute, $min, $max, $exclude=false )
828 assert ( is_string($attribute) );
829 assert ( is_numeric($min) );
830 assert ( is_numeric($max) );
831 assert ( $min<=$max );
833 $this->_filters
[] = array ( "type"=>SPH_FILTER_RANGE
, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max );
836 /// set float range filter
837 /// only match records if $attribute value is beetwen $min and $max (inclusive)
838 function SetFilterFloatRange ( $attribute, $min, $max, $exclude=false )
840 assert ( is_string($attribute) );
841 assert ( is_float($min) );
842 assert ( is_float($max) );
843 assert ( $min<=$max );
845 $this->_filters
[] = array ( "type"=>SPH_FILTER_FLOATRANGE
, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max );
848 /// setup anchor point for geosphere distance calculations
849 /// required to use @geodist in filters and sorting
850 /// latitude and longitude must be in radians
851 function SetGeoAnchor ( $attrlat, $attrlong, $lat, $long )
853 assert ( is_string($attrlat) );
854 assert ( is_string($attrlong) );
855 assert ( is_float($lat) );
856 assert ( is_float($long) );
858 $this->_anchor
= array ( "attrlat"=>$attrlat, "attrlong"=>$attrlong, "lat"=>$lat, "long"=>$long );
861 /// set grouping attribute and function
862 function SetGroupBy ( $attribute, $func, $groupsort="@group desc" )
864 assert ( is_string($attribute) );
865 assert ( is_string($groupsort) );
866 assert ( $func==SPH_GROUPBY_DAY
867 ||
$func==SPH_GROUPBY_WEEK
868 ||
$func==SPH_GROUPBY_MONTH
869 ||
$func==SPH_GROUPBY_YEAR
870 ||
$func==SPH_GROUPBY_ATTR
871 ||
$func==SPH_GROUPBY_ATTRPAIR
);
873 $this->_groupby
= $attribute;
874 $this->_groupfunc
= $func;
875 $this->_groupsort
= $groupsort;
878 /// set count-distinct attribute for group-by queries
879 function SetGroupDistinct ( $attribute )
881 assert ( is_string($attribute) );
882 $this->_groupdistinct
= $attribute;
885 /// set distributed retries count and delay
886 function SetRetries ( $count, $delay=0 )
888 assert ( is_int($count) && $count>=0 );
889 assert ( is_int($delay) && $delay>=0 );
890 $this->_retrycount
= $count;
891 $this->_retrydelay
= $delay;
894 /// set result set format (hash or array; hash by default)
895 /// PHP specific; needed for group-by-MVA result sets that may contain duplicate IDs
896 function SetArrayResult ( $arrayresult )
898 assert ( is_bool($arrayresult) );
899 $this->_arrayresult
= $arrayresult;
902 /// set attribute values override
903 /// there can be only one override per attribute
904 /// $values must be a hash that maps document IDs to attribute values
905 function SetOverride ( $attrname, $attrtype, $values )
907 assert ( is_string ( $attrname ) );
908 assert ( in_array ( $attrtype, array ( SPH_ATTR_INTEGER
, SPH_ATTR_TIMESTAMP
, SPH_ATTR_BOOL
, SPH_ATTR_FLOAT
, SPH_ATTR_BIGINT
) ) );
909 assert ( is_array ( $values ) );
911 $this->_overrides
[$attrname] = array ( "attr"=>$attrname, "type"=>$attrtype, "values"=>$values );
914 /// set select-list (attributes or expressions), SQL-like syntax
915 function SetSelect ( $select )
917 assert ( is_string ( $select ) );
918 $this->_select
= $select;
921 //////////////////////////////////////////////////////////////////////////////
923 /// clear all filters (for multi-queries)
924 function ResetFilters ()
926 $this->_filters
= array();
927 $this->_anchor
= array();
930 /// clear groupby settings (for multi-queries)
931 function ResetGroupBy ()
933 $this->_groupby
= "";
934 $this->_groupfunc
= SPH_GROUPBY_DAY
;
935 $this->_groupsort
= "@group desc";
936 $this->_groupdistinct
= "";
939 /// clear all attribute value overrides (for multi-queries)
940 function ResetOverrides ()
942 $this->_overrides
= array ();
945 //////////////////////////////////////////////////////////////////////////////
947 /// connect to searchd server, run given search query through given indexes,
948 /// and return the search results
949 function Query ( $query, $index="*", $comment="" )
951 assert ( empty($this->_reqs
) );
953 $this->AddQuery ( $query, $index, $comment );
954 $results = $this->RunQueries ();
955 $this->_reqs
= array (); // just in case it failed too early
957 if ( !is_array($results) )
958 return false; // probably network error; error message should be already filled
960 $this->_error
= $results[0]["error"];
961 $this->_warning
= $results[0]["warning"];
962 if ( $results[0]["status"]==SEARCHD_ERROR
)
968 /// helper to pack floats in network byte order
969 function _PackFloat ( $f )
971 $t1 = pack ( "f", $f ); // machine order
972 list(,$t2) = unpack ( "L*", $t1 ); // int in machine order
973 return pack ( "N", $t2 );
976 /// add query to multi-query batch
977 /// returns index into results array from RunQueries() call
978 function AddQuery ( $query, $index="*", $comment="" )
980 // mbstring workaround
984 $req = pack ( "NNNNN", $this->_offset
, $this->_limit
, $this->_mode
, $this->_ranker
, $this->_sort
); // mode and limits
985 $req .= pack ( "N", strlen($this->_sortby
) ) . $this->_sortby
;
986 $req .= pack ( "N", strlen($query) ) . $query; // query itself
987 $req .= pack ( "N", count($this->_weights
) ); // weights
988 foreach ( $this->_weights
as $weight )
989 $req .= pack ( "N", (int)$weight );
990 $req .= pack ( "N", strlen($index) ) . $index; // indexes
991 $req .= pack ( "N", 1 ); // id64 range marker
992 $req .= sphPackU64 ( $this->_min_id
) . sphPackU64 ( $this->_max_id
); // id64 range
995 $req .= pack ( "N", count($this->_filters
) );
996 foreach ( $this->_filters
as $filter )
998 $req .= pack ( "N", strlen($filter["attr"]) ) . $filter["attr"];
999 $req .= pack ( "N", $filter["type"] );
1000 switch ( $filter["type"] )
1002 case SPH_FILTER_VALUES
:
1003 $req .= pack ( "N", count($filter["values"]) );
1004 foreach ( $filter["values"] as $value )
1005 $req .= sphPackI64 ( $value );
1008 case SPH_FILTER_RANGE
:
1009 $req .= sphPackI64 ( $filter["min"] ) . sphPackI64 ( $filter["max"] );
1012 case SPH_FILTER_FLOATRANGE
:
1013 $req .= $this->_PackFloat ( $filter["min"] ) . $this->_PackFloat ( $filter["max"] );
1017 assert ( 0 && "internal error: unhandled filter type" );
1019 $req .= pack ( "N", $filter["exclude"] );
1022 // group-by clause, max-matches count, group-sort clause, cutoff count
1023 $req .= pack ( "NN", $this->_groupfunc
, strlen($this->_groupby
) ) . $this->_groupby
;
1024 $req .= pack ( "N", $this->_maxmatches
);
1025 $req .= pack ( "N", strlen($this->_groupsort
) ) . $this->_groupsort
;
1026 $req .= pack ( "NNN", $this->_cutoff
, $this->_retrycount
, $this->_retrydelay
);
1027 $req .= pack ( "N", strlen($this->_groupdistinct
) ) . $this->_groupdistinct
;
1030 if ( empty($this->_anchor
) )
1032 $req .= pack ( "N", 0 );
1035 $a =& $this->_anchor
;
1036 $req .= pack ( "N", 1 );
1037 $req .= pack ( "N", strlen($a["attrlat"]) ) . $a["attrlat"];
1038 $req .= pack ( "N", strlen($a["attrlong"]) ) . $a["attrlong"];
1039 $req .= $this->_PackFloat ( $a["lat"] ) . $this->_PackFloat ( $a["long"] );
1042 // per-index weights
1043 $req .= pack ( "N", count($this->_indexweights
) );
1044 foreach ( $this->_indexweights
as $idx=>$weight )
1045 $req .= pack ( "N", strlen($idx) ) . $idx . pack ( "N", $weight );
1048 $req .= pack ( "N", $this->_maxquerytime
);
1050 // per-field weights
1051 $req .= pack ( "N", count($this->_fieldweights
) );
1052 foreach ( $this->_fieldweights
as $field=>$weight )
1053 $req .= pack ( "N", strlen($field) ) . $field . pack ( "N", $weight );
1056 $req .= pack ( "N", strlen($comment) ) . $comment;
1058 // attribute overrides
1059 $req .= pack ( "N", count($this->_overrides
) );
1060 foreach ( $this->_overrides
as $key => $entry )
1062 $req .= pack ( "N", strlen($entry["attr"]) ) . $entry["attr"];
1063 $req .= pack ( "NN", $entry["type"], count($entry["values"]) );
1064 foreach ( $entry["values"] as $id=>$val )
1066 assert ( is_numeric($id) );
1067 assert ( is_numeric($val) );
1069 $req .= sphPackU64 ( $id );
1070 switch ( $entry["type"] )
1072 case SPH_ATTR_FLOAT
: $req .= $this->_PackFloat ( $val ); break;
1073 case SPH_ATTR_BIGINT
: $req .= sphPackI64 ( $val ); break;
1074 default: $req .= pack ( "N", $val ); break;
1080 $req .= pack ( "N", strlen($this->_select
) ) . $this->_select
;
1082 // mbstring workaround
1085 // store request to requests array
1086 $this->_reqs
[] = $req;
1087 return count($this->_reqs
)-1;
1090 /// connect to searchd, run queries batch, and return an array of result sets
1091 function RunQueries ()
1093 if ( empty($this->_reqs
) )
1095 $this->_error
= "no queries defined, issue AddQuery() first";
1099 // mbstring workaround
1102 if (!( $fp = $this->_Connect() ))
1108 // send query, get response
1109 $nreqs = count($this->_reqs
);
1110 $req = join ( "", $this->_reqs
);
1111 $len = 8+
strlen($req);
1112 $req = pack ( "nnNNN", SEARCHD_COMMAND_SEARCH
, VER_COMMAND_SEARCH
, $len, 0, $nreqs ) . $req; // add header
1114 if ( !( $this->_Send ( $fp, $req, $len+
8 ) ) ||
1115 !( $response = $this->_GetResponse ( $fp, VER_COMMAND_SEARCH
) ) )
1121 // query sent ok; we can reset reqs now
1122 $this->_reqs
= array ();
1124 // parse and return response
1125 return $this->_ParseSearchResponse ( $response, $nreqs );
1128 /// parse and return search query (or queries) response
1129 function _ParseSearchResponse ( $response, $nreqs )
1131 $p = 0; // current position
1132 $max = strlen($response); // max position for checks, to protect against broken responses
1134 $results = array ();
1135 for ( $ires=0; $ires<$nreqs && $p<$max; $ires++
)
1137 $results[] = array();
1138 $result =& $results[$ires];
1140 $result["error"] = "";
1141 $result["warning"] = "";
1144 list(,$status) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1145 $result["status"] = $status;
1146 if ( $status!=SEARCHD_OK
)
1148 list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1149 $message = substr ( $response, $p, $len ); $p +
= $len;
1151 if ( $status==SEARCHD_WARNING
)
1153 $result["warning"] = $message;
1156 $result["error"] = $message;
1165 list(,$nfields) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1166 while ( $nfields-->0 && $p<$max )
1168 list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1169 $fields[] = substr ( $response, $p, $len ); $p +
= $len;
1171 $result["fields"] = $fields;
1173 list(,$nattrs) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1174 while ( $nattrs-->0 && $p<$max )
1176 list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1177 $attr = substr ( $response, $p, $len ); $p +
= $len;
1178 list(,$type) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1179 $attrs[$attr] = $type;
1181 $result["attrs"] = $attrs;
1184 list(,$count) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1185 list(,$id64) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1189 while ( $count-->0 && $p<$max )
1191 // index into result array
1194 // parse document id and weight
1197 $doc = sphUnpackU64 ( substr ( $response, $p, 8 ) ); $p +
= 8;
1198 list(,$weight) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1202 list ( $doc, $weight ) = array_values ( unpack ( "N*N*",
1203 substr ( $response, $p, 8 ) ) );
1205 $doc = sphFixUint($doc);
1207 $weight = sprintf ( "%u", $weight );
1209 // create match entry
1210 if ( $this->_arrayresult
)
1211 $result["matches"][$idx] = array ( "id"=>$doc, "weight"=>$weight );
1213 $result["matches"][$doc]["weight"] = $weight;
1215 // parse and create attributes
1216 $attrvals = array ();
1217 foreach ( $attrs as $attr=>$type )
1219 // handle 64bit ints
1220 if ( $type==SPH_ATTR_BIGINT
)
1222 $attrvals[$attr] = sphUnpackI64 ( substr ( $response, $p, 8 ) ); $p +
= 8;
1227 if ( $type==SPH_ATTR_FLOAT
)
1229 list(,$uval) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1230 list(,$fval) = unpack ( "f*", pack ( "L", $uval ) );
1231 $attrvals[$attr] = $fval;
1235 // handle everything else as unsigned ints
1236 list(,$val) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1237 if ( $type & SPH_ATTR_MULTI
)
1239 $attrvals[$attr] = array ();
1241 while ( $nvalues-->0 && $p<$max )
1243 list(,$val) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1244 $attrvals[$attr][] = sphFixUint($val);
1246 } else if ( $type==SPH_ATTR_STRING
)
1248 $attrvals[$attr] = substr ( $response, $p, $val );
1252 $attrvals[$attr] = sphFixUint($val);
1256 if ( $this->_arrayresult
)
1257 $result["matches"][$idx]["attrs"] = $attrvals;
1259 $result["matches"][$doc]["attrs"] = $attrvals;
1262 list ( $total, $total_found, $msecs, $words ) =
1263 array_values ( unpack ( "N*N*N*N*", substr ( $response, $p, 16 ) ) );
1264 $result["total"] = sprintf ( "%u", $total );
1265 $result["total_found"] = sprintf ( "%u", $total_found );
1266 $result["time"] = sprintf ( "%.3f", $msecs/1000 );
1269 while ( $words-->0 && $p<$max )
1271 list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1272 $word = substr ( $response, $p, $len ); $p +
= $len;
1273 list ( $docs, $hits ) = array_values ( unpack ( "N*N*", substr ( $response, $p, 8 ) ) ); $p +
= 8;
1274 $result["words"][$word] = array (
1275 "docs"=>sprintf ( "%u", $docs ),
1276 "hits"=>sprintf ( "%u", $hits ) );
1284 /////////////////////////////////////////////////////////////////////////////
1285 // excerpts generation
1286 /////////////////////////////////////////////////////////////////////////////
1288 /// connect to searchd server, and generate exceprts (snippets)
1289 /// of given documents for given query. returns false on failure,
1290 /// an array of snippets on success
1291 function BuildExcerpts ( $docs, $index, $words, $opts=array() )
1293 assert ( is_array($docs) );
1294 assert ( is_string($index) );
1295 assert ( is_string($words) );
1296 assert ( is_array($opts) );
1300 if (!( $fp = $this->_Connect() ))
1310 if ( !isset($opts["before_match"]) ) $opts["before_match"] = "<b>";
1311 if ( !isset($opts["after_match"]) ) $opts["after_match"] = "</b>";
1312 if ( !isset($opts["chunk_separator"]) ) $opts["chunk_separator"] = " ... ";
1313 if ( !isset($opts["limit"]) ) $opts["limit"] = 256;
1314 if ( !isset($opts["limit_passages"]) ) $opts["limit_passages"] = 0;
1315 if ( !isset($opts["limit_words"]) ) $opts["limit_words"] = 0;
1316 if ( !isset($opts["around"]) ) $opts["around"] = 5;
1317 if ( !isset($opts["exact_phrase"]) ) $opts["exact_phrase"] = false;
1318 if ( !isset($opts["single_passage"]) ) $opts["single_passage"] = false;
1319 if ( !isset($opts["use_boundaries"]) ) $opts["use_boundaries"] = false;
1320 if ( !isset($opts["weight_order"]) ) $opts["weight_order"] = false;
1321 if ( !isset($opts["query_mode"]) ) $opts["query_mode"] = false;
1322 if ( !isset($opts["force_all_words"]) ) $opts["force_all_words"] = false;
1323 if ( !isset($opts["start_passage_id"]) ) $opts["start_passage_id"] = 1;
1324 if ( !isset($opts["load_files"]) ) $opts["load_files"] = false;
1325 if ( !isset($opts["html_strip_mode"]) ) $opts["html_strip_mode"] = "index";
1326 if ( !isset($opts["allow_empty"]) ) $opts["allow_empty"] = false;
1327 if ( !isset($opts["passage_boundary"]) ) $opts["passage_boundary"] = "none";
1328 if ( !isset($opts["emit_zones"]) ) $opts["emit_zones"] = false;
1335 $flags = 1; // remove spaces
1336 if ( $opts["exact_phrase"] ) $flags |
= 2;
1337 if ( $opts["single_passage"] ) $flags |
= 4;
1338 if ( $opts["use_boundaries"] ) $flags |
= 8;
1339 if ( $opts["weight_order"] ) $flags |
= 16;
1340 if ( $opts["query_mode"] ) $flags |
= 32;
1341 if ( $opts["force_all_words"] ) $flags |
= 64;
1342 if ( $opts["load_files"] ) $flags |
= 128;
1343 if ( $opts["allow_empty"] ) $flags |
= 256;
1344 if ( $opts["emit_zones"] ) $flags |
= 512;
1345 $req = pack ( "NN", 0, $flags ); // mode=0, flags=$flags
1346 $req .= pack ( "N", strlen($index) ) . $index; // req index
1347 $req .= pack ( "N", strlen($words) ) . $words; // req words
1350 $req .= pack ( "N", strlen($opts["before_match"]) ) . $opts["before_match"];
1351 $req .= pack ( "N", strlen($opts["after_match"]) ) . $opts["after_match"];
1352 $req .= pack ( "N", strlen($opts["chunk_separator"]) ) . $opts["chunk_separator"];
1353 $req .= pack ( "NN", (int)$opts["limit"], (int)$opts["around"] );
1354 $req .= pack ( "NNN", (int)$opts["limit_passages"], (int)$opts["limit_words"], (int)$opts["start_passage_id"] ); // v.1.2
1355 $req .= pack ( "N", strlen($opts["html_strip_mode"]) ) . $opts["html_strip_mode"];
1356 $req .= pack ( "N", strlen($opts["passage_boundary"]) ) . $opts["passage_boundary"];
1359 $req .= pack ( "N", count($docs) );
1360 foreach ( $docs as $doc )
1362 assert ( is_string($doc) );
1363 $req .= pack ( "N", strlen($doc) ) . $doc;
1366 ////////////////////////////
1367 // send query, get response
1368 ////////////////////////////
1370 $len = strlen($req);
1371 $req = pack ( "nnN", SEARCHD_COMMAND_EXCERPT
, VER_COMMAND_EXCERPT
, $len ) . $req; // add header
1372 if ( !( $this->_Send ( $fp, $req, $len+
8 ) ) ||
1373 !( $response = $this->_GetResponse ( $fp, VER_COMMAND_EXCERPT
) ) )
1385 $rlen = strlen($response);
1386 for ( $i=0; $i<count($docs); $i++
)
1388 list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) );
1391 if ( $pos+
$len > $rlen )
1393 $this->_error
= "incomplete reply";
1397 $res[] = $len ?
substr ( $response, $pos, $len ) : "";
1406 /////////////////////////////////////////////////////////////////////////////
1407 // keyword generation
1408 /////////////////////////////////////////////////////////////////////////////
1410 /// connect to searchd server, and generate keyword list for a given query
1411 /// returns false on failure,
1412 /// an array of words on success
1413 function BuildKeywords ( $query, $index, $hits )
1415 assert ( is_string($query) );
1416 assert ( is_string($index) );
1417 assert ( is_bool($hits) );
1421 if (!( $fp = $this->_Connect() ))
1432 $req = pack ( "N", strlen($query) ) . $query; // req query
1433 $req .= pack ( "N", strlen($index) ) . $index; // req index
1434 $req .= pack ( "N", (int)$hits );
1436 ////////////////////////////
1437 // send query, get response
1438 ////////////////////////////
1440 $len = strlen($req);
1441 $req = pack ( "nnN", SEARCHD_COMMAND_KEYWORDS
, VER_COMMAND_KEYWORDS
, $len ) . $req; // add header
1442 if ( !( $this->_Send ( $fp, $req, $len+
8 ) ) ||
1443 !( $response = $this->_GetResponse ( $fp, VER_COMMAND_KEYWORDS
) ) )
1455 $rlen = strlen($response);
1456 list(,$nwords) = unpack ( "N*", substr ( $response, $pos, 4 ) );
1458 for ( $i=0; $i<$nwords; $i++
)
1460 list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) ); $pos +
= 4;
1461 $tokenized = $len ?
substr ( $response, $pos, $len ) : "";
1464 list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) ); $pos +
= 4;
1465 $normalized = $len ?
substr ( $response, $pos, $len ) : "";
1468 $res[] = array ( "tokenized"=>$tokenized, "normalized"=>$normalized );
1472 list($ndocs,$nhits) = array_values ( unpack ( "N*N*", substr ( $response, $pos, 8 ) ) );
1474 $res [$i]["docs"] = $ndocs;
1475 $res [$i]["hits"] = $nhits;
1480 $this->_error
= "incomplete reply";
1490 function EscapeString ( $string )
1492 $from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=' );
1493 $to = array ( '\\\\', '\(','\)','\|','\-','\!','\@','\~','\"', '\&', '\/', '\^', '\$', '\=' );
1495 return str_replace ( $from, $to, $string );
1498 /////////////////////////////////////////////////////////////////////////////
1499 // attribute updates
1500 /////////////////////////////////////////////////////////////////////////////
1502 /// batch update given attributes in given rows in given indexes
1503 /// returns amount of updated documents (0 or more) on success, or -1 on failure
1504 function UpdateAttributes ( $index, $attrs, $values, $mva=false )
1506 // verify everything
1507 assert ( is_string($index) );
1508 assert ( is_bool($mva) );
1510 assert ( is_array($attrs) );
1511 foreach ( $attrs as $attr )
1512 assert ( is_string($attr) );
1514 assert ( is_array($values) );
1515 foreach ( $values as $id=>$entry )
1517 assert ( is_numeric($id) );
1518 assert ( is_array($entry) );
1519 assert ( count($entry)==count($attrs) );
1520 foreach ( $entry as $v )
1524 assert ( is_array($v) );
1525 foreach ( $v as $vv )
1526 assert ( is_int($vv) );
1528 assert ( is_int($v) );
1534 $req = pack ( "N", strlen($index) ) . $index;
1536 $req .= pack ( "N", count($attrs) );
1537 foreach ( $attrs as $attr )
1539 $req .= pack ( "N", strlen($attr) ) . $attr;
1540 $req .= pack ( "N", $mva ?
1 : 0 );
1543 $req .= pack ( "N", count($values) );
1544 foreach ( $values as $id=>$entry )
1546 $req .= sphPackU64 ( $id );
1547 foreach ( $entry as $v )
1549 $req .= pack ( "N", $mva ?
count($v) : $v );
1551 foreach ( $v as $vv )
1552 $req .= pack ( "N", $vv );
1556 // connect, send query, get response
1557 if (!( $fp = $this->_Connect() ))
1563 $len = strlen($req);
1564 $req = pack ( "nnN", SEARCHD_COMMAND_UPDATE
, VER_COMMAND_UPDATE
, $len ) . $req; // add header
1565 if ( !$this->_Send ( $fp, $req, $len+
8 ) )
1571 if (!( $response = $this->_GetResponse ( $fp, VER_COMMAND_UPDATE
) ))
1578 list(,$updated) = unpack ( "N*", substr ( $response, 0, 4 ) );
1583 /////////////////////////////////////////////////////////////////////////////
1584 // persistent connections
1585 /////////////////////////////////////////////////////////////////////////////
1589 if ( $this->_socket
!== false )
1591 $this->_error
= 'already connected';
1594 if ( !$fp = $this->_Connect() )
1597 // command, command version = 0, body length = 4, body = 1
1598 $req = pack ( "nnNN", SEARCHD_COMMAND_PERSIST
, 0, 4, 1 );
1599 if ( !$this->_Send ( $fp, $req, 12 ) )
1602 $this->_socket
= $fp;
1608 if ( $this->_socket
=== false )
1610 $this->_error
= 'not connected';
1614 fclose ( $this->_socket
);
1615 $this->_socket
= false;
1620 //////////////////////////////////////////////////////////////////////////
1622 //////////////////////////////////////////////////////////////////////////
1627 if (!( $fp = $this->_Connect() ))
1633 $req = pack ( "nnNN", SEARCHD_COMMAND_STATUS
, VER_COMMAND_STATUS
, 4, 1 ); // len=4, body=1
1634 if ( !( $this->_Send ( $fp, $req, 12 ) ) ||
1635 !( $response = $this->_GetResponse ( $fp, VER_COMMAND_STATUS
) ) )
1641 $res = substr ( $response, 4 ); // just ignore length, error handling, etc
1643 list ( $rows, $cols ) = array_values ( unpack ( "N*N*", substr ( $response, $p, 8 ) ) ); $p +
= 8;
1646 for ( $i=0; $i<$rows; $i++
)
1647 for ( $j=0; $j<$cols; $j++
)
1649 list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p +
= 4;
1650 $res[$i][] = substr ( $response, $p, $len ); $p +
= $len;
1657 //////////////////////////////////////////////////////////////////////////
1659 //////////////////////////////////////////////////////////////////////////
1661 function FlushAttributes ()
1664 if (!( $fp = $this->_Connect() ))
1670 $req = pack ( "nnN", SEARCHD_COMMAND_FLUSHATTRS
, VER_COMMAND_FLUSHATTRS
, 0 ); // len=0
1671 if ( !( $this->_Send ( $fp, $req, 8 ) ) ||
1672 !( $response = $this->_GetResponse ( $fp, VER_COMMAND_FLUSHATTRS
) ) )
1679 if ( strlen($response)==4 )
1680 list(,$tag) = unpack ( "N*", $response );
1682 $this->_error
= "unexpected response length";
1690 // $Id: sphinxapi.php 2758 2011-04-04 11:10:44Z kevg $