sphinxapi.php 53 KB

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