De-duplicate near match query terms when generating variants
[lhc/web/wiklou.git] / includes / search / SearchEngine.php
1 <?php
2 /**
3 * Basic search engine
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 * @defgroup Search Search
26 */
27
28 /**
29 * Contain a class for special pages
30 * @ingroup Search
31 */
32 class SearchEngine {
33 /** @var string */
34 public $prefix = '';
35
36 /** @var int[]|null */
37 public $namespaces = array( NS_MAIN );
38
39 /** @var int */
40 protected $limit = 10;
41
42 /** @var int */
43 protected $offset = 0;
44
45 /** @var array|string */
46 protected $searchTerms = array();
47
48 /** @var bool */
49 protected $showSuggestion = true;
50 private $sort = 'relevance';
51
52 /** @var array Feature values */
53 protected $features = array();
54
55 /**
56 * Perform a full text search query and return a result set.
57 * If title searches are not supported or disabled, return null.
58 * STUB
59 *
60 * @param string $term Raw search term
61 * @return SearchResultSet|Status|null
62 */
63 function searchText( $term ) {
64 return null;
65 }
66
67 /**
68 * Perform a title-only search query and return a result set.
69 * If title searches are not supported or disabled, return null.
70 * STUB
71 *
72 * @param string $term Raw search term
73 * @return SearchResultSet|null
74 */
75 function searchTitle( $term ) {
76 return null;
77 }
78
79 /**
80 * @since 1.18
81 * @param string $feature
82 * @return bool
83 */
84 public function supports( $feature ) {
85 switch ( $feature ) {
86 case 'search-update':
87 return true;
88 case 'title-suffix-filter':
89 default:
90 return false;
91 }
92 }
93
94 /**
95 * Way to pass custom data for engines
96 * @since 1.18
97 * @param string $feature
98 * @param mixed $data
99 * @return bool
100 */
101 public function setFeatureData( $feature, $data ) {
102 $this->features[$feature] = $data;
103 }
104
105 /**
106 * When overridden in derived class, performs database-specific conversions
107 * on text to be used for searching or updating search index.
108 * Default implementation does nothing (simply returns $string).
109 *
110 * @param string $string String to process
111 * @return string
112 */
113 public function normalizeText( $string ) {
114 global $wgContLang;
115
116 // Some languages such as Chinese require word segmentation
117 return $wgContLang->segmentByWord( $string );
118 }
119
120 /**
121 * Transform search term in cases when parts of the query came as different
122 * GET params (when supported), e.g. for prefix queries:
123 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
124 * @param string $term
125 * @return string
126 */
127 function transformSearchTerm( $term ) {
128 return $term;
129 }
130
131 /**
132 * If an exact title match can be found, or a very slightly close match,
133 * return the title. If no match, returns NULL.
134 *
135 * @param string $searchterm
136 * @return Title
137 */
138 public static function getNearMatch( $searchterm ) {
139 $title = self::getNearMatchInternal( $searchterm );
140
141 Hooks::run( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
142 return $title;
143 }
144
145 /**
146 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
147 * SearchResultSet.
148 *
149 * @param string $searchterm
150 * @return SearchResultSet
151 */
152 public static function getNearMatchResultSet( $searchterm ) {
153 return new SearchNearMatchResultSet( self::getNearMatch( $searchterm ) );
154 }
155
156 /**
157 * Really find the title match.
158 * @param string $searchterm
159 * @return null|Title
160 */
161 private static function getNearMatchInternal( $searchterm ) {
162 global $wgContLang, $wgEnableSearchContributorsByIP;
163
164 $allSearchTerms = array( $searchterm );
165
166 if ( $wgContLang->hasVariants() ) {
167 $allSearchTerms = array_unique( array_merge(
168 $allSearchTerms,
169 $wgContLang->autoConvertToAllVariants( $searchterm )
170 ) );
171 }
172
173 $titleResult = null;
174 if ( !Hooks::run( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
175 return $titleResult;
176 }
177
178 foreach ( $allSearchTerms as $term ) {
179
180 # Exact match? No need to look further.
181 $title = Title::newFromText( $term );
182 if ( is_null( $title ) ) {
183 return null;
184 }
185
186 # Try files if searching in the Media: namespace
187 if ( $title->getNamespace() == NS_MEDIA ) {
188 $title = Title::makeTitle( NS_FILE, $title->getText() );
189 }
190
191 if ( $title->isSpecialPage() || $title->isExternal() || $title->exists() ) {
192 return $title;
193 }
194
195 # See if it still otherwise has content is some sane sense
196 $page = WikiPage::factory( $title );
197 if ( $page->hasViewableContent() ) {
198 return $title;
199 }
200
201 if ( !Hooks::run( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
202 return $title;
203 }
204
205 # Now try all lower case (i.e. first letter capitalized)
206 $title = Title::newFromText( $wgContLang->lc( $term ) );
207 if ( $title && $title->exists() ) {
208 return $title;
209 }
210
211 # Now try capitalized string
212 $title = Title::newFromText( $wgContLang->ucwords( $term ) );
213 if ( $title && $title->exists() ) {
214 return $title;
215 }
216
217 # Now try all upper case
218 $title = Title::newFromText( $wgContLang->uc( $term ) );
219 if ( $title && $title->exists() ) {
220 return $title;
221 }
222
223 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
224 $title = Title::newFromText( $wgContLang->ucwordbreaks( $term ) );
225 if ( $title && $title->exists() ) {
226 return $title;
227 }
228
229 // Give hooks a chance at better match variants
230 $title = null;
231 if ( !Hooks::run( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
232 return $title;
233 }
234 }
235
236 $title = Title::newFromText( $searchterm );
237
238 # Entering an IP address goes to the contributions page
239 if ( $wgEnableSearchContributorsByIP ) {
240 if ( ( $title->getNamespace() == NS_USER && User::isIP( $title->getText() ) )
241 || User::isIP( trim( $searchterm ) ) ) {
242 return SpecialPage::getTitleFor( 'Contributions', $title->getDBkey() );
243 }
244 }
245
246 # Entering a user goes to the user page whether it's there or not
247 if ( $title->getNamespace() == NS_USER ) {
248 return $title;
249 }
250
251 # Go to images that exist even if there's no local page.
252 # There may have been a funny upload, or it may be on a shared
253 # file repository such as Wikimedia Commons.
254 if ( $title->getNamespace() == NS_FILE ) {
255 $image = wfFindFile( $title );
256 if ( $image ) {
257 return $title;
258 }
259 }
260
261 # MediaWiki namespace? Page may be "implied" if not customized.
262 # Just return it, with caps forced as the message system likes it.
263 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
264 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( $title->getText() ) );
265 }
266
267 # Quoted term? Try without the quotes...
268 $matches = array();
269 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
270 return SearchEngine::getNearMatch( $matches[1] );
271 }
272
273 return null;
274 }
275
276 public static function legalSearchChars() {
277 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
278 }
279
280 /**
281 * Set the maximum number of results to return
282 * and how many to skip before returning the first.
283 *
284 * @param int $limit
285 * @param int $offset
286 */
287 function setLimitOffset( $limit, $offset = 0 ) {
288 $this->limit = intval( $limit );
289 $this->offset = intval( $offset );
290 }
291
292 /**
293 * Set which namespaces the search should include.
294 * Give an array of namespace index numbers.
295 *
296 * @param int[]|null $namespaces
297 */
298 function setNamespaces( $namespaces ) {
299 $this->namespaces = $namespaces;
300 }
301
302 /**
303 * Set whether the searcher should try to build a suggestion. Note: some searchers
304 * don't support building a suggestion in the first place and others don't respect
305 * this flag.
306 *
307 * @param bool $showSuggestion Should the searcher try to build suggestions
308 */
309 function setShowSuggestion( $showSuggestion ) {
310 $this->showSuggestion = $showSuggestion;
311 }
312
313 /**
314 * Get the valid sort directions. All search engines support 'relevance' but others
315 * might support more. The default in all implementations should be 'relevance.'
316 *
317 * @since 1.25
318 * @return array(string) the valid sort directions for setSort
319 */
320 public function getValidSorts() {
321 return array( 'relevance' );
322 }
323
324 /**
325 * Set the sort direction of the search results. Must be one returned by
326 * SearchEngine::getValidSorts()
327 *
328 * @since 1.25
329 * @throws InvalidArgumentException
330 * @param string $sort sort direction for query result
331 */
332 public function setSort( $sort ) {
333 if ( !in_array( $sort, $this->getValidSorts() ) ) {
334 throw new InvalidArgumentException( "Invalid sort: $sort. " .
335 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
336 }
337 $this->sort = $sort;
338 }
339
340 /**
341 * Get the sort direction of the search results
342 *
343 * @since 1.25
344 * @return string
345 */
346 public function getSort() {
347 return $this->sort;
348 }
349
350 /**
351 * Parse some common prefixes: all (search everything)
352 * or namespace names
353 *
354 * @param string $query
355 * @return string
356 */
357 function replacePrefixes( $query ) {
358 global $wgContLang;
359
360 $parsed = $query;
361 if ( strpos( $query, ':' ) === false ) { // nothing to do
362 return $parsed;
363 }
364
365 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
366 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
367 $this->namespaces = null;
368 $parsed = substr( $query, strlen( $allkeyword ) );
369 } elseif ( strpos( $query, ':' ) !== false ) {
370 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
371 $index = $wgContLang->getNsIndex( $prefix );
372 if ( $index !== false ) {
373 $this->namespaces = array( $index );
374 $parsed = substr( $query, strlen( $prefix ) + 1 );
375 }
376 }
377 if ( trim( $parsed ) == '' ) {
378 $parsed = $query; // prefix was the whole query
379 }
380
381 return $parsed;
382 }
383
384 /**
385 * Make a list of searchable namespaces and their canonical names.
386 * @return array
387 */
388 public static function searchableNamespaces() {
389 global $wgContLang;
390 $arr = array();
391 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
392 if ( $ns >= NS_MAIN ) {
393 $arr[$ns] = $name;
394 }
395 }
396
397 Hooks::run( 'SearchableNamespaces', array( &$arr ) );
398 return $arr;
399 }
400
401 /**
402 * Extract default namespaces to search from the given user's
403 * settings, returning a list of index numbers.
404 *
405 * @param user $user
406 * @return array
407 */
408 public static function userNamespaces( $user ) {
409 $arr = array();
410 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
411 if ( $user->getOption( 'searchNs' . $ns ) ) {
412 $arr[] = $ns;
413 }
414 }
415
416 return $arr;
417 }
418
419 /**
420 * Find snippet highlight settings for all users
421 *
422 * @return array Contextlines, contextchars
423 */
424 public static function userHighlightPrefs() {
425 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
426 $contextchars = 75; // same as above.... :P
427 return array( $contextlines, $contextchars );
428 }
429
430 /**
431 * An array of namespaces indexes to be searched by default
432 *
433 * @return array
434 */
435 public static function defaultNamespaces() {
436 global $wgNamespacesToBeSearchedDefault;
437
438 return array_keys( $wgNamespacesToBeSearchedDefault, true );
439 }
440
441 /**
442 * Get a list of namespace names useful for showing in tooltips
443 * and preferences
444 *
445 * @param array $namespaces
446 * @return array
447 */
448 public static function namespacesAsText( $namespaces ) {
449 global $wgContLang;
450
451 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
452 foreach ( $formatted as $key => $ns ) {
453 if ( empty( $ns ) ) {
454 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
455 }
456 }
457 return $formatted;
458 }
459
460 /**
461 * Load up the appropriate search engine class for the currently
462 * active database backend, and return a configured instance.
463 *
464 * @param string $type Type of search backend, if not the default
465 * @return SearchEngine
466 */
467 public static function create( $type = null ) {
468 global $wgSearchType;
469 $dbr = null;
470
471 $alternatives = self::getSearchTypes();
472
473 if ( $type && in_array( $type, $alternatives ) ) {
474 $class = $type;
475 } elseif ( $wgSearchType !== null ) {
476 $class = $wgSearchType;
477 } else {
478 $dbr = wfGetDB( DB_SLAVE );
479 $class = $dbr->getSearchEngine();
480 }
481
482 $search = new $class( $dbr );
483 return $search;
484 }
485
486 /**
487 * Return the search engines we support. If only $wgSearchType
488 * is set, it'll be an array of just that one item.
489 *
490 * @return array
491 */
492 public static function getSearchTypes() {
493 global $wgSearchType, $wgSearchTypeAlternatives;
494
495 $alternatives = $wgSearchTypeAlternatives ?: array();
496 array_unshift( $alternatives, $wgSearchType );
497
498 return $alternatives;
499 }
500
501 /**
502 * Create or update the search index record for the given page.
503 * Title and text should be pre-processed.
504 * STUB
505 *
506 * @param int $id
507 * @param string $title
508 * @param string $text
509 */
510 function update( $id, $title, $text ) {
511 // no-op
512 }
513
514 /**
515 * Update a search index record's title only.
516 * Title should be pre-processed.
517 * STUB
518 *
519 * @param int $id
520 * @param string $title
521 */
522 function updateTitle( $id, $title ) {
523 // no-op
524 }
525
526 /**
527 * Delete an indexed page
528 * Title should be pre-processed.
529 * STUB
530 *
531 * @param int $id Page id that was deleted
532 * @param string $title Title of page that was deleted
533 */
534 function delete( $id, $title ) {
535 // no-op
536 }
537
538 /**
539 * Get OpenSearch suggestion template
540 *
541 * @deprecated since 1.25
542 * @return string
543 */
544 public static function getOpenSearchTemplate() {
545 wfDeprecated( __METHOD__, '1.25' );
546 return ApiOpenSearch::getOpenSearchTemplate( 'application/x-suggestions+json' );
547 }
548
549 /**
550 * Get the raw text for updating the index from a content object
551 * Nicer search backends could possibly do something cooler than
552 * just returning raw text
553 *
554 * @todo This isn't ideal, we'd really like to have content-specific handling here
555 * @param Title $t Title we're indexing
556 * @param Content $c Content of the page to index
557 * @return string
558 */
559 public function getTextFromContent( Title $t, Content $c = null ) {
560 return $c ? $c->getTextForSearchIndex() : '';
561 }
562
563 /**
564 * If an implementation of SearchEngine handles all of its own text processing
565 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
566 * rather silly handling, it should return true here instead.
567 *
568 * @return bool
569 */
570 public function textAlreadyUpdatedForIndex() {
571 return false;
572 }
573 }
574
575 /**
576 * Dummy class to be used when non-supported Database engine is present.
577 * @todo FIXME: Dummy class should probably try something at least mildly useful,
578 * such as a LIKE search through titles.
579 * @ingroup Search
580 */
581 class SearchEngineDummy extends SearchEngine {
582 // no-op
583 }