merge latest master into Wikidata branch
[lhc/web/wiklou.git] / includes / search / SearchSqlite.php
1 <?php
2 /**
3 * SQLite search backend, based upon SearchMysql
4 *
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.
9 *
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.
14 *
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
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
30 /**
31 * @var DatabaseSqlite
32 */
33 protected $db;
34
35 /**
36 * Creates an instance of this class
37 * @param $db DatabaseSqlite: database object
38 */
39 function __construct( $db ) {
40 parent::__construct( $db );
41 }
42
43 /**
44 * Whether fulltext search is supported by current schema
45 * @return Boolean
46 */
47 function fulltextSearchSupported() {
48 return $this->db->checkForEnabledSearch();
49 }
50
51 /**
52 * Parse the user's query and transform it into an SQL fragment which will
53 * become part of a WHERE clause
54 *
55 * @return string
56 */
57 function parseQuery( $filteredText, $fulltext ) {
58 global $wgContLang;
59 $lc = SearchEngine::legalSearchChars(); // Minus format chars
60 $searchon = '';
61 $this->searchTerms = array();
62
63 $m = array();
64 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
65 $filteredText, $m, PREG_SET_ORDER ) ) {
66 foreach( $m as $bits ) {
67 @list( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
68
69 if( $nonQuoted != '' ) {
70 $term = $nonQuoted;
71 $quote = '';
72 } else {
73 $term = str_replace( '"', '', $term );
74 $quote = '"';
75 }
76
77 if( $searchon !== '' ) {
78 $searchon .= ' ';
79 }
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, 'normalizeForSearch' ),
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 normalizeForSearch()
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 * @return String
242 */
243 function getQuery( $filteredTerm, $fulltext ) {
244 return $this->limitResult(
245 $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
246 $this->queryRedirect() . ' ' .
247 $this->queryNamespaces()
248 );
249 }
250
251 /**
252 * Picks which field to index on, depending on what type of query.
253 * @param $fulltext Boolean
254 * @return String
255 */
256 function getIndexField( $fulltext ) {
257 return $fulltext ? 'si_text' : 'si_title';
258 }
259
260 /**
261 * Get the base part of the search query.
262 *
263 * @param $filteredTerm String
264 * @param $fulltext Boolean
265 * @return String
266 */
267 function queryMain( $filteredTerm, $fulltext ) {
268 $match = $this->parseQuery( $filteredTerm, $fulltext );
269 $page = $this->db->tableName( 'page' );
270 $searchindex = $this->db->tableName( 'searchindex' );
271 return "SELECT $searchindex.rowid, page_namespace, page_title " .
272 "FROM $page,$searchindex " .
273 "WHERE page_id=$searchindex.rowid AND $match";
274 }
275
276 function getCountQuery( $filteredTerm, $fulltext ) {
277 $match = $this->parseQuery( $filteredTerm, $fulltext );
278 $page = $this->db->tableName( 'page' );
279 $searchindex = $this->db->tableName( 'searchindex' );
280 return "SELECT COUNT(*) AS c " .
281 "FROM $page,$searchindex " .
282 "WHERE page_id=$searchindex.rowid AND $match" .
283 $this->queryRedirect() . ' ' .
284 $this->queryNamespaces();
285 }
286
287 /**
288 * Create or update the search index record for the given page.
289 * Title and text should be pre-processed.
290 *
291 * @param $id Integer
292 * @param $title String
293 * @param $text String
294 */
295 function update( $id, $title, $text ) {
296 if ( !$this->fulltextSearchSupported() ) {
297 return;
298 }
299 // @todo: find a method to do it in a single request,
300 // couldn't do it so far due to typelessness of FTS3 tables.
301 $dbw = wfGetDB( DB_MASTER );
302
303 $dbw->delete( 'searchindex', array( 'rowid' => $id ), __METHOD__ );
304
305 $dbw->insert( 'searchindex',
306 array(
307 'rowid' => $id,
308 'si_title' => $title,
309 'si_text' => $text
310 ), __METHOD__ );
311 }
312
313 /**
314 * Update a search index record's title only.
315 * Title should be pre-processed.
316 *
317 * @param $id Integer
318 * @param $title String
319 */
320 function updateTitle( $id, $title ) {
321 if ( !$this->fulltextSearchSupported() ) {
322 return;
323 }
324 $dbw = wfGetDB( DB_MASTER );
325
326 $dbw->update( 'searchindex',
327 array( 'si_title' => $title ),
328 array( 'rowid' => $id ),
329 __METHOD__ );
330 }
331 }
332
333 /**
334 * @ingroup Search
335 */
336 class SqliteSearchResultSet extends SqlSearchResultSet {
337 function __construct( $resultSet, $terms, $totalHits=null ) {
338 parent::__construct( $resultSet, $terms );
339 $this->mTotalHits = $totalHits;
340 }
341
342 function getTotalHits() {
343 return $this->mTotalHits;
344 }
345 }