sphinxapi.php 54 KB

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