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