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