sphinxapi.php 51 KB

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