2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
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.
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.
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
26 * Search engine hook for MySQL 4+
29 class SearchMySQL
extends SearchEngine
{
30 var $strictMatching = true;
33 function __construct( $db ) {
38 * Parse the user's query and transform it into an SQL fragment which will
39 * become part of a WHERE clause
41 function parseQuery( $filteredText, $fulltext ) {
43 $lc = SearchEngine
::legalSearchChars(); // Minus format chars
45 $this->searchTerms
= array();
47 # FIXME: This doesn't handle parenthetical expressions.
49 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
50 $filteredText, $m, PREG_SET_ORDER
) ) {
51 foreach( $m as $bits ) {
52 @list
( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
54 if( $nonQuoted != '' ) {
58 $term = str_replace( '"', '', $term );
62 if( $searchon !== '' ) $searchon .= ' ';
63 if( $this->strictMatching
&& ($modifier == '') ) {
64 // If we leave this out, boolean op defaults to OR which is rarely helpful.
68 // Some languages such as Serbian store the input form in the search index,
69 // so we may need to search for matches in multiple writing system variants.
70 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
71 if( is_array( $convertedVariants ) ) {
72 $variants = array_unique( array_values( $convertedVariants ) );
74 $variants = array( $term );
77 // The low-level search index does some processing on input to work
78 // around problems with minimum lengths and encoding in MySQL's
80 // For Chinese this also inserts spaces between adjacent Han characters.
81 $strippedVariants = array_map(
82 array( $wgContLang, 'stripForSearch' ),
85 // Some languages such as Chinese force all variants to a canonical
86 // form when stripping to the low-level search index, so to be sure
87 // let's check our variants list for unique items after stripping.
88 $strippedVariants = array_unique( $strippedVariants );
90 $searchon .= $modifier;
91 if( count( $strippedVariants) > 1 )
93 foreach( $strippedVariants as $stripped ) {
94 if( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
95 // Hack for Chinese: we need to toss in quotes for
96 // multiple-character phrases since stripForSearch()
97 // added spaces between them to make word breaks.
98 $stripped = '"' . trim( $stripped ) . '"';
100 $searchon .= "$quote$stripped$quote$wildcard ";
102 if( count( $strippedVariants) > 1 )
105 // Match individual terms or quoted phrase in result highlighting...
106 // Note that variants will be introduced in a later stage for highlighting!
107 $regexp = $this->regexTerm( $term, $wildcard );
108 $this->searchTerms
[] = $regexp;
110 wfDebug( __METHOD__
. ": Would search with '$searchon'\n" );
111 wfDebug( __METHOD__
. ': Match with /' . implode( '|', $this->searchTerms
) . "/\n" );
113 wfDebug( __METHOD__
. ": Can't understand search query '{$filteredText}'\n" );
116 $searchon = $this->db
->strencode( $searchon );
117 $field = $this->getIndexField( $fulltext );
118 return " MATCH($field) AGAINST('$searchon' IN BOOLEAN MODE) ";
121 function regexTerm( $string, $wildcard ) {
124 $regex = preg_quote( $string, '/' );
125 if( $wgContLang->hasWordBreaks() ) {
127 // Don't cut off the final bit!
130 $regex = "\b$regex\b";
133 // For Chinese, words may legitimately abut other words in the text literal.
134 // Don't add \b boundary checks... note this could cause false positives
140 public static function legalSearchChars() {
141 return "\"*" . parent
::legalSearchChars();
145 * Perform a full text search query and return a result set.
147 * @param $term String: raw search term
148 * @return MySQLSearchResultSet
150 function searchText( $term ) {
151 global $wgSearchMySQLTotalHits;
153 $filteredTerm = $this->filter( $term );
154 $resultSet = $this->db
->query( $this->getQuery( $filteredTerm, true ) );
157 if( $wgSearchMySQLTotalHits ) {
158 $totalResult = $this->db
->query( $this->getCountQuery( $filteredTerm, true ) );
159 $row = $totalResult->fetchObject();
163 $totalResult->free();
166 return new MySQLSearchResultSet( $resultSet, $this->searchTerms
, $total );
170 * Perform a title-only search query and return a result set.
172 * @param $term String: raw search term
173 * @return MySQLSearchResultSet
175 function searchTitle( $term ) {
176 $resultSet = $this->db
->resultObject( $this->db
->query( $this->getQuery( $this->filter( $term ), false ) ) );
177 return new MySQLSearchResultSet( $resultSet, $this->searchTerms
);
182 * Return a partial WHERE clause to exclude redirects, if so set
185 function queryRedirect() {
186 if( $this->showRedirects
) {
189 return 'AND page_is_redirect=0';
194 * Return a partial WHERE clause to limit the search to the given namespaces
197 function queryNamespaces() {
198 if( is_null($this->namespaces
) )
199 return ''; # search all
200 if ( !count( $this->namespaces
) ) {
203 $namespaces = $this->db
->makeList( $this->namespaces
);
205 return 'AND page_namespace IN (' . $namespaces . ')';
209 * Return a LIMIT clause to limit results on the query.
212 function queryLimit() {
213 return $this->db
->limitResult( '', $this->limit
, $this->offset
);
217 * Does not do anything for generic search engine
218 * subclasses may define this though
221 function queryRanking( $filteredTerm, $fulltext ) {
226 * Construct the full SQL query to do the search.
227 * The guts shoulds be constructed in queryMain()
228 * @param $filteredTerm String
229 * @param $fulltext Boolean
231 function getQuery( $filteredTerm, $fulltext ) {
232 return $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
233 $this->queryRedirect() . ' ' .
234 $this->queryNamespaces() . ' ' .
235 $this->queryRanking( $filteredTerm, $fulltext ) . ' ' .
240 * Picks which field to index on, depending on what type of query.
241 * @param $fulltext Boolean
244 function getIndexField( $fulltext ) {
245 return $fulltext ?
'si_text' : 'si_title';
249 * Get the base part of the search query.
250 * The actual match syntax will depend on the server
251 * version; MySQL 3 and MySQL 4 have different capabilities
252 * in their fulltext search indexes.
254 * @param $filteredTerm String
255 * @param $fulltext Boolean
258 function queryMain( $filteredTerm, $fulltext ) {
259 $match = $this->parseQuery( $filteredTerm, $fulltext );
260 $page = $this->db
->tableName( 'page' );
261 $searchindex = $this->db
->tableName( 'searchindex' );
262 return 'SELECT page_id, page_namespace, page_title ' .
263 "FROM $page,$searchindex " .
264 'WHERE page_id=si_page AND ' . $match;
267 function getCountQuery( $filteredTerm, $fulltext ) {
268 $match = $this->parseQuery( $filteredTerm, $fulltext );
269 $page = $this->db
->tableName( 'page' );
270 $searchindex = $this->db
->tableName( 'searchindex' );
271 return "SELECT COUNT(*) AS c " .
272 "FROM $page,$searchindex " .
273 'WHERE page_id=si_page AND ' . $match .
274 $this->queryRedirect() . ' ' .
275 $this->queryNamespaces();
279 * Create or update the search index record for the given page.
280 * Title and text should be pre-processed.
283 * @param $title String
284 * @param $text String
286 function update( $id, $title, $text ) {
287 $dbw = wfGetDB( DB_MASTER
);
288 $dbw->replace( 'searchindex',
292 'si_title' => $title,
298 * Update a search index record's title only.
299 * Title should be pre-processed.
302 * @param $title String
304 function updateTitle( $id, $title ) {
305 $dbw = wfGetDB( DB_MASTER
);
307 $dbw->update( 'searchindex',
308 array( 'si_title' => $title ),
309 array( 'si_page' => $id ),
311 array( $dbw->lowPriorityOption() ) );
318 class MySQLSearchResultSet
extends SearchResultSet
{
319 function MySQLSearchResultSet( $resultSet, $terms, $totalHits=null ) {
320 $this->mResultSet
= $resultSet;
321 $this->mTerms
= $terms;
322 $this->mTotalHits
= $totalHits;
325 function termMatches() {
326 return $this->mTerms
;
330 return $this->mResultSet
->numRows();
334 $row = $this->mResultSet
->fetchObject();
335 if( $row === false ) {
338 return new SearchResult( $row );
343 $this->mResultSet
->free();
347 function getTotalHits() {
348 return $this->mTotalHits
;