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