53c093e7f7bbcda2107d7eeec04490a2005b7bc0
[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 // Cached because SearchUpdate keeps recreating our class
30 private static $fulltextSupported = null;
31
32 /**
33 * Creates an instance of this class
34 * @param $db DatabaseSqlite: database object
35 */
36 function __construct( $db ) {
37 $this->db = $db;
38 }
39
40 /**
41 * Whether fulltext search is supported by current schema
42 * @return Boolean
43 */
44 function fulltextSearchSupported() {
45 if ( self::$fulltextSupported === null ) {
46 self::$fulltextSupported = $this->db->selectField(
47 'updatelog',
48 'ul_key',
49 array( 'ul_key' => 'fts3' ),
50 __METHOD__ ) !== false;
51 }
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 $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
81 // Some languages such as Serbian store the input form in the search index,
82 // so we may need to search for matches in multiple writing system variants.
83 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
84 if( is_array( $convertedVariants ) ) {
85 $variants = array_unique( array_values( $convertedVariants ) );
86 } else {
87 $variants = array( $term );
88 }
89
90 // The low-level search index does some processing on input to work
91 // around problems with minimum lengths and encoding in MySQL's
92 // fulltext engine.
93 // For Chinese this also inserts spaces between adjacent Han characters.
94 $strippedVariants = array_map(
95 array( $wgContLang, 'stripForSearch' ),
96 $variants );
97
98 // Some languages such as Chinese force all variants to a canonical
99 // form when stripping to the low-level search index, so to be sure
100 // let's check our variants list for unique items after stripping.
101 $strippedVariants = array_unique( $strippedVariants );
102
103 $searchon .= $modifier;
104 if( count( $strippedVariants) > 1 )
105 $searchon .= '(';
106 foreach( $strippedVariants as $stripped ) {
107 if( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
108 // Hack for Chinese: we need to toss in quotes for
109 // multiple-character phrases since stripForSearch()
110 // added spaces between them to make word breaks.
111 $stripped = '"' . trim( $stripped ) . '"';
112 }
113 $searchon .= "$quote$stripped$quote$wildcard ";
114 }
115 if( count( $strippedVariants) > 1 )
116 $searchon .= ')';
117
118 // Match individual terms or quoted phrase in result highlighting...
119 // Note that variants will be introduced in a later stage for highlighting!
120 $regexp = $this->regexTerm( $term, $wildcard );
121 $this->searchTerms[] = $regexp;
122 }
123
124 } else {
125 wfDebug( __METHOD__ . ": Can't understand search query '{$filteredText}'\n" );
126 }
127
128 $searchon = $this->db->strencode( $searchon );
129 $field = $this->getIndexField( $fulltext );
130 return " $field MATCH '$searchon' ";
131 }
132
133 function regexTerm( $string, $wildcard ) {
134 global $wgContLang;
135
136 $regex = preg_quote( $string, '/' );
137 if( $wgContLang->hasWordBreaks() ) {
138 if( $wildcard ) {
139 // Don't cut off the final bit!
140 $regex = "\b$regex";
141 } else {
142 $regex = "\b$regex\b";
143 }
144 } else {
145 // For Chinese, words may legitimately abut other words in the text literal.
146 // Don't add \b boundary checks... note this could cause false positives
147 // for latin chars.
148 }
149 return $regex;
150 }
151
152 public static function legalSearchChars() {
153 return "\"*" . parent::legalSearchChars();
154 }
155
156 /**
157 * Perform a full text search query and return a result set.
158 *
159 * @param $term String: raw search term
160 * @return SqliteSearchResultSet
161 */
162 function searchText( $term ) {
163 return $this->searchInternal( $term, true );
164 }
165
166 /**
167 * Perform a title-only search query and return a result set.
168 *
169 * @param $term String: raw search term
170 * @return SqliteSearchResultSet
171 */
172 function searchTitle( $term ) {
173 return $this->searchInternal( $term, false );
174 }
175
176 protected function searchInternal( $term, $fulltext ) {
177 global $wgCountTotalSearchHits, $wgContLang;
178
179 if ( !$this->fulltextSearchSupported() ) {
180 return null;
181 }
182
183 $filteredTerm = $this->filter( $wgContLang->lc( $term ) );
184 $resultSet = $this->db->query( $this->getQuery( $filteredTerm, $fulltext ) );
185
186 $total = null;
187 if( $wgCountTotalSearchHits ) {
188 $totalResult = $this->db->query( $this->getCountQuery( $filteredTerm, $fulltext ) );
189 $row = $totalResult->fetchObject();
190 if( $row ) {
191 $total = intval( $row->c );
192 }
193 $totalResult->free();
194 }
195
196 return new SqliteSearchResultSet( $resultSet, $this->searchTerms, $total );
197 }
198
199
200 /**
201 * Return a partial WHERE clause to exclude redirects, if so set
202 * @return String
203 */
204 function queryRedirect() {
205 if( $this->showRedirects ) {
206 return '';
207 } else {
208 return 'AND page_is_redirect=0';
209 }
210 }
211
212 /**
213 * Return a partial WHERE clause to limit the search to the given namespaces
214 * @return String
215 */
216 function queryNamespaces() {
217 if( is_null($this->namespaces) )
218 return ''; # search all
219 if ( !count( $this->namespaces ) ) {
220 $namespaces = '0';
221 } else {
222 $namespaces = $this->db->makeList( $this->namespaces );
223 }
224 return 'AND page_namespace IN (' . $namespaces . ')';
225 }
226
227 /**
228 * Returns a query with limit for number of results set.
229 * @param $sql String:
230 * @return String
231 */
232 function limitResult( $sql ) {
233 return $this->db->limitResult( $sql, $this->limit, $this->offset );
234 }
235
236 /**
237 * Construct the full SQL query to do the search.
238 * The guts shoulds be constructed in queryMain()
239 * @param $filteredTerm String
240 * @param $fulltext Boolean
241 */
242 function getQuery( $filteredTerm, $fulltext ) {
243 return $this->limitResult(
244 $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
245 $this->queryRedirect() . ' ' .
246 $this->queryNamespaces()
247 );
248 }
249
250 /**
251 * Picks which field to index on, depending on what type of query.
252 * @param $fulltext Boolean
253 * @return String
254 */
255 function getIndexField( $fulltext ) {
256 return $fulltext ? 'si_text' : 'si_title';
257 }
258
259 /**
260 * Get the base part of the search query.
261 *
262 * @param $filteredTerm String
263 * @param $fulltext Boolean
264 * @return String
265 */
266 function queryMain( $filteredTerm, $fulltext ) {
267 $match = $this->parseQuery( $filteredTerm, $fulltext );
268 $page = $this->db->tableName( 'page' );
269 $searchindex = $this->db->tableName( 'searchindex' );
270 return "SELECT $searchindex.rowid, page_namespace, page_title " .
271 "FROM $page,$searchindex " .
272 "WHERE page_id=$searchindex.rowid AND $match";
273 }
274
275 function getCountQuery( $filteredTerm, $fulltext ) {
276 $match = $this->parseQuery( $filteredTerm, $fulltext );
277 $page = $this->db->tableName( 'page' );
278 $searchindex = $this->db->tableName( 'searchindex' );
279 return "SELECT COUNT(*) AS c " .
280 "FROM $page,$searchindex " .
281 "WHERE page_id=$searchindex.rowid AND $match" .
282 $this->queryRedirect() . ' ' .
283 $this->queryNamespaces();
284 }
285
286 /**
287 * Create or update the search index record for the given page.
288 * Title and text should be pre-processed.
289 *
290 * @param $id Integer
291 * @param $title String
292 * @param $text String
293 */
294 function update( $id, $title, $text ) {
295 if ( !$this->fulltextSearchSupported() ) {
296 return;
297 }
298 // @todo: find a method to do it in a single request,
299 // couldn't do it so far due to typelessness of FTS3 tables.
300 $dbw = wfGetDB( DB_MASTER );
301
302 $dbw->delete( 'searchindex', array( 'rowid' => $id ), __METHOD__ );
303
304 $dbw->insert( 'searchindex',
305 array(
306 'rowid' => $id,
307 'si_title' => $title,
308 'si_text' => $text
309 ), __METHOD__ );
310 }
311
312 /**
313 * Update a search index record's title only.
314 * Title should be pre-processed.
315 *
316 * @param $id Integer
317 * @param $title String
318 */
319 function updateTitle( $id, $title ) {
320 if ( !$this->fulltextSearchSupported() ) {
321 return;
322 }
323 $dbw = wfGetDB( DB_MASTER );
324
325 $dbw->update( 'searchindex',
326 array( 'rowid' => $id ),
327 array( 'si_title' => $title ),
328 __METHOD__ );
329 }
330 }
331
332 /**
333 * @ingroup Search
334 */
335 class SqliteSearchResultSet extends SqlSearchResultSet {
336 function SqliteSearchResultSet( $resultSet, $terms, $totalHits=null ) {
337 parent::__construct( $resultSet, $terms );
338 $this->mTotalHits = $totalHits;
339 }
340
341 function getTotalHits() {
342 return $this->mTotalHits;
343 }
344 }