sphinxapi.php 50 KB

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