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