sphinxapi.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  1. <?php
  2. //
  3. // $Id$
  4. //
  5. //
  6. // Copyright (c) 2001-2015, Andrew Aksyonoff
  7. // Copyright (c) 2008-2015, 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 Library General Public License. You should
  12. // have received a copy of the LGPL license along with this program; if you
  13. // did not, you can find it at http://www.gnu.org/
  14. //
  15. // WARNING!!!
  16. //
  17. // As of 2015, we strongly recommend to use either SphinxQL or REST APIs
  18. // rather than the native SphinxAPI.
  19. //
  20. // While both the native SphinxAPI protocol and the existing APIs will
  21. // continue to exist, and perhaps should not even break (too much), exposing
  22. // all the new features via multiple different native API implementations
  23. // is too much of a support complication for us.
  24. //
  25. // That said, you're welcome to overtake the maintenance of any given
  26. // official API, and remove this warning ;)
  27. //
  28. /////////////////////////////////////////////////////////////////////////////
  29. // PHP version of Sphinx searchd client (PHP API)
  30. /////////////////////////////////////////////////////////////////////////////
  31. /// known searchd commands
  32. define ( "SEARCHD_COMMAND_SEARCH", 0 );
  33. define ( "SEARCHD_COMMAND_EXCERPT", 1 );
  34. define ( "SEARCHD_COMMAND_UPDATE", 2 );
  35. define ( "SEARCHD_COMMAND_KEYWORDS", 3 );
  36. define ( "SEARCHD_COMMAND_PERSIST", 4 );
  37. define ( "SEARCHD_COMMAND_STATUS", 5 );
  38. define ( "SEARCHD_COMMAND_FLUSHATTRS", 7 );
  39. /// current client-side command implementation versions
  40. define ( "VER_COMMAND_SEARCH", 0x11E );
  41. define ( "VER_COMMAND_EXCERPT", 0x104 );
  42. define ( "VER_COMMAND_UPDATE", 0x103 );
  43. define ( "VER_COMMAND_KEYWORDS", 0x100 );
  44. define ( "VER_COMMAND_STATUS", 0x101 );
  45. define ( "VER_COMMAND_QUERY", 0x100 );
  46. define ( "VER_COMMAND_FLUSHATTRS", 0x100 );
  47. /// known searchd status codes
  48. define ( "SEARCHD_OK", 0 );
  49. define ( "SEARCHD_ERROR", 1 );
  50. define ( "SEARCHD_RETRY", 2 );
  51. define ( "SEARCHD_WARNING", 3 );
  52. /// known match modes
  53. define ( "SPH_MATCH_ALL", 0 );
  54. define ( "SPH_MATCH_ANY", 1 );
  55. define ( "SPH_MATCH_PHRASE", 2 );
  56. define ( "SPH_MATCH_BOOLEAN", 3 );
  57. define ( "SPH_MATCH_EXTENDED", 4 );
  58. define ( "SPH_MATCH_FULLSCAN", 5 );
  59. define ( "SPH_MATCH_EXTENDED2", 6 ); // extended engine V2 (TEMPORARY, WILL BE REMOVED)
  60. /// known ranking modes (ext2 only)
  61. define ( "SPH_RANK_PROXIMITY_BM25", 0 ); ///< default mode, phrase proximity major factor and BM25 minor one
  62. define ( "SPH_RANK_BM25", 1 ); ///< statistical mode, BM25 ranking only (faster but worse quality)
  63. define ( "SPH_RANK_NONE", 2 ); ///< no ranking, all matches get a weight of 1
  64. define ( "SPH_RANK_WORDCOUNT", 3 ); ///< simple word-count weighting, rank is a weighted sum of per-field keyword occurence counts
  65. define ( "SPH_RANK_PROXIMITY", 4 );
  66. define ( "SPH_RANK_MATCHANY", 5 );
  67. define ( "SPH_RANK_FIELDMASK", 6 );
  68. define ( "SPH_RANK_SPH04", 7 );
  69. define ( "SPH_RANK_EXPR", 8 );
  70. define ( "SPH_RANK_TOTAL", 9 );
  71. /// known sort modes
  72. define ( "SPH_SORT_RELEVANCE", 0 );
  73. define ( "SPH_SORT_ATTR_DESC", 1 );
  74. define ( "SPH_SORT_ATTR_ASC", 2 );
  75. define ( "SPH_SORT_TIME_SEGMENTS", 3 );
  76. define ( "SPH_SORT_EXTENDED", 4 );
  77. define ( "SPH_SORT_EXPR", 5 );
  78. /// known filter types
  79. define ( "SPH_FILTER_VALUES", 0 );
  80. define ( "SPH_FILTER_RANGE", 1 );
  81. define ( "SPH_FILTER_FLOATRANGE", 2 );
  82. define ( "SPH_FILTER_STRING", 3 );
  83. /// known attribute types
  84. define ( "SPH_ATTR_INTEGER", 1 );
  85. define ( "SPH_ATTR_TIMESTAMP", 2 );
  86. define ( "SPH_ATTR_ORDINAL", 3 );
  87. define ( "SPH_ATTR_BOOL", 4 );
  88. define ( "SPH_ATTR_FLOAT", 5 );
  89. define ( "SPH_ATTR_BIGINT", 6 );
  90. define ( "SPH_ATTR_STRING", 7 );
  91. define ( "SPH_ATTR_FACTORS", 1001 );
  92. define ( "SPH_ATTR_MULTI", 0x40000001 );
  93. define ( "SPH_ATTR_MULTI64", 0x40000002 );
  94. /// known grouping functions
  95. define ( "SPH_GROUPBY_DAY", 0 );
  96. define ( "SPH_GROUPBY_WEEK", 1 );
  97. define ( "SPH_GROUPBY_MONTH", 2 );
  98. define ( "SPH_GROUPBY_YEAR", 3 );
  99. define ( "SPH_GROUPBY_ATTR", 4 );
  100. define ( "SPH_GROUPBY_ATTRPAIR", 5 );
  101. // important properties of PHP's integers:
  102. // - always signed (one bit short of PHP_INT_SIZE)
  103. // - conversion from string to int is saturated
  104. // - float is double
  105. // - div converts arguments to floats
  106. // - mod converts arguments to ints
  107. // the packing code below works as follows:
  108. // - when we got an int, just pack it
  109. // if performance is a problem, this is the branch users should aim for
  110. //
  111. // - otherwise, we got a number in string form
  112. // this might be due to different reasons, but we assume that this is
  113. // because it didn't fit into PHP int
  114. //
  115. // - factor the string into high and low ints for packing
  116. // - if we have bcmath, then it is used
  117. // - if we don't, we have to do it manually (this is the fun part)
  118. //
  119. // - x64 branch does factoring using ints
  120. // - x32 (ab)uses floats, since we can't fit unsigned 32-bit number into an int
  121. //
  122. // unpacking routines are pretty much the same.
  123. // - return ints if we can
  124. // - otherwise format number into a string
  125. /// pack 64-bit signed
  126. function sphPackI64 ( $v )
  127. {
  128. assert ( is_numeric($v) );
  129. // x64
  130. if ( PHP_INT_SIZE>=8 )
  131. {
  132. $v = (int)$v;
  133. return pack ( "NN", $v>>32, $v&0xFFFFFFFF );
  134. }
  135. // x32, int
  136. if ( is_int($v) )
  137. return pack ( "NN", $v < 0 ? -1 : 0, $v );
  138. // x32, bcmath
  139. if ( function_exists("bcmul") )
  140. {
  141. if ( bccomp ( $v, 0 ) == -1 )
  142. $v = bcadd ( "18446744073709551616", $v );
  143. $h = bcdiv ( $v, "4294967296", 0 );
  144. $l = bcmod ( $v, "4294967296" );
  145. return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit
  146. }
  147. // x32, no-bcmath
  148. $p = max(0, strlen($v) - 13);
  149. $lo = abs((float)substr($v, $p));
  150. $hi = abs((float)substr($v, 0, $p));
  151. $m = $lo + $hi*1316134912.0; // (10 ^ 13) % (1 << 32) = 1316134912
  152. $q = floor($m/4294967296.0);
  153. $l = $m - ($q*4294967296.0);
  154. $h = $hi*2328.0 + $q; // (10 ^ 13) / (1 << 32) = 2328
  155. if ( $v<0 )
  156. {
  157. if ( $l==0 )
  158. $h = 4294967296.0 - $h;
  159. else
  160. {
  161. $h = 4294967295.0 - $h;
  162. $l = 4294967296.0 - $l;
  163. }
  164. }
  165. return pack ( "NN", $h, $l );
  166. }
  167. /// pack 64-bit unsigned
  168. function sphPackU64 ( $v )
  169. {
  170. assert ( is_numeric($v) );
  171. // x64
  172. if ( PHP_INT_SIZE>=8 )
  173. {
  174. assert ( $v>=0 );
  175. // x64, int
  176. if ( is_int($v) )
  177. return pack ( "NN", $v>>32, $v&0xFFFFFFFF );
  178. // x64, bcmath
  179. if ( function_exists("bcmul") )
  180. {
  181. $h = bcdiv ( $v, 4294967296, 0 );
  182. $l = bcmod ( $v, 4294967296 );
  183. return pack ( "NN", $h, $l );
  184. }
  185. // x64, no-bcmath
  186. $p = max ( 0, strlen($v) - 13 );
  187. $lo = (int)substr ( $v, $p );
  188. $hi = (int)substr ( $v, 0, $p );
  189. $m = $lo + $hi*1316134912;
  190. $l = $m % 4294967296;
  191. $h = $hi*2328 + (int)($m/4294967296);
  192. return pack ( "NN", $h, $l );
  193. }
  194. // x32, int
  195. if ( is_int($v) )
  196. return pack ( "NN", 0, $v );
  197. // x32, bcmath
  198. if ( function_exists("bcmul") )
  199. {
  200. $h = bcdiv ( $v, "4294967296", 0 );
  201. $l = bcmod ( $v, "4294967296" );
  202. return pack ( "NN", (float)$h, (float)$l ); // conversion to float is intentional; int would lose 31st bit
  203. }
  204. // x32, no-bcmath
  205. $p = max(0, strlen($v) - 13);
  206. $lo = (float)substr($v, $p);
  207. $hi = (float)substr($v, 0, $p);
  208. $m = $lo + $hi*1316134912.0;
  209. $q = floor($m / 4294967296.0);
  210. $l = $m - ($q * 4294967296.0);
  211. $h = $hi*2328.0 + $q;
  212. return pack ( "NN", $h, $l );
  213. }
  214. // unpack 64-bit unsigned
  215. function sphUnpackU64 ( $v )
  216. {
  217. list ( $hi, $lo ) = array_values ( unpack ( "N*N*", $v ) );
  218. if ( PHP_INT_SIZE>=8 )
  219. {
  220. if ( $hi<0 ) $hi += (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again
  221. if ( $lo<0 ) $lo += (1<<32);
  222. // x64, int
  223. if ( $hi<=2147483647 )
  224. return ($hi<<32) + $lo;
  225. // x64, bcmath
  226. if ( function_exists("bcmul") )
  227. return bcadd ( $lo, bcmul ( $hi, "4294967296" ) );
  228. // x64, no-bcmath
  229. $C = 100000;
  230. $h = ((int)($hi / $C) << 32) + (int)($lo / $C);
  231. $l = (($hi % $C) << 32) + ($lo % $C);
  232. if ( $l>$C )
  233. {
  234. $h += (int)($l / $C);
  235. $l = $l % $C;
  236. }
  237. if ( $h==0 )
  238. return $l;
  239. return sprintf ( "%d%05d", $h, $l );
  240. }
  241. // x32, int
  242. if ( $hi==0 )
  243. {
  244. if ( $lo>0 )
  245. return $lo;
  246. return sprintf ( "%u", $lo );
  247. }
  248. $hi = sprintf ( "%u", $hi );
  249. $lo = sprintf ( "%u", $lo );
  250. // x32, bcmath
  251. if ( function_exists("bcmul") )
  252. return bcadd ( $lo, bcmul ( $hi, "4294967296" ) );
  253. // x32, no-bcmath
  254. $hi = (float)$hi;
  255. $lo = (float)$lo;
  256. $q = floor($hi/10000000.0);
  257. $r = $hi - $q*10000000.0;
  258. $m = $lo + $r*4967296.0;
  259. $mq = floor($m/10000000.0);
  260. $l = $m - $mq*10000000.0;
  261. $h = $q*4294967296.0 + $r*429.0 + $mq;
  262. $h = sprintf ( "%.0f", $h );
  263. $l = sprintf ( "%07.0f", $l );
  264. if ( $h=="0" )
  265. return sprintf( "%.0f", (float)$l );
  266. return $h . $l;
  267. }
  268. // unpack 64-bit signed
  269. function sphUnpackI64 ( $v )
  270. {
  271. list ( $hi, $lo ) = array_values ( unpack ( "N*N*", $v ) );
  272. // x64
  273. if ( PHP_INT_SIZE>=8 )
  274. {
  275. if ( $hi<0 ) $hi += (1<<32); // because php 5.2.2 to 5.2.5 is totally fucked up again
  276. if ( $lo<0 ) $lo += (1<<32);
  277. return ($hi<<32) + $lo;
  278. }
  279. // x32, int
  280. if ( $hi==0 )
  281. {
  282. if ( $lo>0 )
  283. return $lo;
  284. return sprintf ( "%u", $lo );
  285. }
  286. // x32, int
  287. elseif ( $hi==-1 )
  288. {
  289. if ( $lo<0 )
  290. return $lo;
  291. return sprintf ( "%.0f", $lo - 4294967296.0 );
  292. }
  293. $neg = "";
  294. $c = 0;
  295. if ( $hi<0 )
  296. {
  297. $hi = ~$hi;
  298. $lo = ~$lo;
  299. $c = 1;
  300. $neg = "-";
  301. }
  302. $hi = sprintf ( "%u", $hi );
  303. $lo = sprintf ( "%u", $lo );
  304. // x32, bcmath
  305. if ( function_exists("bcmul") )
  306. return $neg . bcadd ( bcadd ( $lo, bcmul ( $hi, "4294967296" ) ), $c );
  307. // x32, no-bcmath
  308. $hi = (float)$hi;
  309. $lo = (float)$lo;
  310. $q = floor($hi/10000000.0);
  311. $r = $hi - $q*10000000.0;
  312. $m = $lo + $r*4967296.0;
  313. $mq = floor($m/10000000.0);
  314. $l = $m - $mq*10000000.0 + $c;
  315. $h = $q*4294967296.0 + $r*429.0 + $mq;
  316. if ( $l==10000000 )
  317. {
  318. $l = 0;
  319. $h += 1;
  320. }
  321. $h = sprintf ( "%.0f", $h );
  322. $l = sprintf ( "%07.0f", $l );
  323. if ( $h=="0" )
  324. return $neg . sprintf( "%.0f", (float)$l );
  325. return $neg . $h . $l;
  326. }
  327. function sphFixUint ( $value )
  328. {
  329. if ( PHP_INT_SIZE>=8 )
  330. {
  331. // x64 route, workaround broken unpack() in 5.2.2+
  332. if ( $value<0 ) $value += (1<<32);
  333. return $value;
  334. }
  335. else
  336. {
  337. // x32 route, workaround php signed/unsigned braindamage
  338. return sprintf ( "%u", $value );
  339. }
  340. }
  341. function sphSetBit ( $flag, $bit, $on )
  342. {
  343. if ( $on )
  344. {
  345. $flag |= ( 1<<$bit );
  346. } else
  347. {
  348. $reset = 16777215 ^ ( 1<<$bit );
  349. $flag = $flag & $reset;
  350. }
  351. return $flag;
  352. }
  353. /// sphinx searchd client class
  354. class SphinxClient
  355. {
  356. var $_host; ///< searchd host (default is "localhost")
  357. var $_port; ///< searchd port (default is 9312)
  358. var $_offset; ///< how many records to seek from result-set start (default is 0)
  359. var $_limit; ///< how many records to return from result-set starting at offset (default is 20)
  360. var $_mode; ///< query matching mode (default is SPH_MATCH_EXTENDED2)
  361. var $_weights; ///< per-field weights (default is 1 for all fields)
  362. var $_sort; ///< match sorting mode (default is SPH_SORT_RELEVANCE)
  363. var $_sortby; ///< attribute to sort by (defualt is "")
  364. var $_min_id; ///< min ID to match (default is 0, which means no limit)
  365. var $_max_id; ///< max ID to match (default is 0, which means no limit)
  366. var $_filters; ///< search filters
  367. var $_groupby; ///< group-by attribute name
  368. var $_groupfunc; ///< group-by function (to pre-process group-by attribute value with)
  369. var $_groupsort; ///< group-by sorting clause (to sort groups in result set with)
  370. var $_groupdistinct;///< group-by count-distinct attribute
  371. var $_maxmatches; ///< max matches to retrieve
  372. var $_cutoff; ///< cutoff to stop searching at (default is 0)
  373. var $_retrycount; ///< distributed retries count
  374. var $_retrydelay; ///< distributed retries delay
  375. var $_anchor; ///< geographical anchor point
  376. var $_indexweights; ///< per-index weights
  377. var $_ranker; ///< ranking mode (default is SPH_RANK_PROXIMITY_BM25)
  378. var $_rankexpr; ///< ranking mode expression (for SPH_RANK_EXPR)
  379. var $_maxquerytime; ///< max query time, milliseconds (default is 0, do not limit)
  380. var $_fieldweights; ///< per-field-name weights
  381. var $_overrides; ///< per-query attribute values overrides
  382. var $_select; ///< select-list (attributes or expressions, with optional aliases)
  383. var $_query_flags; ///< per-query various flags
  384. var $_predictedtime; ///< per-query max_predicted_time
  385. var $_outerorderby; ///< outer match sort by
  386. var $_outeroffset; ///< outer offset
  387. var $_outerlimit; ///< outer limit
  388. var $_hasouter;
  389. var $_error; ///< last error message
  390. var $_warning; ///< last warning message
  391. var $_connerror; ///< connection error vs remote error flag
  392. var $_reqs; ///< requests array for multi-query
  393. var $_mbenc; ///< stored mbstring encoding
  394. var $_arrayresult; ///< whether $result["matches"] should be a hash or an array
  395. var $_timeout; ///< connect timeout
  396. /////////////////////////////////////////////////////////////////////////////
  397. // common stuff
  398. /////////////////////////////////////////////////////////////////////////////
  399. /// create a new client object and fill defaults
  400. function __construct ()
  401. {
  402. // per-client-object settings
  403. $this->_host = "localhost";
  404. $this->_port = 9312;
  405. $this->_path = false;
  406. $this->_socket = false;
  407. // per-query settings
  408. $this->_offset = 0;
  409. $this->_limit = 20;
  410. $this->_mode = SPH_MATCH_EXTENDED2;
  411. $this->_weights = array ();
  412. $this->_sort = SPH_SORT_RELEVANCE;
  413. $this->_sortby = "";
  414. $this->_min_id = 0;
  415. $this->_max_id = 0;
  416. $this->_filters = array ();
  417. $this->_groupby = "";
  418. $this->_groupfunc = SPH_GROUPBY_DAY;
  419. $this->_groupsort = "@group desc";
  420. $this->_groupdistinct= "";
  421. $this->_maxmatches = 1000;
  422. $this->_cutoff = 0;
  423. $this->_retrycount = 0;
  424. $this->_retrydelay = 0;
  425. $this->_anchor = array ();
  426. $this->_indexweights= array ();
  427. $this->_ranker = SPH_RANK_PROXIMITY_BM25;
  428. $this->_rankexpr = "";
  429. $this->_maxquerytime= 0;
  430. $this->_fieldweights= array();
  431. $this->_overrides = array();
  432. $this->_select = "*";
  433. $this->_query_flags = sphSetBit ( 0, 6, true ); // default idf=tfidf_normalized
  434. $this->_predictedtime = 0;
  435. $this->_outerorderby = "";
  436. $this->_outeroffset = 0;
  437. $this->_outerlimit = 0;
  438. $this->_hasouter = false;
  439. $this->_error = ""; // per-reply fields (for single-query case)
  440. $this->_warning = "";
  441. $this->_connerror = false;
  442. $this->_reqs = array (); // requests storage (for multi-query case)
  443. $this->_mbenc = "";
  444. $this->_arrayresult = false;
  445. $this->_timeout = 0;
  446. }
  447. function __destruct()
  448. {
  449. if ( $this->_socket !== false )
  450. fclose ( $this->_socket );
  451. }
  452. /// get last error message (string)
  453. function GetLastError ()
  454. {
  455. return $this->_error;
  456. }
  457. /// get last warning message (string)
  458. function GetLastWarning ()
  459. {
  460. return $this->_warning;
  461. }
  462. /// get last error flag (to tell network connection errors from searchd errors or broken responses)
  463. function IsConnectError()
  464. {
  465. return $this->_connerror;
  466. }
  467. /// set searchd host name (string) and port (integer)
  468. function SetServer ( $host, $port = 0 )
  469. {
  470. assert ( is_string($host) );
  471. if ( $host[0] == '/')
  472. {
  473. $this->_path = 'unix://' . $host;
  474. return;
  475. }
  476. if ( substr ( $host, 0, 7 )=="unix://" )
  477. {
  478. $this->_path = $host;
  479. return;
  480. }
  481. $this->_host = $host;
  482. $port = intval($port);
  483. assert ( 0<=$port && $port<65536 );
  484. $this->_port = ( $port==0 ) ? 9312 : $port;
  485. $this->_path = '';
  486. }
  487. /// set server connection timeout (0 to remove)
  488. function SetConnectTimeout ( $timeout )
  489. {
  490. assert ( is_numeric($timeout) );
  491. $this->_timeout = $timeout;
  492. }
  493. function _Send ( $handle, $data, $length )
  494. {
  495. if ( feof($handle) || fwrite ( $handle, $data, $length ) !== $length )
  496. {
  497. $this->_error = 'connection unexpectedly closed (timed out?)';
  498. $this->_connerror = true;
  499. return false;
  500. }
  501. return true;
  502. }
  503. /////////////////////////////////////////////////////////////////////////////
  504. /// enter mbstring workaround mode
  505. function _MBPush ()
  506. {
  507. $this->_mbenc = "";
  508. if ( ini_get ( "mbstring.func_overload" ) & 2 )
  509. {
  510. $this->_mbenc = mb_internal_encoding();
  511. mb_internal_encoding ( "latin1" );
  512. }
  513. }
  514. /// leave mbstring workaround mode
  515. function _MBPop ()
  516. {
  517. if ( $this->_mbenc )
  518. mb_internal_encoding ( $this->_mbenc );
  519. }
  520. /// connect to searchd server
  521. function _Connect ()
  522. {
  523. if ( $this->_socket!==false )
  524. {
  525. // we are in persistent connection mode, so we have a socket
  526. // however, need to check whether it's still alive
  527. if ( !@feof ( $this->_socket ) )
  528. return $this->_socket;
  529. // force reopen
  530. $this->_socket = false;
  531. }
  532. $errno = 0;
  533. $errstr = "";
  534. $this->_connerror = false;
  535. if ( $this->_path )
  536. {
  537. $host = $this->_path;
  538. $port = 0;
  539. }
  540. else
  541. {
  542. $host = $this->_host;
  543. $port = $this->_port;
  544. }
  545. if ( $this->_timeout<=0 )
  546. $fp = @fsockopen ( $host, $port, $errno, $errstr );
  547. else
  548. $fp = @fsockopen ( $host, $port, $errno, $errstr, $this->_timeout );
  549. if ( !$fp )
  550. {
  551. if ( $this->_path )
  552. $location = $this->_path;
  553. else
  554. $location = "{$this->_host}:{$this->_port}";
  555. $errstr = trim ( $errstr );
  556. $this->_error = "connection to $location failed (errno=$errno, msg=$errstr)";
  557. $this->_connerror = true;
  558. return false;
  559. }
  560. // send my version
  561. // this is a subtle part. we must do it before (!) reading back from searchd.
  562. // because otherwise under some conditions (reported on FreeBSD for instance)
  563. // TCP stack could throttle write-write-read pattern because of Nagle.
  564. if ( !$this->_Send ( $fp, pack ( "N", 1 ), 4 ) )
  565. {
  566. fclose ( $fp );
  567. $this->_error = "failed to send client protocol version";
  568. return false;
  569. }
  570. // check version
  571. list(,$v) = unpack ( "N*", fread ( $fp, 4 ) );
  572. $v = (int)$v;
  573. if ( $v<1 )
  574. {
  575. fclose ( $fp );
  576. $this->_error = "expected searchd protocol version 1+, got version '$v'";
  577. return false;
  578. }
  579. return $fp;
  580. }
  581. /// get and check response packet from searchd server
  582. function _GetResponse ( $fp, $client_ver )
  583. {
  584. $response = "";
  585. $len = 0;
  586. $header = fread ( $fp, 8 );
  587. if ( strlen($header)==8 )
  588. {
  589. list ( $status, $ver, $len ) = array_values ( unpack ( "n2a/Nb", $header ) );
  590. $left = $len;
  591. while ( $left>0 && !feof($fp) )
  592. {
  593. $chunk = fread ( $fp, min ( 8192, $left ) );
  594. if ( $chunk )
  595. {
  596. $response .= $chunk;
  597. $left -= strlen($chunk);
  598. }
  599. }
  600. }
  601. if ( $this->_socket === false )
  602. fclose ( $fp );
  603. // check response
  604. $read = strlen ( $response );
  605. if ( !$response || $read!=$len )
  606. {
  607. $this->_error = $len
  608. ? "failed to read searchd response (status=$status, ver=$ver, len=$len, read=$read)"
  609. : "received zero-sized searchd response";
  610. return false;
  611. }
  612. // check status
  613. if ( $status==SEARCHD_WARNING )
  614. {
  615. list(,$wlen) = unpack ( "N*", substr ( $response, 0, 4 ) );
  616. $this->_warning = substr ( $response, 4, $wlen );
  617. return substr ( $response, 4+$wlen );
  618. }
  619. if ( $status==SEARCHD_ERROR )
  620. {
  621. $this->_error = "searchd error: " . substr ( $response, 4 );
  622. return false;
  623. }
  624. if ( $status==SEARCHD_RETRY )
  625. {
  626. $this->_error = "temporary searchd error: " . substr ( $response, 4 );
  627. return false;
  628. }
  629. if ( $status!=SEARCHD_OK )
  630. {
  631. $this->_error = "unknown status code '$status'";
  632. return false;
  633. }
  634. // check version
  635. if ( $ver<$client_ver )
  636. {
  637. $this->_warning = sprintf ( "searchd command v.%d.%d older than client's v.%d.%d, some options might not work",
  638. $ver>>8, $ver&0xff, $client_ver>>8, $client_ver&0xff );
  639. }
  640. return $response;
  641. }
  642. /////////////////////////////////////////////////////////////////////////////
  643. // searching
  644. /////////////////////////////////////////////////////////////////////////////
  645. /// set offset and count into result set,
  646. /// and optionally set max-matches and cutoff limits
  647. function SetLimits ( $offset, $limit, $max=0, $cutoff=0 )
  648. {
  649. assert ( is_int($offset) );
  650. assert ( is_int($limit) );
  651. assert ( $offset>=0 );
  652. assert ( $limit>0 );
  653. assert ( $max>=0 );
  654. $this->_offset = $offset;
  655. $this->_limit = $limit;
  656. if ( $max>0 )
  657. $this->_maxmatches = $max;
  658. if ( $cutoff>0 )
  659. $this->_cutoff = $cutoff;
  660. }
  661. /// set maximum query time, in milliseconds, per-index
  662. /// integer, 0 means "do not limit"
  663. function SetMaxQueryTime ( $max )
  664. {
  665. assert ( is_int($max) );
  666. assert ( $max>=0 );
  667. $this->_maxquerytime = $max;
  668. }
  669. /// set matching mode
  670. function SetMatchMode ( $mode )
  671. {
  672. trigger_error ( 'DEPRECATED: Do not call this method or, even better, use SphinxQL instead of an API', E_USER_DEPRECATED );
  673. assert ( $mode==SPH_MATCH_ALL
  674. || $mode==SPH_MATCH_ANY
  675. || $mode==SPH_MATCH_PHRASE
  676. || $mode==SPH_MATCH_BOOLEAN
  677. || $mode==SPH_MATCH_EXTENDED
  678. || $mode==SPH_MATCH_FULLSCAN
  679. || $mode==SPH_MATCH_EXTENDED2 );
  680. $this->_mode = $mode;
  681. }
  682. /// set ranking mode
  683. function SetRankingMode ( $ranker, $rankexpr="" )
  684. {
  685. assert ( $ranker===0 || $ranker>=1 && $ranker<SPH_RANK_TOTAL );
  686. assert ( is_string($rankexpr) );
  687. $this->_ranker = $ranker;
  688. $this->_rankexpr = $rankexpr;
  689. }
  690. /// set matches sorting mode
  691. function SetSortMode ( $mode, $sortby="" )
  692. {
  693. assert (
  694. $mode==SPH_SORT_RELEVANCE ||
  695. $mode==SPH_SORT_ATTR_DESC ||
  696. $mode==SPH_SORT_ATTR_ASC ||
  697. $mode==SPH_SORT_TIME_SEGMENTS ||
  698. $mode==SPH_SORT_EXTENDED ||
  699. $mode==SPH_SORT_EXPR );
  700. assert ( is_string($sortby) );
  701. assert ( $mode==SPH_SORT_RELEVANCE || strlen($sortby)>0 );
  702. $this->_sort = $mode;
  703. $this->_sortby = $sortby;
  704. }
  705. /// bind per-field weights by order
  706. /// DEPRECATED; use SetFieldWeights() instead
  707. function SetWeights ( $weights )
  708. {
  709. die("This method is now deprecated; please use SetFieldWeights instead");
  710. }
  711. /// bind per-field weights by name
  712. function SetFieldWeights ( $weights )
  713. {
  714. assert ( is_array($weights) );
  715. foreach ( $weights as $name=>$weight )
  716. {
  717. assert ( is_string($name) );
  718. assert ( is_int($weight) );
  719. }
  720. $this->_fieldweights = $weights;
  721. }
  722. /// bind per-index weights by name
  723. function SetIndexWeights ( $weights )
  724. {
  725. assert ( is_array($weights) );
  726. foreach ( $weights as $index=>$weight )
  727. {
  728. assert ( is_string($index) );
  729. assert ( is_int($weight) );
  730. }
  731. $this->_indexweights = $weights;
  732. }
  733. /// set IDs range to match
  734. /// only match records if document ID is beetwen $min and $max (inclusive)
  735. function SetIDRange ( $min, $max )
  736. {
  737. assert ( is_numeric($min) );
  738. assert ( is_numeric($max) );
  739. assert ( $min<=$max );
  740. $this->_min_id = $min;
  741. $this->_max_id = $max;
  742. }
  743. /// set values set filter
  744. /// only match records where $attribute value is in given set
  745. function SetFilter ( $attribute, $values, $exclude=false )
  746. {
  747. assert ( is_string($attribute) );
  748. assert ( is_array($values) );
  749. assert ( count($values) );
  750. if ( is_array($values) && count($values) )
  751. {
  752. foreach ( $values as $value )
  753. assert ( is_numeric($value) );
  754. $this->_filters[] = array ( "type"=>SPH_FILTER_VALUES, "attr"=>$attribute, "exclude"=>$exclude, "values"=>$values );
  755. }
  756. }
  757. /// set string filter
  758. /// only match records where $attribute value is equal
  759. function SetFilterString ( $attribute, $value, $exclude=false )
  760. {
  761. assert ( is_string($attribute) );
  762. assert ( is_string($value) );
  763. $this->_filters[] = array ( "type"=>SPH_FILTER_STRING, "attr"=>$attribute, "exclude"=>$exclude, "value"=>$value );
  764. }
  765. /// set range filter
  766. /// only match records if $attribute value is beetwen $min and $max (inclusive)
  767. function SetFilterRange ( $attribute, $min, $max, $exclude=false )
  768. {
  769. assert ( is_string($attribute) );
  770. assert ( is_numeric($min) );
  771. assert ( is_numeric($max) );
  772. assert ( $min<=$max );
  773. $this->_filters[] = array ( "type"=>SPH_FILTER_RANGE, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max );
  774. }
  775. /// set float range filter
  776. /// only match records if $attribute value is beetwen $min and $max (inclusive)
  777. function SetFilterFloatRange ( $attribute, $min, $max, $exclude=false )
  778. {
  779. assert ( is_string($attribute) );
  780. assert ( is_float($min) );
  781. assert ( is_float($max) );
  782. assert ( $min<=$max );
  783. $this->_filters[] = array ( "type"=>SPH_FILTER_FLOATRANGE, "attr"=>$attribute, "exclude"=>$exclude, "min"=>$min, "max"=>$max );
  784. }
  785. /// setup anchor point for geosphere distance calculations
  786. /// required to use @geodist in filters and sorting
  787. /// latitude and longitude must be in radians
  788. function SetGeoAnchor ( $attrlat, $attrlong, $lat, $long )
  789. {
  790. assert ( is_string($attrlat) );
  791. assert ( is_string($attrlong) );
  792. assert ( is_float($lat) );
  793. assert ( is_float($long) );
  794. $this->_anchor = array ( "attrlat"=>$attrlat, "attrlong"=>$attrlong, "lat"=>$lat, "long"=>$long );
  795. }
  796. /// set grouping attribute and function
  797. function SetGroupBy ( $attribute, $func, $groupsort="@group desc" )
  798. {
  799. assert ( is_string($attribute) );
  800. assert ( is_string($groupsort) );
  801. assert ( $func==SPH_GROUPBY_DAY
  802. || $func==SPH_GROUPBY_WEEK
  803. || $func==SPH_GROUPBY_MONTH
  804. || $func==SPH_GROUPBY_YEAR
  805. || $func==SPH_GROUPBY_ATTR
  806. || $func==SPH_GROUPBY_ATTRPAIR );
  807. $this->_groupby = $attribute;
  808. $this->_groupfunc = $func;
  809. $this->_groupsort = $groupsort;
  810. }
  811. /// set count-distinct attribute for group-by queries
  812. function SetGroupDistinct ( $attribute )
  813. {
  814. assert ( is_string($attribute) );
  815. $this->_groupdistinct = $attribute;
  816. }
  817. /// set distributed retries count and delay
  818. function SetRetries ( $count, $delay=0 )
  819. {
  820. assert ( is_int($count) && $count>=0 );
  821. assert ( is_int($delay) && $delay>=0 );
  822. $this->_retrycount = $count;
  823. $this->_retrydelay = $delay;
  824. }
  825. /// set result set format (hash or array; hash by default)
  826. /// PHP specific; needed for group-by-MVA result sets that may contain duplicate IDs
  827. function SetArrayResult ( $arrayresult )
  828. {
  829. assert ( is_bool($arrayresult) );
  830. $this->_arrayresult = $arrayresult;
  831. }
  832. /// set attribute values override
  833. /// there can be only one override per attribute
  834. /// $values must be a hash that maps document IDs to attribute values
  835. function SetOverride ( $attrname, $attrtype, $values )
  836. {
  837. trigger_error('DEPRECATED: Do not call this method. Use SphinxQL REMAP() function instead.', E_USER_DEPRECATED);
  838. assert ( is_string ( $attrname ) );
  839. assert ( in_array ( $attrtype, array ( SPH_ATTR_INTEGER, SPH_ATTR_TIMESTAMP, SPH_ATTR_BOOL, SPH_ATTR_FLOAT, SPH_ATTR_BIGINT ) ) );
  840. assert ( is_array ( $values ) );
  841. $this->_overrides[$attrname] = array ( "attr"=>$attrname, "type"=>$attrtype, "values"=>$values );
  842. }
  843. /// set select-list (attributes or expressions), SQL-like syntax
  844. function SetSelect ( $select )
  845. {
  846. assert ( is_string ( $select ) );
  847. $this->_select = $select;
  848. }
  849. function SetQueryFlag ( $flag_name, $flag_value )
  850. {
  851. $known_names = array ( "reverse_scan", "sort_method", "max_predicted_time", "boolean_simplify", "idf", "global_idf", "low_priority" );
  852. $flags = array (
  853. "reverse_scan" => array ( 0, 1 ),
  854. "sort_method" => array ( "pq", "kbuffer" ),
  855. "max_predicted_time" => array ( 0 ),
  856. "boolean_simplify" => array ( true, false ),
  857. "idf" => array ("normalized", "plain", "tfidf_normalized", "tfidf_unnormalized" ),
  858. "global_idf" => array ( true, false ),
  859. "low_priority" => array ( true, false )
  860. );
  861. assert ( isset ( $flag_name, $known_names ) );
  862. assert ( in_array( $flag_value, $flags[$flag_name], true ) || ( $flag_name=="max_predicted_time" && is_int ( $flag_value ) && $flag_value>=0 ) );
  863. if ( $flag_name=="reverse_scan" ) $this->_query_flags = sphSetBit ( $this->_query_flags, 0, $flag_value==1 );
  864. if ( $flag_name=="sort_method" ) $this->_query_flags = sphSetBit ( $this->_query_flags, 1, $flag_value=="kbuffer" );
  865. if ( $flag_name=="max_predicted_time" )
  866. {
  867. $this->_query_flags = sphSetBit ( $this->_query_flags, 2, $flag_value>0 );
  868. $this->_predictedtime = (int)$flag_value;
  869. }
  870. if ( $flag_name=="boolean_simplify" ) $this->_query_flags = sphSetBit ( $this->_query_flags, 3, $flag_value );
  871. if ( $flag_name=="idf" && ( $flag_value=="normalized" || $flag_value=="plain" ) ) $this->_query_flags = sphSetBit ( $this->_query_flags, 4, $flag_value=="plain" );
  872. if ( $flag_name=="global_idf" ) $this->_query_flags = sphSetBit ( $this->_query_flags, 5, $flag_value );
  873. if ( $flag_name=="idf" && ( $flag_value=="tfidf_normalized" || $flag_value=="tfidf_unnormalized" ) ) $this->_query_flags = sphSetBit ( $this->_query_flags, 6, $flag_value=="tfidf_normalized" );
  874. if ( $flag_name=="low_priority" ) $this->_query_flags = sphSetBit ( $this->_query_flags, 8, $flag_value );
  875. }
  876. /// set outer order by parameters
  877. function SetOuterSelect ( $orderby, $offset, $limit )
  878. {
  879. assert ( is_string($orderby) );
  880. assert ( is_int($offset) );
  881. assert ( is_int($limit) );
  882. assert ( $offset>=0 );
  883. assert ( $limit>0 );
  884. $this->_outerorderby = $orderby;
  885. $this->_outeroffset = $offset;
  886. $this->_outerlimit = $limit;
  887. $this->_hasouter = true;
  888. }
  889. //////////////////////////////////////////////////////////////////////////////
  890. /// clear all filters (for multi-queries)
  891. function ResetFilters ()
  892. {
  893. $this->_filters = array();
  894. $this->_anchor = array();
  895. }
  896. /// clear groupby settings (for multi-queries)
  897. function ResetGroupBy ()
  898. {
  899. $this->_groupby = "";
  900. $this->_groupfunc = SPH_GROUPBY_DAY;
  901. $this->_groupsort = "@group desc";
  902. $this->_groupdistinct= "";
  903. }
  904. /// clear all attribute value overrides (for multi-queries)
  905. function ResetOverrides ()
  906. {
  907. $this->_overrides = array ();
  908. }
  909. function ResetQueryFlag ()
  910. {
  911. $this->_query_flags = sphSetBit ( 0, 6, true ); // default idf=tfidf_normalized
  912. $this->_predictedtime = 0;
  913. }
  914. function ResetOuterSelect ()
  915. {
  916. $this->_outerorderby = '';
  917. $this->_outeroffset = 0;
  918. $this->_outerlimit = 0;
  919. $this->_hasouter = false;
  920. }
  921. //////////////////////////////////////////////////////////////////////////////
  922. /// connect to searchd server, run given search query through given indexes,
  923. /// and return the search results
  924. function Query ( $query, $index="*", $comment="" )
  925. {
  926. assert ( empty($this->_reqs) );
  927. $this->AddQuery ( $query, $index, $comment );
  928. $results = $this->RunQueries ();
  929. $this->_reqs = array (); // just in case it failed too early
  930. if ( !is_array($results) )
  931. return false; // probably network error; error message should be already filled
  932. $this->_error = $results[0]["error"];
  933. $this->_warning = $results[0]["warning"];
  934. if ( $results[0]["status"]==SEARCHD_ERROR )
  935. return false;
  936. else
  937. return $results[0];
  938. }
  939. /// helper to pack floats in network byte order
  940. function _PackFloat ( $f )
  941. {
  942. $t1 = pack ( "f", $f ); // machine order
  943. list(,$t2) = unpack ( "L*", $t1 ); // int in machine order
  944. return pack ( "N", $t2 );
  945. }
  946. /// add query to multi-query batch
  947. /// returns index into results array from RunQueries() call
  948. function AddQuery ( $query, $index="*", $comment="" )
  949. {
  950. // mbstring workaround
  951. $this->_MBPush ();
  952. // build request
  953. $req = pack ( "NNNNN", $this->_query_flags, $this->_offset, $this->_limit, $this->_mode, $this->_ranker );
  954. if ( $this->_ranker==SPH_RANK_EXPR )
  955. $req .= pack ( "N", strlen($this->_rankexpr) ) . $this->_rankexpr;
  956. $req .= pack ( "N", $this->_sort ); // (deprecated) sort mode
  957. $req .= pack ( "N", strlen($this->_sortby) ) . $this->_sortby;
  958. $req .= pack ( "N", strlen($query) ) . $query; // query itself
  959. $req .= pack ( "N", count($this->_weights) ); // weights
  960. foreach ( $this->_weights as $weight )
  961. $req .= pack ( "N", (int)$weight );
  962. $req .= pack ( "N", strlen($index) ) . $index; // indexes
  963. $req .= pack ( "N", 1 ); // id64 range marker
  964. $req .= sphPackU64 ( $this->_min_id ) . sphPackU64 ( $this->_max_id ); // id64 range
  965. // filters
  966. $req .= pack ( "N", count($this->_filters) );
  967. foreach ( $this->_filters as $filter )
  968. {
  969. $req .= pack ( "N", strlen($filter["attr"]) ) . $filter["attr"];
  970. $req .= pack ( "N", $filter["type"] );
  971. switch ( $filter["type"] )
  972. {
  973. case SPH_FILTER_VALUES:
  974. $req .= pack ( "N", count($filter["values"]) );
  975. foreach ( $filter["values"] as $value )
  976. $req .= sphPackI64 ( $value );
  977. break;
  978. case SPH_FILTER_RANGE:
  979. $req .= sphPackI64 ( $filter["min"] ) . sphPackI64 ( $filter["max"] );
  980. break;
  981. case SPH_FILTER_FLOATRANGE:
  982. $req .= $this->_PackFloat ( $filter["min"] ) . $this->_PackFloat ( $filter["max"] );
  983. break;
  984. case SPH_FILTER_STRING:
  985. $req .= pack ( "N", strlen($filter["value"]) ) . $filter["value"];
  986. break;
  987. default:
  988. assert ( 0 && "internal error: unhandled filter type" );
  989. }
  990. $req .= pack ( "N", $filter["exclude"] );
  991. }
  992. // group-by clause, max-matches count, group-sort clause, cutoff count
  993. $req .= pack ( "NN", $this->_groupfunc, strlen($this->_groupby) ) . $this->_groupby;
  994. $req .= pack ( "N", $this->_maxmatches );
  995. $req .= pack ( "N", strlen($this->_groupsort) ) . $this->_groupsort;
  996. $req .= pack ( "NNN", $this->_cutoff, $this->_retrycount, $this->_retrydelay );
  997. $req .= pack ( "N", strlen($this->_groupdistinct) ) . $this->_groupdistinct;
  998. // anchor point
  999. if ( empty($this->_anchor) )
  1000. {
  1001. $req .= pack ( "N", 0 );
  1002. } else
  1003. {
  1004. $a =& $this->_anchor;
  1005. $req .= pack ( "N", 1 );
  1006. $req .= pack ( "N", strlen($a["attrlat"]) ) . $a["attrlat"];
  1007. $req .= pack ( "N", strlen($a["attrlong"]) ) . $a["attrlong"];
  1008. $req .= $this->_PackFloat ( $a["lat"] ) . $this->_PackFloat ( $a["long"] );
  1009. }
  1010. // per-index weights
  1011. $req .= pack ( "N", count($this->_indexweights) );
  1012. foreach ( $this->_indexweights as $idx=>$weight )
  1013. $req .= pack ( "N", strlen($idx) ) . $idx . pack ( "N", $weight );
  1014. // max query time
  1015. $req .= pack ( "N", $this->_maxquerytime );
  1016. // per-field weights
  1017. $req .= pack ( "N", count($this->_fieldweights) );
  1018. foreach ( $this->_fieldweights as $field=>$weight )
  1019. $req .= pack ( "N", strlen($field) ) . $field . pack ( "N", $weight );
  1020. // comment
  1021. $req .= pack ( "N", strlen($comment) ) . $comment;
  1022. // attribute overrides
  1023. $req .= pack ( "N", count($this->_overrides) );
  1024. foreach ( $this->_overrides as $key => $entry )
  1025. {
  1026. $req .= pack ( "N", strlen($entry["attr"]) ) . $entry["attr"];
  1027. $req .= pack ( "NN", $entry["type"], count($entry["values"]) );
  1028. foreach ( $entry["values"] as $id=>$val )
  1029. {
  1030. assert ( is_numeric($id) );
  1031. assert ( is_numeric($val) );
  1032. $req .= sphPackU64 ( $id );
  1033. switch ( $entry["type"] )
  1034. {
  1035. case SPH_ATTR_FLOAT: $req .= $this->_PackFloat ( $val ); break;
  1036. case SPH_ATTR_BIGINT: $req .= sphPackI64 ( $val ); break;
  1037. default: $req .= pack ( "N", $val ); break;
  1038. }
  1039. }
  1040. }
  1041. // select-list
  1042. $req .= pack ( "N", strlen($this->_select) ) . $this->_select;
  1043. // max_predicted_time
  1044. if ( $this->_predictedtime>0 )
  1045. $req .= pack ( "N", (int)$this->_predictedtime );
  1046. $req .= pack ( "N", strlen($this->_outerorderby) ) . $this->_outerorderby;
  1047. $req .= pack ( "NN", $this->_outeroffset, $this->_outerlimit );
  1048. if ( $this->_hasouter )
  1049. $req .= pack ( "N", 1 );
  1050. else
  1051. $req .= pack ( "N", 0 );
  1052. // mbstring workaround
  1053. $this->_MBPop ();
  1054. // store request to requests array
  1055. $this->_reqs[] = $req;
  1056. return count($this->_reqs)-1;
  1057. }
  1058. /// connect to searchd, run queries batch, and return an array of result sets
  1059. function RunQueries ()
  1060. {
  1061. if ( empty($this->_reqs) )
  1062. {
  1063. $this->_error = "no queries defined, issue AddQuery() first";
  1064. return false;
  1065. }
  1066. // mbstring workaround
  1067. $this->_MBPush ();
  1068. if (!( $fp = $this->_Connect() ))
  1069. {
  1070. $this->_MBPop ();
  1071. return false;
  1072. }
  1073. // send query, get response
  1074. $nreqs = count($this->_reqs);
  1075. $req = join ( "", $this->_reqs );
  1076. $len = 8+strlen($req);
  1077. $req = pack ( "nnNNN", SEARCHD_COMMAND_SEARCH, VER_COMMAND_SEARCH, $len, 0, $nreqs ) . $req; // add header
  1078. if ( !( $this->_Send ( $fp, $req, $len+8 ) ) ||
  1079. !( $response = $this->_GetResponse ( $fp, VER_COMMAND_SEARCH ) ) )
  1080. {
  1081. $this->_MBPop ();
  1082. return false;
  1083. }
  1084. // query sent ok; we can reset reqs now
  1085. $this->_reqs = array ();
  1086. // parse and return response
  1087. return $this->_ParseSearchResponse ( $response, $nreqs );
  1088. }
  1089. /// parse and return search query (or queries) response
  1090. function _ParseSearchResponse ( $response, $nreqs )
  1091. {
  1092. $p = 0; // current position
  1093. $max = strlen($response); // max position for checks, to protect against broken responses
  1094. $results = array ();
  1095. for ( $ires=0; $ires<$nreqs && $p<$max; $ires++ )
  1096. {
  1097. $results[] = array();
  1098. $result =& $results[$ires];
  1099. $result["error"] = "";
  1100. $result["warning"] = "";
  1101. // extract status
  1102. list(,$status) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1103. $result["status"] = $status;
  1104. if ( $status!=SEARCHD_OK )
  1105. {
  1106. list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1107. $message = substr ( $response, $p, $len ); $p += $len;
  1108. if ( $status==SEARCHD_WARNING )
  1109. {
  1110. $result["warning"] = $message;
  1111. } else
  1112. {
  1113. $result["error"] = $message;
  1114. continue;
  1115. }
  1116. }
  1117. // read schema
  1118. $fields = array ();
  1119. $attrs = array ();
  1120. list(,$nfields) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1121. while ( $nfields-->0 && $p<$max )
  1122. {
  1123. list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1124. $fields[] = substr ( $response, $p, $len ); $p += $len;
  1125. }
  1126. $result["fields"] = $fields;
  1127. list(,$nattrs) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1128. while ( $nattrs-->0 && $p<$max )
  1129. {
  1130. list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1131. $attr = substr ( $response, $p, $len ); $p += $len;
  1132. list(,$type) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1133. $attrs[$attr] = $type;
  1134. }
  1135. $result["attrs"] = $attrs;
  1136. // read match count
  1137. list(,$count) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1138. list(,$id64) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1139. // read matches
  1140. $idx = -1;
  1141. while ( $count-->0 && $p<$max )
  1142. {
  1143. // index into result array
  1144. $idx++;
  1145. // parse document id and weight
  1146. if ( $id64 )
  1147. {
  1148. $doc = sphUnpackU64 ( substr ( $response, $p, 8 ) ); $p += 8;
  1149. list(,$weight) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1150. }
  1151. else
  1152. {
  1153. list ( $doc, $weight ) = array_values ( unpack ( "N*N*",
  1154. substr ( $response, $p, 8 ) ) );
  1155. $p += 8;
  1156. $doc = sphFixUint($doc);
  1157. }
  1158. $weight = sprintf ( "%u", $weight );
  1159. // create match entry
  1160. if ( $this->_arrayresult )
  1161. $result["matches"][$idx] = array ( "id"=>$doc, "weight"=>$weight );
  1162. else
  1163. $result["matches"][$doc]["weight"] = $weight;
  1164. // parse and create attributes
  1165. $attrvals = array ();
  1166. foreach ( $attrs as $attr=>$type )
  1167. {
  1168. // handle 64bit ints
  1169. if ( $type==SPH_ATTR_BIGINT )
  1170. {
  1171. $attrvals[$attr] = sphUnpackI64 ( substr ( $response, $p, 8 ) ); $p += 8;
  1172. continue;
  1173. }
  1174. // handle floats
  1175. if ( $type==SPH_ATTR_FLOAT )
  1176. {
  1177. list(,$uval) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1178. list(,$fval) = unpack ( "f*", pack ( "L", $uval ) );
  1179. $attrvals[$attr] = $fval;
  1180. continue;
  1181. }
  1182. // handle everything else as unsigned ints
  1183. list(,$val) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1184. if ( $type==SPH_ATTR_MULTI )
  1185. {
  1186. $attrvals[$attr] = array ();
  1187. $nvalues = $val;
  1188. while ( $nvalues-->0 && $p<$max )
  1189. {
  1190. list(,$val) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1191. $attrvals[$attr][] = sphFixUint($val);
  1192. }
  1193. } else if ( $type==SPH_ATTR_MULTI64 )
  1194. {
  1195. $attrvals[$attr] = array ();
  1196. $nvalues = $val;
  1197. while ( $nvalues>0 && $p<$max )
  1198. {
  1199. $attrvals[$attr][] = sphUnpackI64 ( substr ( $response, $p, 8 ) ); $p += 8;
  1200. $nvalues -= 2;
  1201. }
  1202. } else if ( $type==SPH_ATTR_STRING )
  1203. {
  1204. $attrvals[$attr] = substr ( $response, $p, $val );
  1205. $p += $val;
  1206. } else if ( $type==SPH_ATTR_FACTORS )
  1207. {
  1208. $attrvals[$attr] = substr ( $response, $p, $val-4 );
  1209. $p += $val-4;
  1210. } else
  1211. {
  1212. $attrvals[$attr] = sphFixUint($val);
  1213. }
  1214. }
  1215. if ( $this->_arrayresult )
  1216. $result["matches"][$idx]["attrs"] = $attrvals;
  1217. else
  1218. $result["matches"][$doc]["attrs"] = $attrvals;
  1219. }
  1220. list ( $total, $total_found, $msecs, $words ) =
  1221. array_values ( unpack ( "N*N*N*N*", substr ( $response, $p, 16 ) ) );
  1222. $result["total"] = sprintf ( "%u", $total );
  1223. $result["total_found"] = sprintf ( "%u", $total_found );
  1224. $result["time"] = sprintf ( "%.3f", $msecs/1000 );
  1225. $p += 16;
  1226. while ( $words-->0 && $p<$max )
  1227. {
  1228. list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1229. $word = substr ( $response, $p, $len ); $p += $len;
  1230. list ( $docs, $hits ) = array_values ( unpack ( "N*N*", substr ( $response, $p, 8 ) ) ); $p += 8;
  1231. $result["words"][$word] = array (
  1232. "docs"=>sprintf ( "%u", $docs ),
  1233. "hits"=>sprintf ( "%u", $hits ) );
  1234. }
  1235. }
  1236. $this->_MBPop ();
  1237. return $results;
  1238. }
  1239. /////////////////////////////////////////////////////////////////////////////
  1240. // excerpts generation
  1241. /////////////////////////////////////////////////////////////////////////////
  1242. /// connect to searchd server, and generate exceprts (snippets)
  1243. /// of given documents for given query. returns false on failure,
  1244. /// an array of snippets on success
  1245. function BuildExcerpts ( $docs, $index, $words, $opts=array() )
  1246. {
  1247. assert ( is_array($docs) );
  1248. assert ( is_string($index) );
  1249. assert ( is_string($words) );
  1250. assert ( is_array($opts) );
  1251. $this->_MBPush ();
  1252. if (!( $fp = $this->_Connect() ))
  1253. {
  1254. $this->_MBPop();
  1255. return false;
  1256. }
  1257. /////////////////
  1258. // fixup options
  1259. /////////////////
  1260. if ( !isset($opts["before_match"]) ) $opts["before_match"] = "<b>";
  1261. if ( !isset($opts["after_match"]) ) $opts["after_match"] = "</b>";
  1262. if ( !isset($opts["chunk_separator"]) ) $opts["chunk_separator"] = " ... ";
  1263. if ( !isset($opts["limit"]) ) $opts["limit"] = 256;
  1264. if ( !isset($opts["limit_passages"]) ) $opts["limit_passages"] = 0;
  1265. if ( !isset($opts["limit_words"]) ) $opts["limit_words"] = 0;
  1266. if ( !isset($opts["around"]) ) $opts["around"] = 5;
  1267. if ( !isset($opts["exact_phrase"]) ) $opts["exact_phrase"] = false;
  1268. if ( !isset($opts["single_passage"]) ) $opts["single_passage"] = false;
  1269. if ( !isset($opts["use_boundaries"]) ) $opts["use_boundaries"] = false;
  1270. if ( !isset($opts["weight_order"]) ) $opts["weight_order"] = false;
  1271. if ( !isset($opts["query_mode"]) ) $opts["query_mode"] = false;
  1272. if ( !isset($opts["force_all_words"]) ) $opts["force_all_words"] = false;
  1273. if ( !isset($opts["start_passage_id"]) ) $opts["start_passage_id"] = 1;
  1274. if ( !isset($opts["load_files"]) ) $opts["load_files"] = false;
  1275. if ( !isset($opts["html_strip_mode"]) ) $opts["html_strip_mode"] = "index";
  1276. if ( !isset($opts["allow_empty"]) ) $opts["allow_empty"] = false;
  1277. if ( !isset($opts["passage_boundary"]) ) $opts["passage_boundary"] = "none";
  1278. if ( !isset($opts["emit_zones"]) ) $opts["emit_zones"] = false;
  1279. if ( !isset($opts["load_files_scattered"]) ) $opts["load_files_scattered"] = false;
  1280. /////////////////
  1281. // build request
  1282. /////////////////
  1283. // v.1.2 req
  1284. $flags = 1; // remove spaces
  1285. if ( $opts["exact_phrase"] ) $flags |= 2;
  1286. if ( $opts["single_passage"] ) $flags |= 4;
  1287. if ( $opts["use_boundaries"] ) $flags |= 8;
  1288. if ( $opts["weight_order"] ) $flags |= 16;
  1289. if ( $opts["query_mode"] ) $flags |= 32;
  1290. if ( $opts["force_all_words"] ) $flags |= 64;
  1291. if ( $opts["load_files"] ) $flags |= 128;
  1292. if ( $opts["allow_empty"] ) $flags |= 256;
  1293. if ( $opts["emit_zones"] ) $flags |= 512;
  1294. if ( $opts["load_files_scattered"] ) $flags |= 1024;
  1295. $req = pack ( "NN", 0, $flags ); // mode=0, flags=$flags
  1296. $req .= pack ( "N", strlen($index) ) . $index; // req index
  1297. $req .= pack ( "N", strlen($words) ) . $words; // req words
  1298. // options
  1299. $req .= pack ( "N", strlen($opts["before_match"]) ) . $opts["before_match"];
  1300. $req .= pack ( "N", strlen($opts["after_match"]) ) . $opts["after_match"];
  1301. $req .= pack ( "N", strlen($opts["chunk_separator"]) ) . $opts["chunk_separator"];
  1302. $req .= pack ( "NN", (int)$opts["limit"], (int)$opts["around"] );
  1303. $req .= pack ( "NNN", (int)$opts["limit_passages"], (int)$opts["limit_words"], (int)$opts["start_passage_id"] ); // v.1.2
  1304. $req .= pack ( "N", strlen($opts["html_strip_mode"]) ) . $opts["html_strip_mode"];
  1305. $req .= pack ( "N", strlen($opts["passage_boundary"]) ) . $opts["passage_boundary"];
  1306. // documents
  1307. $req .= pack ( "N", count($docs) );
  1308. foreach ( $docs as $doc )
  1309. {
  1310. assert ( is_string($doc) );
  1311. $req .= pack ( "N", strlen($doc) ) . $doc;
  1312. }
  1313. ////////////////////////////
  1314. // send query, get response
  1315. ////////////////////////////
  1316. $len = strlen($req);
  1317. $req = pack ( "nnN", SEARCHD_COMMAND_EXCERPT, VER_COMMAND_EXCERPT, $len ) . $req; // add header
  1318. if ( !( $this->_Send ( $fp, $req, $len+8 ) ) ||
  1319. !( $response = $this->_GetResponse ( $fp, VER_COMMAND_EXCERPT ) ) )
  1320. {
  1321. $this->_MBPop ();
  1322. return false;
  1323. }
  1324. //////////////////
  1325. // parse response
  1326. //////////////////
  1327. $pos = 0;
  1328. $res = array ();
  1329. $rlen = strlen($response);
  1330. for ( $i=0; $i<count($docs); $i++ )
  1331. {
  1332. list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) );
  1333. $pos += 4;
  1334. if ( $pos+$len > $rlen )
  1335. {
  1336. $this->_error = "incomplete reply";
  1337. $this->_MBPop ();
  1338. return false;
  1339. }
  1340. $res[] = $len ? substr ( $response, $pos, $len ) : "";
  1341. $pos += $len;
  1342. }
  1343. $this->_MBPop ();
  1344. return $res;
  1345. }
  1346. /////////////////////////////////////////////////////////////////////////////
  1347. // keyword generation
  1348. /////////////////////////////////////////////////////////////////////////////
  1349. /// connect to searchd server, and generate keyword list for a given query
  1350. /// returns false on failure,
  1351. /// an array of words on success
  1352. function BuildKeywords ( $query, $index, $hits )
  1353. {
  1354. assert ( is_string($query) );
  1355. assert ( is_string($index) );
  1356. assert ( is_bool($hits) );
  1357. $this->_MBPush ();
  1358. if (!( $fp = $this->_Connect() ))
  1359. {
  1360. $this->_MBPop();
  1361. return false;
  1362. }
  1363. /////////////////
  1364. // build request
  1365. /////////////////
  1366. // v.1.0 req
  1367. $req = pack ( "N", strlen($query) ) . $query; // req query
  1368. $req .= pack ( "N", strlen($index) ) . $index; // req index
  1369. $req .= pack ( "N", (int)$hits );
  1370. ////////////////////////////
  1371. // send query, get response
  1372. ////////////////////////////
  1373. $len = strlen($req);
  1374. $req = pack ( "nnN", SEARCHD_COMMAND_KEYWORDS, VER_COMMAND_KEYWORDS, $len ) . $req; // add header
  1375. if ( !( $this->_Send ( $fp, $req, $len+8 ) ) ||
  1376. !( $response = $this->_GetResponse ( $fp, VER_COMMAND_KEYWORDS ) ) )
  1377. {
  1378. $this->_MBPop ();
  1379. return false;
  1380. }
  1381. //////////////////
  1382. // parse response
  1383. //////////////////
  1384. $pos = 0;
  1385. $res = array ();
  1386. $rlen = strlen($response);
  1387. list(,$nwords) = unpack ( "N*", substr ( $response, $pos, 4 ) );
  1388. $pos += 4;
  1389. for ( $i=0; $i<$nwords; $i++ )
  1390. {
  1391. list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) ); $pos += 4;
  1392. $tokenized = $len ? substr ( $response, $pos, $len ) : "";
  1393. $pos += $len;
  1394. list(,$len) = unpack ( "N*", substr ( $response, $pos, 4 ) ); $pos += 4;
  1395. $normalized = $len ? substr ( $response, $pos, $len ) : "";
  1396. $pos += $len;
  1397. $res[] = array ( "tokenized"=>$tokenized, "normalized"=>$normalized );
  1398. if ( $hits )
  1399. {
  1400. list($ndocs,$nhits) = array_values ( unpack ( "N*N*", substr ( $response, $pos, 8 ) ) );
  1401. $pos += 8;
  1402. $res [$i]["docs"] = $ndocs;
  1403. $res [$i]["hits"] = $nhits;
  1404. }
  1405. if ( $pos > $rlen )
  1406. {
  1407. $this->_error = "incomplete reply";
  1408. $this->_MBPop ();
  1409. return false;
  1410. }
  1411. }
  1412. $this->_MBPop ();
  1413. return $res;
  1414. }
  1415. function EscapeString ( $string )
  1416. {
  1417. $from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=', '<' );
  1418. $to = array ( '\\\\', '\(','\)','\|','\-','\!','\@','\~','\"', '\&', '\/', '\^', '\$', '\=', '\<' );
  1419. return str_replace ( $from, $to, $string );
  1420. }
  1421. /////////////////////////////////////////////////////////////////////////////
  1422. // attribute updates
  1423. /////////////////////////////////////////////////////////////////////////////
  1424. /// batch update given attributes in given rows in given indexes
  1425. /// returns amount of updated documents (0 or more) on success, or -1 on failure
  1426. function UpdateAttributes ( $index, $attrs, $values, $mva=false, $ignorenonexistent=false )
  1427. {
  1428. // verify everything
  1429. assert ( is_string($index) );
  1430. assert ( is_bool($mva) );
  1431. assert ( is_bool($ignorenonexistent) );
  1432. assert ( is_array($attrs) );
  1433. foreach ( $attrs as $attr )
  1434. assert ( is_string($attr) );
  1435. assert ( is_array($values) );
  1436. foreach ( $values as $id=>$entry )
  1437. {
  1438. assert ( is_numeric($id) );
  1439. assert ( is_array($entry) );
  1440. assert ( count($entry)==count($attrs) );
  1441. foreach ( $entry as $v )
  1442. {
  1443. if ( $mva )
  1444. {
  1445. assert ( is_array($v) );
  1446. foreach ( $v as $vv )
  1447. assert ( is_int($vv) );
  1448. } else
  1449. assert ( is_int($v) );
  1450. }
  1451. }
  1452. // build request
  1453. $this->_MBPush ();
  1454. $req = pack ( "N", strlen($index) ) . $index;
  1455. $req .= pack ( "N", count($attrs) );
  1456. $req .= pack ( "N", $ignorenonexistent ? 1 : 0 );
  1457. foreach ( $attrs as $attr )
  1458. {
  1459. $req .= pack ( "N", strlen($attr) ) . $attr;
  1460. $req .= pack ( "N", $mva ? 1 : 0 );
  1461. }
  1462. $req .= pack ( "N", count($values) );
  1463. foreach ( $values as $id=>$entry )
  1464. {
  1465. $req .= sphPackU64 ( $id );
  1466. foreach ( $entry as $v )
  1467. {
  1468. $req .= pack ( "N", $mva ? count($v) : $v );
  1469. if ( $mva )
  1470. foreach ( $v as $vv )
  1471. $req .= pack ( "N", $vv );
  1472. }
  1473. }
  1474. // connect, send query, get response
  1475. if (!( $fp = $this->_Connect() ))
  1476. {
  1477. $this->_MBPop ();
  1478. return -1;
  1479. }
  1480. $len = strlen($req);
  1481. $req = pack ( "nnN", SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, $len ) . $req; // add header
  1482. if ( !$this->_Send ( $fp, $req, $len+8 ) )
  1483. {
  1484. $this->_MBPop ();
  1485. return -1;
  1486. }
  1487. if (!( $response = $this->_GetResponse ( $fp, VER_COMMAND_UPDATE ) ))
  1488. {
  1489. $this->_MBPop ();
  1490. return -1;
  1491. }
  1492. // parse response
  1493. list(,$updated) = unpack ( "N*", substr ( $response, 0, 4 ) );
  1494. $this->_MBPop ();
  1495. return $updated;
  1496. }
  1497. /////////////////////////////////////////////////////////////////////////////
  1498. // persistent connections
  1499. /////////////////////////////////////////////////////////////////////////////
  1500. function Open()
  1501. {
  1502. if ( $this->_socket !== false )
  1503. {
  1504. $this->_error = 'already connected';
  1505. return false;
  1506. }
  1507. if ( !$fp = $this->_Connect() )
  1508. return false;
  1509. // command, command version = 0, body length = 4, body = 1
  1510. $req = pack ( "nnNN", SEARCHD_COMMAND_PERSIST, 0, 4, 1 );
  1511. if ( !$this->_Send ( $fp, $req, 12 ) )
  1512. return false;
  1513. $this->_socket = $fp;
  1514. return true;
  1515. }
  1516. function Close()
  1517. {
  1518. if ( $this->_socket === false )
  1519. {
  1520. $this->_error = 'not connected';
  1521. return false;
  1522. }
  1523. fclose ( $this->_socket );
  1524. $this->_socket = false;
  1525. return true;
  1526. }
  1527. //////////////////////////////////////////////////////////////////////////
  1528. // status
  1529. //////////////////////////////////////////////////////////////////////////
  1530. function Status ($session=false)
  1531. {
  1532. assert ( is_bool($session) );
  1533. $this->_MBPush ();
  1534. if (!( $fp = $this->_Connect() ))
  1535. {
  1536. $this->_MBPop();
  1537. return false;
  1538. }
  1539. $req = pack ( "nnNN", SEARCHD_COMMAND_STATUS, VER_COMMAND_STATUS, 4, $session?0:1 ); // len=4, body=1
  1540. if ( !( $this->_Send ( $fp, $req, 12 ) ) ||
  1541. !( $response = $this->_GetResponse ( $fp, VER_COMMAND_STATUS ) ) )
  1542. {
  1543. $this->_MBPop ();
  1544. return false;
  1545. }
  1546. $res = substr ( $response, 4 ); // just ignore length, error handling, etc
  1547. $p = 0;
  1548. list ( $rows, $cols ) = array_values ( unpack ( "N*N*", substr ( $response, $p, 8 ) ) ); $p += 8;
  1549. $res = array();
  1550. for ( $i=0; $i<$rows; $i++ )
  1551. for ( $j=0; $j<$cols; $j++ )
  1552. {
  1553. list(,$len) = unpack ( "N*", substr ( $response, $p, 4 ) ); $p += 4;
  1554. $res[$i][] = substr ( $response, $p, $len ); $p += $len;
  1555. }
  1556. $this->_MBPop ();
  1557. return $res;
  1558. }
  1559. //////////////////////////////////////////////////////////////////////////
  1560. // flush
  1561. //////////////////////////////////////////////////////////////////////////
  1562. function FlushAttributes ()
  1563. {
  1564. $this->_MBPush ();
  1565. if (!( $fp = $this->_Connect() ))
  1566. {
  1567. $this->_MBPop();
  1568. return -1;
  1569. }
  1570. $req = pack ( "nnN", SEARCHD_COMMAND_FLUSHATTRS, VER_COMMAND_FLUSHATTRS, 0 ); // len=0
  1571. if ( !( $this->_Send ( $fp, $req, 8 ) ) ||
  1572. !( $response = $this->_GetResponse ( $fp, VER_COMMAND_FLUSHATTRS ) ) )
  1573. {
  1574. $this->_MBPop ();
  1575. return -1;
  1576. }
  1577. $tag = -1;
  1578. if ( strlen($response)==4 )
  1579. list(,$tag) = unpack ( "N*", $response );
  1580. else
  1581. $this->_error = "unexpected response length";
  1582. $this->_MBPop ();
  1583. return $tag;
  1584. }
  1585. }
  1586. //
  1587. // $Id$
  1588. //