sphinxapi.php 35 KB

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