sphinxapi.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  1. <?php
  2. //
  3. // $Id$
  4. //
  5. //
  6. // Copyright (c) 2001-2008, Andrew Aksyonoff. All rights reserved.
  7. //
  8. // This program is free software; you can redistribute it and/or modify
  9. // it under the terms of the GNU General Public License. You should have
  10. // received a copy of the GPL license along with this program; if you
  11. // did not, you can find it at http://www.gnu.org/
  12. //
  13. /////////////////////////////////////////////////////////////////////////////
  14. // PHP version of Sphinx searchd client (PHP API)
  15. /////////////////////////////////////////////////////////////////////////////
  16. /// known searchd commands
  17. define ( "SEARCHD_COMMAND_SEARCH", 0 );
  18. define ( "SEARCHD_COMMAND_EXCERPT", 1 );
  19. define ( "SEARCHD_COMMAND_UPDATE", 2 );
  20. define ( "SEARCHD_COMMAND_KEYWORDS",3 );
  21. /// current client-side command implementation versions
  22. define ( "VER_COMMAND_SEARCH", 0x113 );
  23. define ( "VER_COMMAND_EXCERPT", 0x100 );
  24. define ( "VER_COMMAND_UPDATE", 0x101 );
  25. define ( "VER_COMMAND_KEYWORDS", 0x100 );
  26. /// known searchd status codes
  27. define ( "SEARCHD_OK", 0 );
  28. define ( "SEARCHD_ERROR", 1 );
  29. define ( "SEARCHD_RETRY", 2 );
  30. define ( "SEARCHD_WARNING", 3 );
  31. /// known match modes
  32. define ( "SPH_MATCH_ALL", 0 );
  33. define ( "SPH_MATCH_ANY", 1 );
  34. define ( "SPH_MATCH_PHRASE", 2 );
  35. define ( "SPH_MATCH_BOOLEAN", 3 );
  36. define ( "SPH_MATCH_EXTENDED", 4 );
  37. define ( "SPH_MATCH_FULLSCAN", 5 );
  38. define ( "SPH_MATCH_EXTENDED2", 6 ); // extended engine V2 (TEMPORARY, WILL BE REMOVED)
  39. /// known ranking modes (ext2 only)
  40. define ( "SPH_RANK_PROXIMITY_BM25", 0 ); ///< default mode, phrase proximity major factor and BM25 minor one
  41. define ( "SPH_RANK_BM25", 1 ); ///< statistical mode, BM25 ranking only (faster but worse quality)
  42. define ( "SPH_RANK_NONE", 2 ); ///< no ranking, all matches get a weight of 1
  43. define ( "SPH_RANK_WORDCOUNT", 3 ); ///< simple word-count weighting, rank is a weighted sum of per-field keyword occurence counts
  44. /// known sort modes
  45. define ( "SPH_SORT_RELEVANCE", 0 );
  46. define ( "SPH_SORT_ATTR_DESC", 1 );
  47. define ( "SPH_SORT_ATTR_ASC", 2 );
  48. define ( "SPH_SORT_TIME_SEGMENTS", 3 );
  49. define ( "SPH_SORT_EXTENDED", 4 );
  50. define ( "SPH_SORT_EXPR", 5 );
  51. /// known filter types
  52. define ( "SPH_FILTER_VALUES", 0 );
  53. define ( "SPH_FILTER_RANGE", 1 );
  54. define ( "SPH_FILTER_FLOATRANGE", 2 );
  55. /// known attribute types
  56. define ( "SPH_ATTR_INTEGER", 1 );
  57. define ( "SPH_ATTR_TIMESTAMP", 2 );
  58. define ( "SPH_ATTR_ORDINAL", 3 );
  59. define ( "SPH_ATTR_BOOL", 4 );
  60. define ( "SPH_ATTR_FLOAT", 5 );
  61. define ( "SPH_ATTR_MULTI", 0x40000000 );
  62. /// known grouping functions
  63. define ( "SPH_GROUPBY_DAY", 0 );
  64. define ( "SPH_GROUPBY_WEEK", 1 );
  65. define ( "SPH_GROUPBY_MONTH", 2 );
  66. define ( "SPH_GROUPBY_YEAR", 3 );
  67. define ( "SPH_GROUPBY_ATTR", 4 );
  68. define ( "SPH_GROUPBY_ATTRPAIR", 5 );
  69. /// portably pack numeric to 64 unsigned bits, network order
  70. function sphPack64 ( $v )
  71. {
  72. assert ( is_numeric($v) );
  73. // x64 route
  74. if ( PHP_INT_SIZE>=8 )
  75. {
  76. $i = (int)$v;
  77. return pack ( "NN", $i>>32, $i&((1<<32)-1) );
  78. }
  79. // x32 route, bcmath
  80. $x = "4294967296";
  81. if ( function_exists("bcmul") )
  82. {
  83. $h = bcdiv ( $v, $x, 0 );
  84. $l = bcmod ( $v, $x );
  85. return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit
  86. }
  87. // x32 route, 15 or less decimal digits
  88. // we can use float, because its actually double and has 52 precision bits
  89. if ( strlen($v)<=15 )
  90. {
  91. $f = (float)$v;
  92. $h = (int)($f/$x);
  93. $l = (int)($f-$x*$h);
  94. return pack ( "NN", $h, $l );
  95. }
  96. // x32 route, 16 or more decimal digits
  97. // well, let me know if you *really* need this
  98. die ( "INTERNAL ERROR: packing more than 15-digit numeric on 32-bit PHP is not implemented yet (contact support)" );
  99. }
  100. /// portably unpack 64 unsigned bits, network order to numeric
  101. function sphUnpack64 ( $v )
  102. {
  103. list($h,$l) = array_values ( unpack ( "N*N*", $v ) );
  104. // x64 route
  105. if ( PHP_INT_SIZE>=8 )
  106. {
  107. if ( $h<0 ) $h += (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again
  108. if ( $l<0 ) $l += (1<<32);
  109. return ($h<<32) + $l;
  110. }
  111. // x32 route
  112. $h = sprintf ( "%u", $h );
  113. $l = sprintf ( "%u", $l );
  114. $x = "4294967296";
  115. // bcmath
  116. if ( function_exists("bcmul") )
  117. return bcadd ( $l, bcmul ( $x, $h ) );
  118. // no bcmath, 15 or less decimal digits
  119. // we can use float, because its actually double and has 52 precision bits
  120. if ( $h<1048576 )
  121. {
  122. $f = ((float)$h)*$x + (float)$l;
  123. return sprintf ( "%.0f", $f ); // builtin conversion is only about 39-40 bits precise!
  124. }
  125. // x32 route, 16 or more decimal digits
  126. // well, let me know if you *really* need this
  127. die ( "INTERNAL ERROR: unpacking more than 15-digit numeric on 32-bit PHP is not implemented yet (contact support)" );
  128. }
  129. /// sphinx searchd client class
  130. class SphinxClient
  131. {
  132. var $_host; ///< searchd host (default is "localhost")
  133. var $_port; ///< searchd port (default is 3312)
  134. var $_offset; ///< how many records to seek from result-set start (default is 0)
  135. var $_limit; ///< how many records to return from result-set starting at offset (default is 20)
  136. var $_mode; ///< query matching mode (default is SPH_MATCH_ALL)
  137. var $_weights; ///< per-field weights (default is 1 for all fields)
  138. var $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE)
  139. var $_sortby; ///< attribute to sort by (defualt is "")
  140. var $_min_id; ///< min ID to match (default is 0, which means no limit)
  141. var $_max_id; ///< max ID to match (default is 0, which means no limit)
  142. var $_filters; ///< search filters
  143. var $_groupby; ///< group-by attribute name
  144. var $_groupfunc; ///< group-by function (to pre-process group-by attribute value with)
  145. var $_groupsort; ///< group-by sorting clause (to sort groups in result set with)
  146. var $_groupdistinct;///< group-by count-distinct attribute
  147. var $_maxmatches; ///< max matches to retrieve
  148. var $_cutoff; ///< cutoff to stop searching at (default is 0)
  149. var $_retrycount; ///< distributed retries count
  150. var $_retrydelay; ///< distributed retries delay
  151. var $_anchor; ///< geographical anchor point
  152. var $_indexweights; ///< per-index weights
  153. var $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25)
  154. var $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit)
  155. var $_fieldweights; ///< per-field-name weights
  156. var $_error; ///< last error message
  157. var $_warning; ///< last warning message
  158. var $_reqs; ///< requests array for multi-query
  159. var $_mbenc; ///< stored mbstring encoding
  160. var $_arrayresult; ///< whether $result["matches"] should be a hash or an array
  161. /////////////////////////////////////////////////////////////////////////////
  162. // common stuff
  163. /////////////////////////////////////////////////////////////////////////////
  164. /// create a new client object and fill defaults
  165. function SphinxClient ()
  166. {
  167. // per-client-object settings
  168. $this->_host = "localhost";
  169. $this->_port = 3312;
  170. // per-query settings
  171. $this->_offset = 0;
  172. $this->_limit = 20;
  173. $this->_mode = SPH_MATCH_ALL;
  174. $this->_weights = array ();
  175. $this->_sort = SPH_SORT_RELEVANCE;
  176. $this->_sortby = "";
  177. $this->_min_id = 0;
  178. $this->_max_id = 0;
  179. $this->_filters = array ();
  180. $this->_groupby = "";
  181. $this->_groupfunc = SPH_GROUPBY_DAY;
  182. $this->_groupsort = "@group desc";
  183. $this->_groupdistinct= "";
  184. $this->_maxmatches = 1000;
  185. $this->_cutoff = 0;
  186. $this->_retrycount = 0;
  187. $this->_retrydelay = 0;
  188. $this->_anchor = array ();
  189. $this->_indexweights= array ();
  190. $this->_ranker = SPH_RANK_PROXIMITY_BM25;
  191. $this->_maxquerytime= 0;
  192. $this->_fieldweights= array();
  193. $this->_error = ""; // per-reply fields (for single-query case)
  194. $this->_warning = "";
  195. $this->_reqs = array (); // requests storage (for multi-query case)
  196. $this->_mbenc = "";
  197. $this->_arrayresult = false;
  198. }
  199. /// get last error message (string)
  200. function GetLastError ()
  201. {
  202. return $this->_error;
  203. }
  204. /// get last warning message (string)
  205. function GetLastWarning ()
  206. {
  207. return $this->_warning;
  208. }
  209. /// set searchd host name (string) and port (integer)
  210. function SetServer ( $host, $port )
  211. {
  212. assert ( is_string($host) );
  213. assert ( is_int($port) );
  214. $this->_host = $host;
  215. $this->_port = $port;
  216. }
  217. /////////////////////////////////////////////////////////////////////////////
  218. /// enter mbstring workaround mode
  219. function _MBPush ()
  220. {
  221. $this->_mbenc = "";
  222. if ( ini_get ( "mbstring.func_overload" ) & 2 )
  223. {
  224. $this->_mbenc = mb_internal_encoding();
  225. mb_internal_encoding ( "latin1" );
  226. }
  227. }
  228. /// leave mbstring workaround mode
  229. function _MBPop ()
  230. {
  231. if ( $this->_mbenc )
  232. mb_internal_encoding ( $this->_mbenc );
  233. }
  234. /// connect to searchd server
  235. function _Connect ()
  236. {
  237. if (!( $fp = @fsockopen ( $this->_host, $this->_port ) ) )
  238. {
  239. $this->_error = "connection to {$this->_host}:{$this->_port} failed";
  240. return false;
  241. }
  242. // check version
  243. list(,$v) = unpack ( "N*", fread ( $fp, 4 ) );
  244. $v = (int)$v;
  245. if ( $v<1 )
  246. {
  247. fclose ( $fp );
  248. $this->_error = "expected searchd protocol version 1+, got version '$v'";
  249. return false;
  250. }
  251. // all ok, send my version
  252. fwrite ( $fp, pack ( "N", 1 ) );
  253. return $fp;
  254. }
  255. /// get and check response packet from searchd server
  256. function _GetResponse ( $fp, $client_ver )
  257. {
  258. $response = "";
  259. $len = 0;
  260. $header = fread ( $fp, 8 );
  261. if ( strlen($header)==8 )
  262. {
  263. list ( $status, $ver, $len ) = array_values ( unpack ( "n2a/Nb", $header ) );
  264. $left = $len;
  265. while ( $left>0 && !feof($fp) )
  266. {
  267. $chunk = fread ( $fp, $left );
  268. if ( $chunk )
  269. {
  270. $response .= $chunk;
  271. $left -= strlen($chunk);
  272. }
  273. }
  274. }
  275. fclose ( $fp );
  276. // check response
  277. $read = strlen ( $response );
  278. if ( !$response || $read!=$len )
  279. {
  280. $this->_error = $len
  281. ? "failed to read searchd response (status=$status, ver=$ver, len=$len, read=$read)"
  282. : "received zero-sized searchd response";
  283. return false;
  284. }
  285. // check status
  286. if ( $status==SEARCHD_WARNING )
  287. {
  288. list(,$wlen) = unpack ( "N*", substr ( $response, 0, 4 ) );
  289. $this->_warning = substr ( $response, 4, $wlen );
  290. return substr ( $response, 4+$wlen );
  291. }
  292. if ( $status==SEARCHD_ERROR )
  293. {
  294. $this->_error = "searchd error: " . substr ( $response, 4 );
  295. return false;
  296. }
  297. if ( $status==SEARCHD_RETRY )
  298. {
  299. $this->_error = "temporary searchd error: " . substr ( $response, 4 );
  300. return false;
  301. }
  302. if ( $status!=SEARCHD_OK )
  303. {
  304. $this->_error = "unknown status code '$status'";
  305. return false;
  306. }
  307. // check version
  308. if ( $ver<$client_ver )
  309. {
  310. $this->_warning = sprintf ( "searchd command v.%d.%d older than client's v.%d.%d, some options might not work",
  311. $ver>>8, $ver&0xff, $client_ver>>8, $client_ver&0xff );
  312. }
  313. return $response;
  314. }
  315. /////////////////////////////////////////////////////////////////////////////
  316. // searching
  317. /////////////////////////////////////////////////////////////////////////////
  318. /// set offset and count into result set,
  319. /// and optionally set max-matches and cutoff limits
  320. function SetLimits ( $offset, $limit, $max=0, $cutoff=0 )
  321. {
  322. assert ( is_int($offset) );
  323. assert ( is_int($limit) );
  324. assert ( $offset>=0 );
  325. assert ( $limit>0 );
  326. assert ( $max>=0 );
  327. $this->_offset = $offset;
  328. $this->_limit = $limit;
  329. if ( $max>0 )
  330. $this->_maxmatches = $max;
  331. if ( $cutoff>0 )
  332. $this->_cutoff = $cutoff;
  333. }
  334. /// set maximum query time, in milliseconds, per-index
  335. /// integer, 0 means "do not limit"
  336. function SetMaxQueryTime ( $max )
  337. {
  338. assert ( is_int($max) );
  339. assert ( $max>=0 );
  340. $this->_maxquerytime = $max;
  341. }
  342. /// set matching mode
  343. function SetMatchMode ( $mode )
  344. {
  345. assert ( $mode==SPH_MATCH_ALL
  346. || $mode==SPH_MATCH_ANY
  347. || $mode==SPH_MATCH_PHRASE
  348. || $mode==SPH_MATCH_BOOLEAN
  349. || $mode==SPH_MATCH_EXTENDED
  350. || $mode==SPH_MATCH_EXTENDED2 );
  351. $this->_mode = $mode;
  352. }
  353. /// set ranking mode
  354. function SetRankingMode ( $ranker )
  355. {
  356. assert ( $ranker==SPH_RANK_PROXIMITY_BM25
  357. || $ranker==SPH_RANK_BM25
  358. || $ranker==SPH_RANK_NONE
  359. || $ranker==SPH_RANK_WORDCOUNT );
  360. $this->_ranker = $ranker;
  361. }
  362. /// set matches sorting mode
  363. function SetSortMode ( $mode, $sortby="" )
  364. {
  365. assert (
  366. $mode==SPH_SORT_RELEVANCE ||
  367. $mode==SPH_SORT_ATTR_DESC ||
  368. $mode==SPH_SORT_ATTR_ASC ||
  369. $mode==SPH_SORT_TIME_SEGMENTS ||
  370. $mode==SPH_SORT_EXTENDED ||
  371. $mode==SPH_SORT_EXPR );
  372. assert ( is_string($sortby) );
  373. assert ( $mode==SPH_SORT_RELEVANCE || strlen($sortby)>0 );
  374. $this->_sort = $mode;
  375. $this->_sortby = $sortby;
  376. }
  377. /// bind per-field weights by order
  378. /// DEPRECATED; use SetFieldWeights() instead
  379. function SetWeights ( $weights )
  380. {
  381. assert ( is_array($weights) );
  382. foreach ( $weights as $weight )
  383. assert ( is_int($weight) );
  384. $this->_weights = $weights;
  385. }
  386. /// bind per-field weights by name
  387. function SetFieldWeights ( $weights )
  388. {
  389. assert ( is_array($weights) );
  390. foreach ( $weights as $name=>$weight )
  391. {
  392. assert ( is_string($name) );
  393. assert ( is_int($weight) );
  394. }
  395. $this->_fieldweights = $weights;
  396. }
  397. /// bind per-index weights by name
  398. function SetIndexWeights ( $weights )
  399. {
  400. assert ( is_array($weights) );
  401. foreach ( $weights as $index=>$weight )
  402. {
  403. assert ( is_string($index) );
  404. assert ( is_int($weight) );
  405. }
  406. $this->_indexweights = $weights;
  407. }
  408. /// set IDs range to match
  409. /// only match records if document ID is beetwen $min and $max (inclusive)
  410. function SetIDRange ( $min, $max )
  411. {
  412. assert ( is_numeric($min) );
  413. assert ( is_numeric($max) );
  414. assert ( $min<=$max );
  415. $this->_min_id = $min;
  416. $this->_max_id = $max;
  417. }
  418. /// set values set filter
  419. /// only match records where $attribute value is in given set
  420. function SetFilter ( $attribute, $values, $exclude=false )
  421. {
  422. assert ( is_string($attribute) );
  423. assert ( is_array($values) );
  424. assert ( count($values) );
  425. if ( is_array($values) && count($values) )
  426. {
  427. foreach ( $values as $value )
  428. assert ( is_numeric($value) );
  429. $this->_filters[] = array ( "type"=>SPH_FILTER_VALUES, "attr"=>$attribute, "exclude"=>$exclude, "values"=>$values );
  430. }
  431. }
  432. /// set range filter
  433. /// only match records if $attribute value is beetwen $min and $max (inclusive)
  434. function SetFilterRange ( $attribute, $min, $max, $exclude=false )
  435. {
  436. assert ( is_string($attribute) );
  437. assert ( is_int($min) );
  438. assert ( is_int($max) );
  439. assert ( $min<=$max );
  440. $this->_filters[] = array ( "type"=>SPH_FILTER_RANGE, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max );
  441. }
  442. /// set float range filter
  443. /// only match records if $attribute value is beetwen $min and $max (inclusive)
  444. function SetFilterFloatRange ( $attribute, $min, $max, $exclude=false )
  445. {
  446. assert ( is_string($attribute) );
  447. assert ( is_float($min) );
  448. assert ( is_float($max) );
  449. assert ( $min<=$max );
  450. $this->_filters[] = array ( "type"=>SPH_FILTER_FLOATRANGE, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max );
  451. }
  452. /// setup anchor point for geosphere distance calculations
  453. /// required to use @geodist in filters and sorting
  454. /// latitude and longitude must be in radians
  455. function SetGeoAnchor ( $attrlat, $attrlong, $lat, $long )
  456. {
  457. assert ( is_string($attrlat) );
  458. assert ( is_string($attrlong) );
  459. assert ( is_float($lat) );
  460. assert ( is_float($long) );
  461. $this->_anchor = array ( "attrlat"=>$attrlat, "attrlong"=>$attrlong, "lat"=>$lat, "long"=>$long );
  462. }
  463. /// set grouping attribute and function
  464. function SetGroupBy ( $attribute, $func, $groupsort="@group desc" )
  465. {
  466. assert ( is_string($attribute) );
  467. assert ( is_string($groupsort) );
  468. assert ( $func==SPH_GROUPBY_DAY
  469. || $func==SPH_GROUPBY_WEEK
  470. || $func==SPH_GROUPBY_MONTH
  471. || $func==SPH_GROUPBY_YEAR
  472. || $func==SPH_GROUPBY_ATTR
  473. || $func==SPH_GROUPBY_ATTRPAIR );
  474. $this->_groupby = $attribute;
  475. $this->_groupfunc = $func;
  476. $this->_groupsort = $groupsort;
  477. }
  478. /// set count-distinct attribute for group-by queries
  479. function SetGroupDistinct ( $attribute )
  480. {
  481. assert ( is_string($attribute) );
  482. $this->_groupdistinct = $attribute;
  483. }
  484. /// set distributed retries count and delay
  485. function SetRetries ( $count, $delay=0 )
  486. {
  487. assert ( is_int($count) && $count>=0 );
  488. assert ( is_int($delay) && $delay>=0 );
  489. $this->_retrycount = $count;
  490. $this->_retrydelay = $delay;
  491. }
  492. /// set result set format (hash or array; hash by default)
  493. /// PHP specific; needed for group-by-MVA result sets that may contain duplicate IDs
  494. function SetArrayResult ( $arrayresult )
  495. {
  496. assert ( is_bool($arrayresult) );
  497. $this->_arrayresult = $arrayresult;
  498. }
  499. //////////////////////////////////////////////////////////////////////////////
  500. /// clear all filters (for multi-queries)
  501. function ResetFilters ()
  502. {
  503. $this->_filters = array();
  504. $this->_anchor = array();
  505. }
  506. /// clear groupby settings (for multi-queries)
  507. function ResetGroupBy ()
  508. {
  509. $this->_groupby = "";
  510. $this->_groupfunc = SPH_GROUPBY_DAY;
  511. $this->_groupsort = "@group desc";
  512. $this->_groupdistinct= "";
  513. }
  514. //////////////////////////////////////////////////////////////////////////////
  515. /// connect to searchd server, run given search query through given indexes,
  516. /// and return the search results
  517. function Query ( $query, $index="*", $comment="" )
  518. {
  519. assert ( empty($this->_reqs) );
  520. $this->AddQuery ( $query, $index, $comment );
  521. $results = $this->RunQueries ();
  522. if ( !is_array($results) )
  523. return false; // probably network error; error message should be already filled
  524. $this->_error = $results[0]["error"];
  525. $this->_warning = $results[0]["warning"];
  526. if ( $results[0]["status"]==SEARCHD_ERROR )
  527. return false;
  528. else
  529. return $results[0];
  530. }
  531. /// helper to pack floats in network byte order
  532. function _PackFloat ( $f )
  533. {
  534. $t1 = pack ( "f", $f ); // machine order
  535. list(,$t2) = unpack ( "L*", $t1 ); // int in machine order
  536. return pack ( "N", $t2 );
  537. }
  538. /// add query to multi-query batch
  539. /// returns index into results array from RunQueries() call
  540. function AddQuery ( $query, $index="*", $comment="" )
  541. {
  542. // mbstring workaround
  543. $this->_MBPush ();
  544. // build request
  545. $req = pack ( "NNNNN", $this->_offset, $this->_limit, $this->_mode, $this->_ranker, $this->_sort ); // mode and limits
  546. $req .= pack ( "N", strlen($this->_sortby) ) . $this->_sortby;
  547. $req .= pack ( "N", strlen($query) ) . $query; // query itself
  548. $req .= pack ( "N", count($this->_weights) ); // weights
  549. foreach ( $this->_weights as $weight )
  550. $req .= pack ( "N", (int)$weight );
  551. $req .= pack ( "N", strlen($index) ) . $index; // indexes
  552. $req .= pack ( "N", 1 ); // id64 range marker
  553. $req .= sphPack64 ( $this->_min_id ) . sphPack64 ( $this->_max_id ); // id64 range
  554. // filters
  555. $req .= pack ( "N", count($this->_filters) );
  556. foreach ( $this->_filters as $filter )
  557. {
  558. $req .= pack ( "N", strlen($filter["attr"]) ) . $filter["attr"];
  559. $req .= pack ( "N", $filter["type"] );
  560. switch ( $filter["type"] )
  561. {
  562. case SPH_FILTER_VALUES:
  563. $req .= pack ( "N", count($filter["values"]) );
  564. foreach ( $filter["values"] as $value )
  565. $req .= pack ( "N", floatval($value) ); // this uberhack is to workaround 32bit signed int limit on x32 platforms
  566. break;
  567. case SPH_FILTER_RANGE:
  568. $req .= pack ( "NN", $filter["min"], $filter["max"] );
  569. break;
  570. case SPH_FILTER_FLOATRANGE:
  571. $req .= $this->_PackFloat ( $filter["min"] ) . $this->_PackFloat ( $filter["max"] );
  572. break;
  573. default:
  574. assert ( 0 && "internal error: unhandled filter type" );
  575. }
  576. $req .= pack ( "N", $filter["exclude"] );
  577. }
  578. // group-by clause, max-matches count, group-sort clause, cutoff count
  579. $req .= pack ( "NN", $this->_groupfunc, strlen($this->_groupby) ) . $this->_groupby;
  580. $req .= pack ( "N", $this->_maxmatches );
  581. $req .= pack ( "N", strlen($this->_groupsort) ) . $this->_groupsort;
  582. $req .= pack ( "NNN", $this->_cutoff, $this->_retrycount, $this->_retrydelay );
  583. $req .= pack ( "N", strlen($this->_groupdistinct) ) . $this->_groupdistinct;
  584. // anchor point
  585. if ( empty($this->_anchor) )
  586. {
  587. $req .= pack ( "N", 0 );
  588. } else
  589. {
  590. $a =& $this->_anchor;
  591. $req .= pack ( "N", 1 );
  592. $req .= pack ( "N", strlen($a["attrlat"]) ) . $a["attrlat"];
  593. $req .= pack ( "N", strlen($a["attrlong"]) ) . $a["attrlong"];
  594. $req .= $this->_PackFloat ( $a["lat"] ) . $this->_PackFloat ( $a["long"] );
  595. }
  596. // per-index weights
  597. $req .= pack ( "N", count($this->_indexweights) );
  598. foreach ( $this->_indexweights as $idx=>$weight )
  599. $req .= pack ( "N", strlen($idx) ) . $idx . pack ( "N", $weight );
  600. // max query time
  601. $req .= pack ( "N", $this->_maxquerytime );
  602. // per-field weights
  603. $req .= pack ( "N", count($this->_fieldweights) );
  604. foreach ( $this->_fieldweights as $field=>$weight )
  605. $req .= pack ( "N", strlen($field) ) . $field . pack ( "N", $weight );
  606. // comment
  607. $req .= pack ( "N", strlen($comment) ) . $comment;
  608. // mbstring workaround
  609. $this->_MBPop ();
  610. // store request to requests array
  611. $this->_reqs[] = $req;
  612. return count($this->_reqs)-1;
  613. }
  614. /// connect to searchd, run queries batch, and return an array of result sets
  615. function RunQueries ()
  616. {
  617. if ( empty($this->_reqs) )
  618. {
  619. $this->_error = "no queries defined, issue AddQuery() first";
  620. return false;
  621. }
  622. // mbstring workaround
  623. $this->_MBPush ();
  624. if (!( $fp = $this->_Connect() ))
  625. {
  626. $this->_MBPop ();
  627. return false;
  628. }
  629. ////////////////////////////
  630. // send query, get response
  631. ////////////////////////////
  632. $nreqs = count($this->_reqs);
  633. $req = join ( "", $this->_reqs );
  634. $len = 4+strlen($req);
  635. $req = pack ( "nnNN", SEARCHD_COMMAND_SEARCH, VER_COMMAND_SEARCH, $len, $nreqs ) . $req; // add header
  636. fwrite ( $fp, $req, $len+8 );
  637. if (!( $response = $this->_GetResponse ( $fp, VER_COMMAND_SEARCH ) ))
  638. {
  639. $this->_MBPop ();
  640. return false;
  641. }
  642. $this->_reqs = array ();
  643. //////////////////
  644. // parse response
  645. //////////////////
  646. $p = 0; // current position
  647. $max = strlen($response); // max position for checks, to protect against broken responses
  648. $results = array ();
  649. for ( $ires=0; $ires<$nreqs && $p<$max; $ires++ )
  650. {
  651. $results[] = array();
  652. $result =& $results[$ires];
  653. $result["error"] = "";
  654. $result["warning"] = "";
  655. // extract status
  656. list(,$status) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  657. $result["status"] = $status;
  658. if ( $status!=SEARCHD_OK )
  659. {
  660. list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  661. $message = substr ( $response, $p, $len ); $p += $len;
  662. if ( $status==SEARCHD_WARNING )
  663. {
  664. $result["warning"] = $message;
  665. } else
  666. {
  667. $result["error"] = $message;
  668. continue;
  669. }
  670. }
  671. // read schema
  672. $fields = array ();
  673. $attrs = array ();
  674. list(,$nfields) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  675. while ( $nfields-->0 && $p<$max )
  676. {
  677. list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  678. $fields[] = substr ( $response, $p, $len ); $p += $len;
  679. }
  680. $result["fields"] = $fields;
  681. list(,$nattrs) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  682. while ( $nattrs-->0 && $p<$max )
  683. {
  684. list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  685. $attr = substr ( $response, $p, $len ); $p += $len;
  686. list(,$type) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  687. $attrs[$attr] = $type;
  688. }
  689. $result["attrs"] = $attrs;
  690. // read match count
  691. list(,$count) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  692. list(,$id64) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  693. // read matches
  694. $idx = -1;
  695. while ( $count-->0 && $p<$max )
  696. {
  697. // index into result array
  698. $idx++;
  699. // parse document id and weight
  700. if ( $id64 )
  701. {
  702. $doc = sphUnpack64 ( substr ( $response, $p, 8 ) ); $p += 8;
  703. list(,$weight) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  704. } else
  705. {
  706. list ( $doc, $weight ) = array_values ( unpack ( "N*N*",
  707. substr ( $response, $p, 8 ) ) );
  708. $p += 8;
  709. if ( PHP_INT_SIZE>=8 )
  710. {
  711. // x64 route, workaround broken unpack() in 5.2.2+
  712. if ( $doc<0 ) $doc += (1<<32);
  713. } else
  714. {
  715. // x32 route, workaround php signed/unsigned braindamage
  716. $doc = sprintf ( "%u", $doc );
  717. }
  718. }
  719. $weight = sprintf ( "%u", $weight );
  720. // create match entry
  721. if ( $this->_arrayresult )
  722. $result["matches"][$idx] = array ( "id"=>$doc, "weight"=>$weight );
  723. else
  724. $result["matches"][$doc]["weight"] = $weight;
  725. // parse and create attributes
  726. $attrvals = array ();
  727. foreach ( $attrs as $attr=>$type )
  728. {
  729. // handle floats
  730. if ( $type==SPH_ATTR_FLOAT )
  731. {
  732. list(,$uval) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  733. list(,$fval) = unpack ( "f*", pack ( "L", $uval ) );
  734. $attrvals[$attr] = $fval;
  735. continue;
  736. }
  737. // handle everything else as unsigned ints
  738. list(,$val) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  739. if ( $type & SPH_ATTR_MULTI )
  740. {
  741. $attrvals[$attr] = array ();
  742. $nvalues = $val;
  743. while ( $nvalues-->0 && $p<$max )
  744. {
  745. list(,$val) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  746. $attrvals[$attr][] = sprintf ( "%u", $val );
  747. }
  748. } else
  749. {
  750. $attrvals[$attr] = sprintf ( "%u", $val );
  751. }
  752. }
  753. if ( $this->_arrayresult )
  754. $result["matches"][$idx]["attrs"] = $attrvals;
  755. else
  756. $result["matches"][$doc]["attrs"] = $attrvals;
  757. }
  758. list ( $total, $total_found, $msecs, $words ) =
  759. array_values ( unpack ( "N*N*N*N*", substr ( $response, $p, 16 ) ) );
  760. $result["total"] = sprintf ( "%u", $total );
  761. $result["total_found"] = sprintf ( "%u", $total_found );
  762. $result["time"] = sprintf ( "%.3f", $msecs/1000 );
  763. $p += 16;
  764. while ( $words-->0 && $p<$max )
  765. {
  766. list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  767. $word = substr ( $response, $p, $len ); $p += $len;
  768. list ( $docs, $hits ) = array_values ( unpack ( "N*N*", substr ( $response, $p, 8 ) ) ); $p += 8;
  769. $result["words"][$word] = array (
  770. "docs"=>sprintf ( "%u", $docs ),
  771. "hits"=>sprintf ( "%u", $hits ) );
  772. }
  773. }
  774. $this->_MBPop ();
  775. return $results;
  776. }
  777. /////////////////////////////////////////////////////////////////////////////
  778. // excerpts generation
  779. /////////////////////////////////////////////////////////////////////////////
  780. /// connect to searchd server, and generate exceprts (snippets)
  781. /// of given documents for given query. returns false on failure,
  782. /// an array of snippets on success
  783. function BuildExcerpts ( $docs, $index, $words, $opts=array() )
  784. {
  785. assert ( is_array($docs) );
  786. assert ( is_string($index) );
  787. assert ( is_string($words) );
  788. assert ( is_array($opts) );
  789. $this->_MBPush ();
  790. if (!( $fp = $this->_Connect() ))
  791. {
  792. $this->_MBPop();
  793. return false;
  794. }
  795. /////////////////
  796. // fixup options
  797. /////////////////
  798. if ( !isset($opts["before_match"]) ) $opts["before_match"] = "<b>";
  799. if ( !isset($opts["after_match"]) ) $opts["after_match"] = "</b>";
  800. if ( !isset($opts["chunk_separator"]) ) $opts["chunk_separator"] = " ... ";
  801. if ( !isset($opts["limit"]) ) $opts["limit"] = 256;
  802. if ( !isset($opts["around"]) ) $opts["around"] = 5;
  803. if ( !isset($opts["exact_phrase"]) ) $opts["exact_phrase"] = false;
  804. if ( !isset($opts["single_passage"]) ) $opts["single_passage"] = false;
  805. if ( !isset($opts["use_boundaries"]) ) $opts["use_boundaries"] = false;
  806. if ( !isset($opts["weight_order"]) ) $opts["weight_order"] = false;
  807. /////////////////
  808. // build request
  809. /////////////////
  810. // v.1.0 req
  811. $flags = 1; // remove spaces
  812. if ( $opts["exact_phrase"] ) $flags |= 2;
  813. if ( $opts["single_passage"] ) $flags |= 4;
  814. if ( $opts["use_boundaries"] ) $flags |= 8;
  815. if ( $opts["weight_order"] ) $flags |= 16;
  816. $req = pack ( "NN", 0, $flags ); // mode=0, flags=$flags
  817. $req .= pack ( "N", strlen($index) ) . $index; // req index
  818. $req .= pack ( "N", strlen($words) ) . $words; // req words
  819. // options
  820. $req .= pack ( "N", strlen($opts["before_match"]) ) . $opts["before_match"];
  821. $req .= pack ( "N", strlen($opts["after_match"]) ) . $opts["after_match"];
  822. $req .= pack ( "N", strlen($opts["chunk_separator"]) ) . $opts["chunk_separator"];
  823. $req .= pack ( "N", (int)$opts["limit"] );
  824. $req .= pack ( "N", (int)$opts["around"] );
  825. // documents
  826. $req .= pack ( "N", count($docs) );
  827. foreach ( $docs as $doc )
  828. {
  829. assert ( is_string($doc) );
  830. $req .= pack ( "N", strlen($doc) ) . $doc;
  831. }
  832. ////////////////////////////
  833. // send query, get response
  834. ////////////////////////////
  835. $len = strlen($req);
  836. $req = pack ( "nnN", SEARCHD_COMMAND_EXCERPT, VER_COMMAND_EXCERPT, $len ) . $req; // add header
  837. $wrote = fwrite ( $fp, $req, $len+8 );
  838. if (!( $response = $this->_GetResponse ( $fp, VER_COMMAND_EXCERPT ) ))
  839. {
  840. $this->_MBPop ();
  841. return false;
  842. }
  843. //////////////////
  844. // parse response
  845. //////////////////
  846. $pos = 0;
  847. $res = array ();
  848. $rlen = strlen($response);
  849. for ( $i=0; $i<count($docs); $i++ )
  850. {
  851. list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) );
  852. $pos += 4;
  853. if ( $pos+$len > $rlen )
  854. {
  855. $this->_error = "incomplete reply";
  856. $this->_MBPop ();
  857. return false;
  858. }
  859. $res[] = $len ? substr ( $response, $pos, $len ) : "";
  860. $pos += $len;
  861. }
  862. $this->_MBPop ();
  863. return $res;
  864. }
  865. /////////////////////////////////////////////////////////////////////////////
  866. // keyword generation
  867. /////////////////////////////////////////////////////////////////////////////
  868. /// connect to searchd server, and generate keyword list for a given query
  869. /// returns false on failure,
  870. /// an array of words on success
  871. function BuildKeywords ( $query, $index, $hits )
  872. {
  873. assert ( is_string($query) );
  874. assert ( is_string($index) );
  875. assert ( is_bool($hits) );
  876. $this->_MBPush ();
  877. if (!( $fp = $this->_Connect() ))
  878. {
  879. $this->_MBPop();
  880. return false;
  881. }
  882. /////////////////
  883. // build request
  884. /////////////////
  885. // v.1.0 req
  886. $req = pack ( "N", strlen($query) ) . $query; // req query
  887. $req .= pack ( "N", strlen($index) ) . $index; // req index
  888. $req .= pack ( "N", (int)$hits );
  889. ////////////////////////////
  890. // send query, get response
  891. ////////////////////////////
  892. $len = strlen($req);
  893. $req = pack ( "nnN", SEARCHD_COMMAND_KEYWORDS, VER_COMMAND_KEYWORDS, $len ) . $req; // add header
  894. $wrote = fwrite ( $fp, $req, $len+8 );
  895. if (!( $response = $this->_GetResponse ( $fp, VER_COMMAND_KEYWORDS ) ))
  896. {
  897. $this->_MBPop ();
  898. return false;
  899. }
  900. //////////////////
  901. // parse response
  902. //////////////////
  903. $pos = 0;
  904. $res = array ();
  905. $rlen = strlen($response);
  906. list(,$nwords) = unpack ( "N*", substr ( $response, $pos, 4 ) );
  907. $pos += 4;
  908. for ( $i=0; $i<$nwords; $i++ )
  909. {
  910. list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) ); $pos += 4;
  911. $tokenized = $len ? substr ( $response, $pos, $len ) : "";
  912. $pos += $len;
  913. list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) ); $pos += 4;
  914. $normalized = $len ? substr ( $response, $pos, $len ) : "";
  915. $pos += $len;
  916. $res[] = array ( "tokenized"=>$tokenized, "normalized"=>$normalized );
  917. if ( $hits )
  918. {
  919. list($ndocs,$nhits) = array_values ( unpack ( "N*N*", substr ( $response, $pos, 8 ) ) );
  920. $pos += 8;
  921. $res [$i]["docs"] = $ndocs;
  922. $res [$i]["hits"] = $nhits;
  923. }
  924. if ( $pos > $rlen )
  925. {
  926. $this->_error = "incomplete reply";
  927. $this->_MBPop ();
  928. return false;
  929. }
  930. }
  931. $this->_MBPop ();
  932. return $res;
  933. }
  934. function EscapeString ( $string )
  935. {
  936. $from = array ( '(',')','|','-','!','@','~','\"','&' );
  937. $to = array ( '\\(','\\)','\\|','\\-','\\!','\\@','\\~','\\\"', '\\&' );
  938. return str_replace ( $from, $to, $string );
  939. }
  940. /////////////////////////////////////////////////////////////////////////////
  941. // attribute updates
  942. /////////////////////////////////////////////////////////////////////////////
  943. /// update given attribute values on given documents in given indexes
  944. /// returns amount of updated documents (0 or more) on success, or -1 on failure
  945. function UpdateAttributes ( $index, $attrs, $values )
  946. {
  947. // verify everything
  948. assert ( is_string($index) );
  949. assert ( is_array($attrs) );
  950. foreach ( $attrs as $attr )
  951. assert ( is_string($attr) );
  952. assert ( is_array($values) );
  953. foreach ( $values as $id=>$entry )
  954. {
  955. assert ( is_numeric($id) );
  956. assert ( is_array($entry) );
  957. assert ( count($entry)==count($attrs) );
  958. foreach ( $entry as $v )
  959. assert ( is_int($v) );
  960. }
  961. // build request
  962. $req = pack ( "N", strlen($index) ) . $index;
  963. $req .= pack ( "N", count($attrs) );
  964. foreach ( $attrs as $attr )
  965. $req .= pack ( "N", strlen($attr) ) . $attr;
  966. $req .= pack ( "N", count($values) );
  967. foreach ( $values as $id=>$entry )
  968. {
  969. $req .= sphPack64 ( $id );
  970. foreach ( $entry as $v )
  971. $req .= pack ( "N", $v );
  972. }
  973. // mbstring workaround
  974. $this->_MBPush ();
  975. // connect, send query, get response
  976. if (!( $fp = $this->_Connect() ))
  977. {
  978. $this->_MBPop ();
  979. return -1;
  980. }
  981. $len = strlen($req);
  982. $req = pack ( "nnN", SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, $len ) . $req; // add header
  983. fwrite ( $fp, $req, $len+8 );
  984. if (!( $response = $this->_GetResponse ( $fp, VER_COMMAND_UPDATE ) ))
  985. {
  986. $this->_MBPop ();
  987. return -1;
  988. }
  989. // parse response
  990. list(,$updated) = unpack ( "N*", substr ( $response, 0, 4 ) );
  991. $this->_MBPop ();
  992. return $updated;
  993. }
  994. }
  995. //
  996. // $Id$
  997. //
  998. ?>