Merge "Allow wildcard searching in wiki IDs for interwiki user rights logs"
[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 bool
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 = $this->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 wfSuppressWarnings();
54 list( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
55 wfRestoreWarnings();
56
57 if ( $nonQuoted != '' ) {
58 $term = $nonQuoted;
59 $quote = '';
60 } else {
61 $term = str_replace( '"', '', $term );
62 $quote = '"';
63 }
64
65 if ( $searchon !== '' ) {
66 $searchon .= ' ';
67 }
68
69 // Some languages such as Serbian store the input form in the search index,
70 // so we may need to search for matches in multiple writing system variants.
71 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
72 if ( is_array( $convertedVariants ) ) {
73 $variants = array_unique( array_values( $convertedVariants ) );
74 } else {
75 $variants = array( $term );
76 }
77
78 // The low-level search index does some processing on input to work
79 // around problems with minimum lengths and encoding in MySQL's
80 // fulltext engine.
81 // For Chinese this also inserts spaces between adjacent Han characters.
82 $strippedVariants = array_map(
83 array( $wgContLang, 'normalizeForSearch' ),
84 $variants );
85
86 // Some languages such as Chinese force all variants to a canonical
87 // form when stripping to the low-level search index, so to be sure
88 // let's check our variants list for unique items after stripping.
89 $strippedVariants = array_unique( $strippedVariants );
90
91 $searchon .= $modifier;
92 if ( count( $strippedVariants ) > 1 ) {
93 $searchon .= '(';
94 }
95 foreach ( $strippedVariants as $stripped ) {
96 if ( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
97 // Hack for Chinese: we need to toss in quotes for
98 // multiple-character phrases since normalizeForSearch()
99 // added spaces between them to make word breaks.
100 $stripped = '"' . trim( $stripped ) . '"';
101 }
102 $searchon .= "$quote$stripped$quote$wildcard ";
103 }
104 if ( count( $strippedVariants ) > 1 ) {
105 $searchon .= ')';
106 }
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->addQuotes( $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 string $term Raw search term
150 * @return SqlSearchResultSet
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 string $term Raw search term
160 * @return SqlSearchResultSet
161 */
162 function searchTitle( $term ) {
163 return $this->searchInternal( $term, false );
164 }
165
166 protected function searchInternal( $term, $fulltext ) {
167 global $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 $totalResult = $this->db->query( $this->getCountQuery( $filteredTerm, $fulltext ) );
178 $row = $totalResult->fetchObject();
179 if ( $row ) {
180 $total = intval( $row->c );
181 }
182 $totalResult->free();
183
184 return new SqlSearchResultSet( $resultSet, $this->searchTerms, $total );
185 }
186
187 /**
188 * Return a partial WHERE clause to limit the search to the given namespaces
189 * @return string
190 */
191 function queryNamespaces() {
192 if ( is_null( $this->namespaces ) ) {
193 return ''; # search all
194 }
195 if ( !count( $this->namespaces ) ) {
196 $namespaces = '0';
197 } else {
198 $namespaces = $this->db->makeList( $this->namespaces );
199 }
200 return 'AND page_namespace IN (' . $namespaces . ')';
201 }
202
203 /**
204 * Returns a query with limit for number of results set.
205 * @param string $sql
206 * @return string
207 */
208 function limitResult( $sql ) {
209 return $this->db->limitResult( $sql, $this->limit, $this->offset );
210 }
211
212 /**
213 * Construct the full SQL query to do the search.
214 * The guts shoulds be constructed in queryMain()
215 * @param string $filteredTerm
216 * @param bool $fulltext
217 * @return string
218 */
219 function getQuery( $filteredTerm, $fulltext ) {
220 return $this->limitResult(
221 $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
222 $this->queryNamespaces()
223 );
224 }
225
226 /**
227 * Picks which field to index on, depending on what type of query.
228 * @param bool $fulltext
229 * @return string
230 */
231 function getIndexField( $fulltext ) {
232 return $fulltext ? 'si_text' : 'si_title';
233 }
234
235 /**
236 * Get the base part of the search query.
237 *
238 * @param string $filteredTerm
239 * @param bool $fulltext
240 * @return string
241 */
242 function queryMain( $filteredTerm, $fulltext ) {
243 $match = $this->parseQuery( $filteredTerm, $fulltext );
244 $page = $this->db->tableName( 'page' );
245 $searchindex = $this->db->tableName( 'searchindex' );
246 return "SELECT $searchindex.rowid, page_namespace, page_title " .
247 "FROM $page,$searchindex " .
248 "WHERE page_id=$searchindex.rowid AND $match";
249 }
250
251 function getCountQuery( $filteredTerm, $fulltext ) {
252 $match = $this->parseQuery( $filteredTerm, $fulltext );
253 $page = $this->db->tableName( 'page' );
254 $searchindex = $this->db->tableName( 'searchindex' );
255 return "SELECT COUNT(*) AS c " .
256 "FROM $page,$searchindex " .
257 "WHERE page_id=$searchindex.rowid AND $match " .
258 $this->queryNamespaces();
259 }
260
261 /**
262 * Create or update the search index record for the given page.
263 * Title and text should be pre-processed.
264 *
265 * @param int $id
266 * @param string $title
267 * @param string $text
268 */
269 function update( $id, $title, $text ) {
270 if ( !$this->fulltextSearchSupported() ) {
271 return;
272 }
273 // @todo find a method to do it in a single request,
274 // couldn't do it so far due to typelessness of FTS3 tables.
275 $dbw = wfGetDB( DB_MASTER );
276
277 $dbw->delete( 'searchindex', array( 'rowid' => $id ), __METHOD__ );
278
279 $dbw->insert( 'searchindex',
280 array(
281 'rowid' => $id,
282 'si_title' => $title,
283 'si_text' => $text
284 ), __METHOD__ );
285 }
286
287 /**
288 * Update a search index record's title only.
289 * Title should be pre-processed.
290 *
291 * @param int $id
292 * @param string $title
293 */
294 function updateTitle( $id, $title ) {
295 if ( !$this->fulltextSearchSupported() ) {
296 return;
297 }
298 $dbw = wfGetDB( DB_MASTER );
299
300 $dbw->update( 'searchindex',
301 array( 'si_title' => $title ),
302 array( 'rowid' => $id ),
303 __METHOD__ );
304 }
305 }