sphinxapi.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  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. /////////////////////////////////////////////////////////////////////////////
  935. // attribute updates
  936. /////////////////////////////////////////////////////////////////////////////
  937. /// update given attribute values on given documents in given indexes
  938. /// returns amount of updated documents (0 or more) on success, or -1 on failure
  939. function UpdateAttributes ( $index, $attrs, $values )
  940. {
  941. // verify everything
  942. assert ( is_string($index) );
  943. assert ( is_array($attrs) );
  944. foreach ( $attrs as $attr )
  945. assert ( is_string($attr) );
  946. assert ( is_array($values) );
  947. foreach ( $values as $id=>$entry )
  948. {
  949. assert ( is_numeric($id) );
  950. assert ( is_array($entry) );
  951. assert ( count($entry)==count($attrs) );
  952. foreach ( $entry as $v )
  953. assert ( is_int($v) );
  954. }
  955. // build request
  956. $req = pack ( "N", strlen($index) ) . $index;
  957. $req .= pack ( "N", count($attrs) );
  958. foreach ( $attrs as $attr )
  959. $req .= pack ( "N", strlen($attr) ) . $attr;
  960. $req .= pack ( "N", count($values) );
  961. foreach ( $values as $id=>$entry )
  962. {
  963. $req .= sphPack64 ( $id );
  964. foreach ( $entry as $v )
  965. $req .= pack ( "N", $v );
  966. }
  967. // mbstring workaround
  968. $this->_MBPush ();
  969. // connect, send query, get response
  970. if (!( $fp = $this->_Connect() ))
  971. {
  972. $this->_MBPop ();
  973. return -1;
  974. }
  975. $len = strlen($req);
  976. $req = pack ( "nnN", SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, $len ) . $req; // add header
  977. fwrite ( $fp, $req, $len+8 );
  978. if (!( $response = $this->_GetResponse ( $fp, VER_COMMAND_UPDATE ) ))
  979. {
  980. $this->_MBPop ();
  981. return -1;
  982. }
  983. // parse response
  984. list(,$updated) = unpack ( "N*", substr ( $response, 0, 4 ) );
  985. $this->_MBPop ();
  986. return $updated;
  987. }
  988. }
  989. //
  990. // $Id$
  991. //
  992. ?>