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