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