docs: Remove odd colons after @todo
[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 }
107 foreach ( $strippedVariants as $stripped ) {
108 if ( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
109 // Hack for Chinese: we need to toss in quotes for
110 // multiple-character phrases since normalizeForSearch()
111 // added spaces between them to make word breaks.
112 $stripped = '"' . trim( $stripped ) . '"';
113 }
114 $searchon .= "$quote$stripped$quote$wildcard ";
115 }
116 if ( count( $strippedVariants ) > 1 ) {
117 $searchon .= ')';
118 }
119
120 // Match individual terms or quoted phrase in result highlighting...
121 // Note that variants will be introduced in a later stage for highlighting!
122 $regexp = $this->regexTerm( $term, $wildcard );
123 $this->searchTerms[] = $regexp;
124 }
125
126 } else {
127 wfDebug( __METHOD__ . ": Can't understand search query '{$filteredText}'\n" );
128 }
129
130 $searchon = $this->db->strencode( $searchon );
131 $field = $this->getIndexField( $fulltext );
132 return " $field MATCH '$searchon' ";
133 }
134
135 function regexTerm( $string, $wildcard ) {
136 global $wgContLang;
137
138 $regex = preg_quote( $string, '/' );
139 if ( $wgContLang->hasWordBreaks() ) {
140 if ( $wildcard ) {
141 // Don't cut off the final bit!
142 $regex = "\b$regex";
143 } else {
144 $regex = "\b$regex\b";
145 }
146 } else {
147 // For Chinese, words may legitimately abut other words in the text literal.
148 // Don't add \b boundary checks... note this could cause false positives
149 // for latin chars.
150 }
151 return $regex;
152 }
153
154 public static function legalSearchChars() {
155 return "\"*" . parent::legalSearchChars();
156 }
157
158 /**
159 * Perform a full text search query and return a result set.
160 *
161 * @param string $term raw search term
162 * @return SqliteSearchResultSet
163 */
164 function searchText( $term ) {
165 return $this->searchInternal( $term, true );
166 }
167
168 /**
169 * Perform a title-only search query and return a result set.
170 *
171 * @param string $term raw search term
172 * @return SqliteSearchResultSet
173 */
174 function searchTitle( $term ) {
175 return $this->searchInternal( $term, false );
176 }
177
178 protected function searchInternal( $term, $fulltext ) {
179 global $wgCountTotalSearchHits, $wgContLang;
180
181 if ( !$this->fulltextSearchSupported() ) {
182 return null;
183 }
184
185 $filteredTerm = $this->filter( $wgContLang->lc( $term ) );
186 $resultSet = $this->db->query( $this->getQuery( $filteredTerm, $fulltext ) );
187
188 $total = null;
189 if ( $wgCountTotalSearchHits ) {
190 $totalResult = $this->db->query( $this->getCountQuery( $filteredTerm, $fulltext ) );
191 $row = $totalResult->fetchObject();
192 if ( $row ) {
193 $total = intval( $row->c );
194 }
195 $totalResult->free();
196 }
197
198 return new SqliteSearchResultSet( $resultSet, $this->searchTerms, $total );
199 }
200
201 /**
202 * Return a partial WHERE clause to exclude redirects, if so set
203 * @return String
204 */
205 function queryRedirect() {
206 if ( $this->showRedirects ) {
207 return '';
208 } else {
209 return 'AND page_is_redirect=0';
210 }
211 }
212
213 /**
214 * Return a partial WHERE clause to limit the search to the given namespaces
215 * @return String
216 */
217 function queryNamespaces() {
218 if ( is_null( $this->namespaces ) ) {
219 return ''; # search all
220 }
221 if ( !count( $this->namespaces ) ) {
222 $namespaces = '0';
223 } else {
224 $namespaces = $this->db->makeList( $this->namespaces );
225 }
226 return 'AND page_namespace IN (' . $namespaces . ')';
227 }
228
229 /**
230 * Returns a query with limit for number of results set.
231 * @param $sql String:
232 * @return String
233 */
234 function limitResult( $sql ) {
235 return $this->db->limitResult( $sql, $this->limit, $this->offset );
236 }
237
238 /**
239 * Construct the full SQL query to do the search.
240 * The guts shoulds be constructed in queryMain()
241 * @param $filteredTerm String
242 * @param $fulltext Boolean
243 * @return String
244 */
245 function getQuery( $filteredTerm, $fulltext ) {
246 return $this->limitResult(
247 $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
248 $this->queryRedirect() . ' ' .
249 $this->queryNamespaces()
250 );
251 }
252
253 /**
254 * Picks which field to index on, depending on what type of query.
255 * @param $fulltext Boolean
256 * @return String
257 */
258 function getIndexField( $fulltext ) {
259 return $fulltext ? 'si_text' : 'si_title';
260 }
261
262 /**
263 * Get the base part of the search query.
264 *
265 * @param $filteredTerm String
266 * @param $fulltext Boolean
267 * @return String
268 */
269 function queryMain( $filteredTerm, $fulltext ) {
270 $match = $this->parseQuery( $filteredTerm, $fulltext );
271 $page = $this->db->tableName( 'page' );
272 $searchindex = $this->db->tableName( 'searchindex' );
273 return "SELECT $searchindex.rowid, page_namespace, page_title " .
274 "FROM $page,$searchindex " .
275 "WHERE page_id=$searchindex.rowid AND $match";
276 }
277
278 function getCountQuery( $filteredTerm, $fulltext ) {
279 $match = $this->parseQuery( $filteredTerm, $fulltext );
280 $page = $this->db->tableName( 'page' );
281 $searchindex = $this->db->tableName( 'searchindex' );
282 return "SELECT COUNT(*) AS c " .
283 "FROM $page,$searchindex " .
284 "WHERE page_id=$searchindex.rowid AND $match" .
285 $this->queryRedirect() . ' ' .
286 $this->queryNamespaces();
287 }
288
289 /**
290 * Create or update the search index record for the given page.
291 * Title and text should be pre-processed.
292 *
293 * @param $id Integer
294 * @param $title String
295 * @param $text String
296 */
297 function update( $id, $title, $text ) {
298 if ( !$this->fulltextSearchSupported() ) {
299 return;
300 }
301 // @todo find a method to do it in a single request,
302 // couldn't do it so far due to typelessness of FTS3 tables.
303 $dbw = wfGetDB( DB_MASTER );
304
305 $dbw->delete( 'searchindex', array( 'rowid' => $id ), __METHOD__ );
306
307 $dbw->insert( 'searchindex',
308 array(
309 'rowid' => $id,
310 'si_title' => $title,
311 'si_text' => $text
312 ), __METHOD__ );
313 }
314
315 /**
316 * Update a search index record's title only.
317 * Title should be pre-processed.
318 *
319 * @param $id Integer
320 * @param $title String
321 */
322 function updateTitle( $id, $title ) {
323 if ( !$this->fulltextSearchSupported() ) {
324 return;
325 }
326 $dbw = wfGetDB( DB_MASTER );
327
328 $dbw->update( 'searchindex',
329 array( 'si_title' => $title ),
330 array( 'rowid' => $id ),
331 __METHOD__ );
332 }
333 }
334
335 /**
336 * @ingroup Search
337 */
338 class SqliteSearchResultSet extends SqlSearchResultSet {
339 function __construct( $resultSet, $terms, $totalHits = null ) {
340 parent::__construct( $resultSet, $terms );
341 $this->mTotalHits = $totalHits;
342 }
343
344 function getTotalHits() {
345 return $this->mTotalHits;
346 }
347 }