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