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