Merge "Adding Wikivoyage to the default interwiki map"
[mediawiki.git] / includes / search / SearchSqlite.php
blobebff68ef1fb43c038b2e1d5bacd17d273f8d7afa
1 <?php
2 /**
3 * SQLite search backend, based upon SearchMysql
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.
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.
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
20 * @file
21 * @ingroup Search
24 /**
25 * Search engine hook for SQLite
26 * @ingroup Search
28 class SearchSqlite extends SearchDatabase {
29 /**
30 * Whether fulltext search is supported by current schema
31 * @return Boolean
33 function fulltextSearchSupported() {
34 return $this->db->checkForEnabledSearch();
37 /**
38 * Parse the user's query and transform it into an SQL fragment which will
39 * become part of a WHERE clause
41 * @return string
43 function parseQuery( $filteredText, $fulltext ) {
44 global $wgContLang;
45 $lc = SearchEngine::legalSearchChars(); // Minus format chars
46 $searchon = '';
47 $this->searchTerms = array();
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;
55 if ( $nonQuoted != '' ) {
56 $term = $nonQuoted;
57 $quote = '';
58 } else {
59 $term = str_replace( '"', '', $term );
60 $quote = '"';
63 if ( $searchon !== '' ) {
64 $searchon .= ' ';
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 );
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 );
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 );
89 $searchon .= $modifier;
90 if ( count( $strippedVariants ) > 1 ) {
91 $searchon .= '(';
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 ) . '"';
100 $searchon .= "$quote$stripped$quote$wildcard ";
102 if ( count( $strippedVariants ) > 1 ) {
103 $searchon .= ')';
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;
112 } else {
113 wfDebug( __METHOD__ . ": Can't understand search query '{$filteredText}'\n" );
116 $searchon = $this->db->strencode( $searchon );
117 $field = $this->getIndexField( $fulltext );
118 return " $field MATCH '$searchon' ";
121 function regexTerm( $string, $wildcard ) {
122 global $wgContLang;
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";
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.
137 return $regex;
140 public static function legalSearchChars() {
141 return "\"*" . parent::legalSearchChars();
145 * Perform a full text search query and return a result set.
147 * @param string $term raw search term
148 * @return SqliteSearchResultSet
150 function searchText( $term ) {
151 return $this->searchInternal( $term, true );
155 * Perform a title-only search query and return a result set.
157 * @param string $term raw search term
158 * @return SqliteSearchResultSet
160 function searchTitle( $term ) {
161 return $this->searchInternal( $term, false );
164 protected function searchInternal( $term, $fulltext ) {
165 global $wgCountTotalSearchHits, $wgContLang;
167 if ( !$this->fulltextSearchSupported() ) {
168 return null;
171 $filteredTerm = $this->filter( $wgContLang->lc( $term ) );
172 $resultSet = $this->db->query( $this->getQuery( $filteredTerm, $fulltext ) );
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 );
181 $totalResult->free();
184 return new SqliteSearchResultSet( $resultSet, $this->searchTerms, $total );
188 * Return a partial WHERE clause to exclude redirects, if so set
189 * @return String
191 function queryRedirect() {
192 if ( $this->showRedirects ) {
193 return '';
194 } else {
195 return 'AND page_is_redirect=0';
200 * Return a partial WHERE clause to limit the search to the given namespaces
201 * @return String
203 function queryNamespaces() {
204 if ( is_null( $this->namespaces ) ) {
205 return ''; # search all
207 if ( !count( $this->namespaces ) ) {
208 $namespaces = '0';
209 } else {
210 $namespaces = $this->db->makeList( $this->namespaces );
212 return 'AND page_namespace IN (' . $namespaces . ')';
216 * Returns a query with limit for number of results set.
217 * @param $sql String:
218 * @return String
220 function limitResult( $sql ) {
221 return $this->db->limitResult( $sql, $this->limit, $this->offset );
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
231 function getQuery( $filteredTerm, $fulltext ) {
232 return $this->limitResult(
233 $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
234 $this->queryRedirect() . ' ' .
235 $this->queryNamespaces()
240 * Picks which field to index on, depending on what type of query.
241 * @param $fulltext Boolean
242 * @return String
244 function getIndexField( $fulltext ) {
245 return $fulltext ? 'si_text' : 'si_title';
249 * Get the base part of the search query.
251 * @param $filteredTerm String
252 * @param $fulltext Boolean
253 * @return String
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";
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();
276 * Create or update the search index record for the given page.
277 * Title and text should be pre-processed.
279 * @param $id Integer
280 * @param $title String
281 * @param $text String
283 function update( $id, $title, $text ) {
284 if ( !$this->fulltextSearchSupported() ) {
285 return;
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 );
291 $dbw->delete( 'searchindex', array( 'rowid' => $id ), __METHOD__ );
293 $dbw->insert( 'searchindex',
294 array(
295 'rowid' => $id,
296 'si_title' => $title,
297 'si_text' => $text
298 ), __METHOD__ );
302 * Update a search index record's title only.
303 * Title should be pre-processed.
305 * @param $id Integer
306 * @param $title String
308 function updateTitle( $id, $title ) {
309 if ( !$this->fulltextSearchSupported() ) {
310 return;
312 $dbw = wfGetDB( DB_MASTER );
314 $dbw->update( 'searchindex',
315 array( 'si_title' => $title ),
316 array( 'rowid' => $id ),
317 __METHOD__ );
322 * @ingroup Search
324 class SqliteSearchResultSet extends SqlSearchResultSet {
325 function __construct( $resultSet, $terms, $totalHits = null ) {
326 parent::__construct( $resultSet, $terms );
327 $this->mTotalHits = $totalHits;
330 function getTotalHits() {
331 return $this->mTotalHits;