PageRenderTime 55ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/source/class/class_sphinx.php

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