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