Match lowercase titles in SearchSqlite
[lhc/web/wiklou.git] / includes / search / SearchSqlite.php
1 <?php
2 # SQLite search backend, based upon SearchMysql
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 # http://www.gnu.org/copyleft/gpl.html
18
19 /**
20 * @file
21 * @ingroup Search
22 */
23
24 /**
25 * Search engine hook for SQLite
26 * @ingroup Search
27 */
28 class SearchSqlite extends SearchEngine {
29 var $strictMatching = true;
30
31 // Cached because SearchUpdate keeps recreating our class
32 private static $fulltextSupported = NULL;
33
34 /**
35 * Creates an instance of this class
36 * @param $db DatabaseSqlite: database object
37 */
38 function __construct( $db ) {
39 $this->db = $db;
40 }
41
42 /**
43 * Whether fulltext search is supported by current schema
44 * @return Boolean
45 */
46 function fulltextSearchSupported() {
47 if ( self::$fulltextSupported === NULL ) {
48 $res = $this->db->selectField( 'updatelog', 'ul_key', array( 'ul_key' => 'fts3' ), __METHOD__ );
49 self::$fulltextSupported = $res && $this->db->numRows( $res ) > 0;
50 }
51 return self::$fulltextSupported;
52 }
53
54 /**
55 * Parse the user's query and transform it into an SQL fragment which will
56 * become part of a WHERE clause
57 */
58 function parseQuery( $filteredText, $fulltext ) {
59 global $wgContLang;
60 $lc = SearchEngine::legalSearchChars(); // Minus format chars
61 $searchon = '';
62 $this->searchTerms = array();
63
64 # FIXME: This doesn't handle parenthetical expressions.
65 $m = array();
66 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
67 $filteredText, $m, PREG_SET_ORDER ) ) {
68 foreach( $m as $bits ) {
69 @list( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
70
71 if( $nonQuoted != '' ) {
72 $term = $nonQuoted;
73 $quote = '';
74 } else {
75 $term = str_replace( '"', '', $term );
76 $quote = '"';
77 }
78
79 if( $searchon !== '' ) $searchon .= ' ';
80 if( $this->strictMatching && ($modifier == '') ) {
81 // If we leave this out, boolean op defaults to OR which is rarely helpful.
82 $modifier = '+';
83 }
84
85 // Some languages such as Serbian store the input form in the search index,
86 // so we may need to search for matches in multiple writing system variants.
87 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
88 if( is_array( $convertedVariants ) ) {
89 $variants = array_unique( array_values( $convertedVariants ) );
90 } else {
91 $variants = array( $term );
92 }
93
94 // The low-level search index does some processing on input to work
95 // around problems with minimum lengths and encoding in MySQL's
96 // fulltext engine.
97 // For Chinese this also inserts spaces between adjacent Han characters.
98 $strippedVariants = array_map(
99 array( $wgContLang, 'stripForSearch' ),
100 $variants );
101
102 // Some languages such as Chinese force all variants to a canonical
103 // form when stripping to the low-level search index, so to be sure
104 // let's check our variants list for unique items after stripping.
105 $strippedVariants = array_unique( $strippedVariants );
106
107 $searchon .= $modifier;
108 if( count( $strippedVariants) > 1 )
109 $searchon .= '(';
110 foreach( $strippedVariants as $stripped ) {
111 if( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
112 // Hack for Chinese: we need to toss in quotes for
113 // multiple-character phrases since stripForSearch()
114 // added spaces between them to make word breaks.
115 $stripped = '"' . trim( $stripped ) . '"';
116 }
117 $searchon .= "$quote$stripped$quote$wildcard ";
118 }
119 if( count( $strippedVariants) > 1 )
120 $searchon .= ')';
121
122 // Match individual terms or quoted phrase in result highlighting...
123 // Note that variants will be introduced in a later stage for highlighting!
124 $regexp = $this->regexTerm( $term, $wildcard );
125 $this->searchTerms[] = $regexp;
126 }
127 wfDebug( __METHOD__ . ": Would search with '$searchon'\n" );
128 wfDebug( __METHOD__ . ': Match with /' . implode( '|', $this->searchTerms ) . "/\n" );
129 } else {
130 wfDebug( __METHOD__ . ": Can't understand search query '{$filteredText}'\n" );
131 }
132
133 $searchon = $this->db->strencode( $searchon );
134 $field = $this->getIndexField( $fulltext );
135 return " $field MATCH '$searchon' ";
136 }
137
138 function regexTerm( $string, $wildcard ) {
139 global $wgContLang;
140
141 $regex = preg_quote( $string, '/' );
142 if( $wgContLang->hasWordBreaks() ) {
143 if( $wildcard ) {
144 // Don't cut off the final bit!
145 $regex = "\b$regex";
146 } else {
147 $regex = "\b$regex\b";
148 }
149 } else {
150 // For Chinese, words may legitimately abut other words in the text literal.
151 // Don't add \b boundary checks... note this could cause false positives
152 // for latin chars.
153 }
154 return $regex;
155 }
156
157 public static function legalSearchChars() {
158 return "\"*" . parent::legalSearchChars();
159 }
160
161 /**
162 * Perform a full text search query and return a result set.
163 *
164 * @param $term String: raw search term
165 * @return SqliteSearchResultSet
166 */
167 function searchText( $term ) {
168 return $this->searchInternal( $term, true );
169 }
170
171 /**
172 * Perform a title-only search query and return a result set.
173 *
174 * @param $term String: raw search term
175 * @return SqliteSearchResultSet
176 */
177 function searchTitle( $term ) {
178 return $this->searchInternal( $term, false );
179 }
180
181 protected function searchInternal( $term, $fulltext ) {
182 global $wgSearchMySQLTotalHits, $wgContLang;
183
184 if ( !$this->fulltextSearchSupported() ) {
185 return null;
186 }
187
188 $filteredTerm = $this->filter( $wgContLang->lc( $term ) );
189 $resultSet = $this->db->query( $this->getQuery( $filteredTerm, $fulltext ) );
190
191 $total = null;
192 if( $wgSearchMySQLTotalHits ) {
193 $totalResult = $this->db->query( $this->getCountQuery( $filteredTerm, $fulltext ) );
194 $row = $totalResult->fetchObject();
195 if( $row ) {
196 $total = intval( $row->c );
197 }
198 $totalResult->free();
199 }
200
201 return new SqliteSearchResultSet( $resultSet, $this->searchTerms, $total );
202 }
203
204
205 /**
206 * Return a partial WHERE clause to exclude redirects, if so set
207 * @return String
208 */
209 function queryRedirect() {
210 if( $this->showRedirects ) {
211 return '';
212 } else {
213 return 'AND page_is_redirect=0';
214 }
215 }
216
217 /**
218 * Return a partial WHERE clause to limit the search to the given namespaces
219 * @return String
220 */
221 function queryNamespaces() {
222 if( is_null($this->namespaces) )
223 return ''; # search all
224 if ( !count( $this->namespaces ) ) {
225 $namespaces = '0';
226 } else {
227 $namespaces = $this->db->makeList( $this->namespaces );
228 }
229 return 'AND page_namespace IN (' . $namespaces . ')';
230 }
231
232 /**
233 * Returns a query with limit for number of results set.
234 * @param $sql String:
235 * @return String
236 */
237 function limitResult( $sql ) {
238 return $this->db->limitResult( $sql, $this->limit, $this->offset );
239 }
240
241 /**
242 * Does not do anything for generic search engine
243 * subclasses may define this though
244 * @return String
245 */
246 function queryRanking( $filteredTerm, $fulltext ) {
247 return '';
248 }
249
250 /**
251 * Construct the full SQL query to do the search.
252 * The guts shoulds be constructed in queryMain()
253 * @param $filteredTerm String
254 * @param $fulltext Boolean
255 */
256 function getQuery( $filteredTerm, $fulltext ) {
257 return $this->limitResult(
258 $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
259 $this->queryRedirect() . ' ' .
260 $this->queryNamespaces() . ' ' .
261 $this->queryRanking( $filteredTerm, $fulltext )
262 );
263 }
264
265 /**
266 * Picks which field to index on, depending on what type of query.
267 * @param $fulltext Boolean
268 * @return String
269 */
270 function getIndexField( $fulltext ) {
271 return $fulltext ? 'si_text' : 'si_title';
272 }
273
274 /**
275 * Get the base part of the search query.
276 *
277 * @param $filteredTerm String
278 * @param $fulltext Boolean
279 * @return String
280 */
281 function queryMain( $filteredTerm, $fulltext ) {
282 $match = $this->parseQuery( $filteredTerm, $fulltext );
283 $page = $this->db->tableName( 'page' );
284 $searchindex = $this->db->tableName( 'searchindex' );
285 return "SELECT $searchindex.rowid, page_namespace, page_title " .
286 "FROM $page,$searchindex " .
287 "WHERE page_id=$searchindex.rowid AND $match";
288 }
289
290 function getCountQuery( $filteredTerm, $fulltext ) {
291 $match = $this->parseQuery( $filteredTerm, $fulltext );
292 $page = $this->db->tableName( 'page' );
293 $searchindex = $this->db->tableName( 'searchindex' );
294 return "SELECT COUNT(*) AS c " .
295 "FROM $page,$searchindex " .
296 "WHERE page_id=$searchindex.rowid AND $match" .
297 $this->queryRedirect() . ' ' .
298 $this->queryNamespaces();
299 }
300
301 /**
302 * Create or update the search index record for the given page.
303 * Title and text should be pre-processed.
304 *
305 * @param $id Integer
306 * @param $title String
307 * @param $text String
308 */
309 function update( $id, $title, $text ) {
310 if ( !$this->fulltextSearchSupported() ) {
311 return;
312 }
313 // @todo: find a method to do it in a single request,
314 // couldn't do it so far due to typelessness of FTS3 tables.
315 $dbw = wfGetDB( DB_MASTER );
316
317 $dbw->delete( 'searchindex', array( 'rowid' => $id ), __METHOD__ );
318
319 $dbw->insert( 'searchindex',
320 array(
321 'rowid' => $id,
322 'si_title' => $title,
323 'si_text' => $text
324 ), __METHOD__ );
325 }
326
327 /**
328 * Update a search index record's title only.
329 * Title should be pre-processed.
330 *
331 * @param $id Integer
332 * @param $title String
333 */
334 function updateTitle( $id, $title ) {
335 if ( !$this->fulltextSearchSupported() ) {
336 return;
337 }
338 $dbw = wfGetDB( DB_MASTER );
339
340 $dbw->update( 'searchindex',
341 array( 'rowid' => $id ),
342 array( 'si_title' => $title ),
343 __METHOD__ );
344 }
345 }
346
347 /**
348 * @ingroup Search
349 */
350 class SqliteSearchResultSet extends SearchResultSet {
351 function SqliteSearchResultSet( $resultSet, $terms, $totalHits=null ) {
352 $this->mResultSet = $resultSet;
353 $this->mTerms = $terms;
354 $this->mTotalHits = $totalHits;
355 }
356
357 function termMatches() {
358 return $this->mTerms;
359 }
360
361 function numRows() {
362 return $this->mResultSet->numRows();
363 }
364
365 function next() {
366 $row = $this->mResultSet->fetchObject();
367 if( $row === false ) {
368 return false;
369 } else {
370 return new SearchResult( $row );
371 }
372 }
373
374 function free() {
375 $this->mResultSet->free();
376 }
377
378
379 function getTotalHits() {
380 return $this->mTotalHits;
381 }
382 }