fix some spacing
[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 * Return a partial WHERE clause to exclude redirects, if so set
201 * @return String
202 */
203 function queryRedirect() {
204 if( $this->showRedirects ) {
205 return '';
206 } else {
207 return 'AND page_is_redirect=0';
208 }
209 }
210
211 /**
212 * Return a partial WHERE clause to limit the search to the given namespaces
213 * @return String
214 */
215 function queryNamespaces() {
216 if( is_null( $this->namespaces ) )
217 return ''; # search all
218 if ( !count( $this->namespaces ) ) {
219 $namespaces = '0';
220 } else {
221 $namespaces = $this->db->makeList( $this->namespaces );
222 }
223 return 'AND page_namespace IN (' . $namespaces . ')';
224 }
225
226 /**
227 * Returns a query with limit for number of results set.
228 * @param $sql String:
229 * @return String
230 */
231 function limitResult( $sql ) {
232 return $this->db->limitResult( $sql, $this->limit, $this->offset );
233 }
234
235 /**
236 * Construct the full SQL query to do the search.
237 * The guts shoulds be constructed in queryMain()
238 * @param $filteredTerm String
239 * @param $fulltext Boolean
240 * @return String
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( 'si_title' => $title ),
327 array( 'rowid' => $id ),
328 __METHOD__ );
329 }
330 }
331
332 /**
333 * @ingroup Search
334 */
335 class SqliteSearchResultSet extends SqlSearchResultSet {
336 function __construct( $resultSet, $terms, $totalHits=null ) {
337 parent::__construct( $resultSet, $terms );
338 $this->mTotalHits = $totalHits;
339 }
340
341 function getTotalHits() {
342 return $this->mTotalHits;
343 }
344 }