Fixed r61214: moved MySQL munging to SearchEngine, updated calls. Can we kill $doStri...
[lhc/web/wiklou.git] / includes / search / SearchMySQL.php
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21 * @file
22 * @ingroup Search
23 */
24
25 /**
26 * Search engine hook for MySQL 4+
27 * @ingroup Search
28 */
29 class SearchMySQL extends SearchEngine {
30 var $strictMatching = true;
31 static $mMinSearchLength;
32
33 /** @todo document */
34 function __construct( $db ) {
35 $this->db = $db;
36 }
37
38 /**
39 * Parse the user's query and transform it into an SQL fragment which will
40 * become part of a WHERE clause
41 */
42 function parseQuery( $filteredText, $fulltext ) {
43 global $wgContLang;
44 $lc = SearchEngine::legalSearchChars(); // Minus format chars
45 $searchon = '';
46 $this->searchTerms = array();
47
48 # FIXME: This doesn't handle parenthetical expressions.
49 $m = array();
50 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
51 $filteredText, $m, PREG_SET_ORDER ) ) {
52 foreach( $m as $bits ) {
53 @list( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
54
55 if( $nonQuoted != '' ) {
56 $term = $nonQuoted;
57 $quote = '';
58 } else {
59 $term = str_replace( '"', '', $term );
60 $quote = '"';
61 }
62
63 if( $searchon !== '' ) $searchon .= ' ';
64 if( $this->strictMatching && ($modifier == '') ) {
65 // If we leave this out, boolean op defaults to OR which is rarely helpful.
66 $modifier = '+';
67 }
68
69 // Some languages such as Serbian store the input form in the search index,
70 // so we may need to search for matches in multiple writing system variants.
71 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
72 if( is_array( $convertedVariants ) ) {
73 $variants = array_unique( array_values( $convertedVariants ) );
74 } else {
75 $variants = array( $term );
76 }
77
78 // The low-level search index does some processing on input to work
79 // around problems with minimum lengths and encoding in MySQL's
80 // fulltext engine.
81 // For Chinese this also inserts spaces between adjacent Han characters.
82 $strippedVariants = array_map(
83 array( $wgContLang, 'stripForSearch' ),
84 $variants );
85
86 // Some languages such as Chinese force all variants to a canonical
87 // form when stripping to the low-level search index, so to be sure
88 // let's check our variants list for unique items after stripping.
89 $strippedVariants = array_unique( $strippedVariants );
90
91 $searchon .= $modifier;
92 if( count( $strippedVariants) > 1 )
93 $searchon .= '(';
94 foreach( $strippedVariants as $stripped ) {
95 $stripped = $this->normalizeText( $stripped );
96 if( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
97 // Hack for Chinese: we need to toss in quotes for
98 // multiple-character phrases since stripForSearch()
99 // added spaces between them to make word breaks.
100 $stripped = '"' . trim( $stripped ) . '"';
101 }
102 $searchon .= "$quote$stripped$quote$wildcard ";
103 }
104 if( count( $strippedVariants) > 1 )
105 $searchon .= ')';
106
107 // Match individual terms or quoted phrase in result highlighting...
108 // Note that variants will be introduced in a later stage for highlighting!
109 $regexp = $this->regexTerm( $term, $wildcard );
110 $this->searchTerms[] = $regexp;
111 }
112 wfDebug( __METHOD__ . ": Would search with '$searchon'\n" );
113 wfDebug( __METHOD__ . ': Match with /' . implode( '|', $this->searchTerms ) . "/\n" );
114 } else {
115 wfDebug( __METHOD__ . ": Can't understand search query '{$filteredText}'\n" );
116 }
117
118 $searchon = $this->db->strencode( $searchon );
119 $field = $this->getIndexField( $fulltext );
120 return " MATCH($field) AGAINST('$searchon' IN BOOLEAN MODE) ";
121 }
122
123 function regexTerm( $string, $wildcard ) {
124 global $wgContLang;
125
126 $regex = preg_quote( $string, '/' );
127 if( $wgContLang->hasWordBreaks() ) {
128 if( $wildcard ) {
129 // Don't cut off the final bit!
130 $regex = "\b$regex";
131 } else {
132 $regex = "\b$regex\b";
133 }
134 } else {
135 // For Chinese, words may legitimately abut other words in the text literal.
136 // Don't add \b boundary checks... note this could cause false positives
137 // for latin chars.
138 }
139 return $regex;
140 }
141
142 public static function legalSearchChars() {
143 return "\"*" . parent::legalSearchChars();
144 }
145
146 /**
147 * Perform a full text search query and return a result set.
148 *
149 * @param $term String: raw search term
150 * @return MySQLSearchResultSet
151 */
152 function searchText( $term ) {
153 return $this->searchInternal( $term, true );
154 }
155
156 /**
157 * Perform a title-only search query and return a result set.
158 *
159 * @param $term String: raw search term
160 * @return MySQLSearchResultSet
161 */
162 function searchTitle( $term ) {
163 return $this->searchInternal( $term, false );
164 }
165
166 protected function searchInternal( $term, $fulltext ) {
167 global $wgCountTotalSearchHits;
168
169 $filteredTerm = $this->filter( $term );
170 $resultSet = $this->db->query( $this->getQuery( $filteredTerm, $fulltext ) );
171
172 $total = null;
173 if( $wgCountTotalSearchHits ) {
174 $totalResult = $this->db->query( $this->getCountQuery( $filteredTerm, $fulltext ) );
175 $row = $totalResult->fetchObject();
176 if( $row ) {
177 $total = intval( $row->c );
178 }
179 $totalResult->free();
180 }
181
182 return new MySQLSearchResultSet( $resultSet, $this->searchTerms, $total );
183 }
184
185
186 /**
187 * Return a partial WHERE clause to exclude redirects, if so set
188 * @return String
189 */
190 function queryRedirect() {
191 if( $this->showRedirects ) {
192 return '';
193 } else {
194 return 'AND page_is_redirect=0';
195 }
196 }
197
198 /**
199 * Return a partial WHERE clause to limit the search to the given namespaces
200 * @return String
201 */
202 function queryNamespaces() {
203 if( is_null($this->namespaces) )
204 return ''; # search all
205 if ( !count( $this->namespaces ) ) {
206 $namespaces = '0';
207 } else {
208 $namespaces = $this->db->makeList( $this->namespaces );
209 }
210 return 'AND page_namespace IN (' . $namespaces . ')';
211 }
212
213 /**
214 * Return a LIMIT clause to limit results on the query.
215 * @return String
216 */
217 function queryLimit() {
218 return $this->db->limitResult( '', $this->limit, $this->offset );
219 }
220
221 /**
222 * Does not do anything for generic search engine
223 * subclasses may define this though
224 * @return String
225 */
226 function queryRanking( $filteredTerm, $fulltext ) {
227 return '';
228 }
229
230 /**
231 * Construct the full SQL query to do the search.
232 * The guts shoulds be constructed in queryMain()
233 * @param $filteredTerm String
234 * @param $fulltext Boolean
235 */
236 function getQuery( $filteredTerm, $fulltext ) {
237 return $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
238 $this->queryRedirect() . ' ' .
239 $this->queryNamespaces() . ' ' .
240 $this->queryRanking( $filteredTerm, $fulltext ) . ' ' .
241 $this->queryLimit();
242 }
243
244 /**
245 * Picks which field to index on, depending on what type of query.
246 * @param $fulltext Boolean
247 * @return String
248 */
249 function getIndexField( $fulltext ) {
250 return $fulltext ? 'si_text' : 'si_title';
251 }
252
253 /**
254 * Get the base part of the search query.
255 * The actual match syntax will depend on the server
256 * version; MySQL 3 and MySQL 4 have different capabilities
257 * in their fulltext search indexes.
258 *
259 * @param $filteredTerm String
260 * @param $fulltext Boolean
261 * @return String
262 */
263 function queryMain( $filteredTerm, $fulltext ) {
264 $match = $this->parseQuery( $filteredTerm, $fulltext );
265 $page = $this->db->tableName( 'page' );
266 $searchindex = $this->db->tableName( 'searchindex' );
267 return 'SELECT page_id, page_namespace, page_title ' .
268 "FROM $page,$searchindex " .
269 'WHERE page_id=si_page AND ' . $match;
270 }
271
272 function getCountQuery( $filteredTerm, $fulltext ) {
273 $match = $this->parseQuery( $filteredTerm, $fulltext );
274 $page = $this->db->tableName( 'page' );
275 $searchindex = $this->db->tableName( 'searchindex' );
276 return "SELECT COUNT(*) AS c " .
277 "FROM $page,$searchindex " .
278 'WHERE page_id=si_page AND ' . $match .
279 $this->queryRedirect() . ' ' .
280 $this->queryNamespaces();
281 }
282
283 /**
284 * Create or update the search index record for the given page.
285 * Title and text should be pre-processed.
286 *
287 * @param $id Integer
288 * @param $title String
289 * @param $text String
290 */
291 function update( $id, $title, $text ) {
292 $dbw = wfGetDB( DB_MASTER );
293 $dbw->replace( 'searchindex',
294 array( 'si_page' ),
295 array(
296 'si_page' => $id,
297 'si_title' => $this->normalizeText( $title ),
298 'si_text' => $this->normalizeText( $text )
299 ), __METHOD__ );
300 }
301
302 /**
303 * Update a search index record's title only.
304 * Title should be pre-processed.
305 *
306 * @param $id Integer
307 * @param $title String
308 */
309 function updateTitle( $id, $title ) {
310 $dbw = wfGetDB( DB_MASTER );
311
312 $dbw->update( 'searchindex',
313 array( 'si_title' => $this->normalizeText( $title ) ),
314 array( 'si_page' => $id ),
315 __METHOD__,
316 array( $dbw->lowPriorityOption() ) );
317 }
318
319 /**
320 * Converts some characters for MySQL's indexing to grok it correctly,
321 * and pads short words to overcome limitations.
322 */
323 function normalizeText( $string ) {
324 global $wgContLang;
325
326 wfProfileIn( __METHOD__ );
327
328 // MySQL fulltext index doesn't grok utf-8, so we
329 // need to fold cases and convert to hex
330 $out = preg_replace_callback(
331 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
332 array( $this, 'stripForSearchCallback' ),
333 $wgContLang->lc( $string ) );
334
335 // And to add insult to injury, the default indexing
336 // ignores short words... Pad them so we can pass them
337 // through without reconfiguring the server...
338 $minLength = $this->minSearchLength();
339 if( $minLength > 1 ) {
340 $n = $minLength - 1;
341 $out = preg_replace(
342 "/\b(\w{1,$n})\b/",
343 "$1u800",
344 $out );
345 }
346
347 // Periods within things like hostnames and IP addresses
348 // are also important -- we want a search for "example.com"
349 // or "192.168.1.1" to work sanely.
350 //
351 // MySQL's search seems to ignore them, so you'd match on
352 // "example.wikipedia.com" and "192.168.83.1" as well.
353 $out = preg_replace(
354 "/(\w)\.(\w|\*)/u",
355 "$1u82e$2",
356 $out );
357
358 wfProfileOut( __METHOD__ );
359
360 return $out;
361 }
362
363 /**
364 * Armor a case-folded UTF-8 string to get through MySQL's
365 * fulltext search without being mucked up by funny charset
366 * settings or anything else of the sort.
367 */
368 protected function stripForSearchCallback( $matches ) {
369 return 'u8' . bin2hex( $matches[1] );
370 }
371
372 /**
373 * Check MySQL server's ft_min_word_len setting so we know
374 * if we need to pad short words...
375 *
376 * @return int
377 */
378 protected function minSearchLength() {
379 if( is_null( self::$mMinSearchLength ) ) {
380 $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
381
382 $dbr = wfGetDB( DB_SLAVE );
383 $result = $dbr->query( $sql );
384 $row = $result->fetchObject();
385 $result->free();
386
387 if( $row && $row->Variable_name == 'ft_min_word_len' ) {
388 self::$mMinSearchLength = intval( $row->Value );
389 } else {
390 self::$mMinSearchLength = 0;
391 }
392 }
393 return self::$mMinSearchLength;
394 }
395 }
396
397 /**
398 * @ingroup Search
399 */
400 class MySQLSearchResultSet extends SqlSearchResultSet {
401 function MySQLSearchResultSet( $resultSet, $terms, $totalHits=null ) {
402 parent::__construct( $resultSet, $terms );
403 $this->mTotalHits = $totalHits;
404 }
405
406 function getTotalHits() {
407 return $this->mTotalHits;
408 }
409 }