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