sphinxapi.php 54 KB

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