]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/search/SearchMySQL.php
MediaWiki 1.16.1-scripts
[autoinstalls/mediawiki.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, 'normalizeForSearch' ),
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 normalizeForSearch()
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                 // Some languages such as Chinese require word segmentation
329                 $out = $wgContLang->wordSegmentation( $string );
330
331                 // MySQL fulltext index doesn't grok utf-8, so we
332                 // need to fold cases and convert to hex
333                 $out = preg_replace_callback(
334                         "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
335                         array( $this, 'stripForSearchCallback' ),
336                         $wgContLang->lc( $out ) );
337
338                 // And to add insult to injury, the default indexing
339                 // ignores short words... Pad them so we can pass them
340                 // through without reconfiguring the server...
341                 $minLength = $this->minSearchLength();
342                 if( $minLength > 1 ) {
343                         $n = $minLength - 1;
344                         $out = preg_replace(
345                                 "/\b(\w{1,$n})\b/",
346                                 "$1u800",
347                                 $out );
348                 }
349
350                 // Periods within things like hostnames and IP addresses
351                 // are also important -- we want a search for "example.com"
352                 // or "192.168.1.1" to work sanely.
353                 //
354                 // MySQL's search seems to ignore them, so you'd match on
355                 // "example.wikipedia.com" and "192.168.83.1" as well.
356                 $out = preg_replace(
357                         "/(\w)\.(\w|\*)/u",
358                         "$1u82e$2",
359                         $out );
360
361                 wfProfileOut( __METHOD__ );
362                 
363                 return $out;
364         }
365
366         /**
367          * Armor a case-folded UTF-8 string to get through MySQL's
368          * fulltext search without being mucked up by funny charset
369          * settings or anything else of the sort.
370          */
371         protected function stripForSearchCallback( $matches ) {
372                 return 'u8' . bin2hex( $matches[1] );
373         }
374
375         /**
376          * Check MySQL server's ft_min_word_len setting so we know
377          * if we need to pad short words...
378          * 
379          * @return int
380          */
381         protected function minSearchLength() {
382                 if( is_null( self::$mMinSearchLength ) ) {
383                         $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
384
385                         $dbr = wfGetDB( DB_SLAVE );
386                         $result = $dbr->query( $sql );
387                         $row = $result->fetchObject();
388                         $result->free();
389
390                         if( $row && $row->Variable_name == 'ft_min_word_len' ) {
391                                 self::$mMinSearchLength = intval( $row->Value );
392                         } else {
393                                 self::$mMinSearchLength = 0;
394                         }
395                 }
396                 return self::$mMinSearchLength;
397         }
398 }
399
400 /**
401  * @ingroup Search
402  */
403 class MySQLSearchResultSet extends SqlSearchResultSet {
404         function MySQLSearchResultSet( $resultSet, $terms, $totalHits=null ) {
405                 parent::__construct( $resultSet, $terms );
406                 $this->mTotalHits = $totalHits;
407         }
408
409         function getTotalHits() {
410                 return $this->mTotalHits;
411         }
412 }