sphinxapi.php 51 KB

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