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