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