Merge "Create ChangesListSpecialPage as a base class for Watchlist and RC"
[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 * If this search backend can list/unlist redirects
70 * @deprecated since 1.18 Call supports( 'list-redirects' );
71 * @return bool
72 */
73 function acceptListRedirects() {
74 wfDeprecated( __METHOD__, '1.18' );
75 return $this->supports( 'list-redirects' );
76 }
77
78 /**
79 * @since 1.18
80 * @param $feature String
81 * @return Boolean
82 */
83 public function supports( $feature ) {
84 switch ( $feature ) {
85 case 'list-redirects':
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 $feature String
98 * @param $data Mixed
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 GET params (when supported)
122 * e.g. for prefix queries: 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 $searchterm String
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 $searchterm string
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( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
164 }
165
166 $titleResult = null;
167 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
168 return $titleResult;
169 }
170
171 foreach ( $allSearchTerms as $term ) {
172
173 # Exact match? No need to look further.
174 $title = Title::newFromText( $term );
175 if ( is_null( $title ) ) {
176 return null;
177 }
178
179 # Try files if searching in the Media: namespace
180 if ( $title->getNamespace() == NS_MEDIA ) {
181 $title = Title::makeTitle( NS_FILE, $title->getText() );
182 }
183
184 if ( $title->isSpecialPage() || $title->isExternal() || $title->exists() ) {
185 return $title;
186 }
187
188 # See if it still otherwise has content is some sane sense
189 $page = WikiPage::factory( $title );
190 if ( $page->hasViewableContent() ) {
191 return $title;
192 }
193
194 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
195 return $title;
196 }
197
198 # Now try all lower case (i.e. first letter capitalized)
199 $title = Title::newFromText( $wgContLang->lc( $term ) );
200 if ( $title && $title->exists() ) {
201 return $title;
202 }
203
204 # Now try capitalized string
205 $title = Title::newFromText( $wgContLang->ucwords( $term ) );
206 if ( $title && $title->exists() ) {
207 return $title;
208 }
209
210 # Now try all upper case
211 $title = Title::newFromText( $wgContLang->uc( $term ) );
212 if ( $title && $title->exists() ) {
213 return $title;
214 }
215
216 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
217 $title = Title::newFromText( $wgContLang->ucwordbreaks( $term ) );
218 if ( $title && $title->exists() ) {
219 return $title;
220 }
221
222 // Give hooks a chance at better match variants
223 $title = null;
224 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
225 return $title;
226 }
227 }
228
229 $title = Title::newFromText( $searchterm );
230
231 # Entering an IP address goes to the contributions page
232 if ( $wgEnableSearchContributorsByIP ) {
233 if ( ( $title->getNamespace() == NS_USER && User::isIP( $title->getText() ) )
234 || User::isIP( trim( $searchterm ) ) ) {
235 return SpecialPage::getTitleFor( 'Contributions', $title->getDBkey() );
236 }
237 }
238
239 # Entering a user goes to the user page whether it's there or not
240 if ( $title->getNamespace() == NS_USER ) {
241 return $title;
242 }
243
244 # Go to images that exist even if there's no local page.
245 # There may have been a funny upload, or it may be on a shared
246 # file repository such as Wikimedia Commons.
247 if ( $title->getNamespace() == NS_FILE ) {
248 $image = wfFindFile( $title );
249 if ( $image ) {
250 return $title;
251 }
252 }
253
254 # MediaWiki namespace? Page may be "implied" if not customized.
255 # Just return it, with caps forced as the message system likes it.
256 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
257 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( $title->getText() ) );
258 }
259
260 # Quoted term? Try without the quotes...
261 $matches = array();
262 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
263 return SearchEngine::getNearMatch( $matches[1] );
264 }
265
266 return null;
267 }
268
269 public static function legalSearchChars() {
270 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
271 }
272
273 /**
274 * Set the maximum number of results to return
275 * and how many to skip before returning the first.
276 *
277 * @param $limit Integer
278 * @param $offset Integer
279 */
280 function setLimitOffset( $limit, $offset = 0 ) {
281 $this->limit = intval( $limit );
282 $this->offset = intval( $offset );
283 }
284
285 /**
286 * Set which namespaces the search should include.
287 * Give an array of namespace index numbers.
288 *
289 * @param $namespaces Array
290 */
291 function setNamespaces( $namespaces ) {
292 $this->namespaces = $namespaces;
293 }
294
295 /**
296 * Set whether the searcher should try to build a suggestion. Note: some searchers
297 * don't support building a suggestion in the first place and others don't respect
298 * this flag.
299 *
300 * @param boolean $showSuggestion should the searcher try to build suggestions
301 */
302 function setShowSuggestion( $showSuggestion ) {
303 $this->showSuggestion = $showSuggestion;
304 }
305
306 /**
307 * Parse some common prefixes: all (search everything)
308 * or namespace names
309 *
310 * @param $query String
311 * @return string
312 */
313 function replacePrefixes( $query ) {
314 global $wgContLang;
315
316 $parsed = $query;
317 if ( strpos( $query, ':' ) === false ) { // nothing to do
318 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
319 return $parsed;
320 }
321
322 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
323 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
324 $this->namespaces = null;
325 $parsed = substr( $query, strlen( $allkeyword ) );
326 } elseif ( strpos( $query, ':' ) !== false ) {
327 $prefix = substr( $query, 0, strpos( $query, ':' ) );
328 $index = $wgContLang->getNsIndex( $prefix );
329 if ( $index !== false ) {
330 $this->namespaces = array( $index );
331 $parsed = substr( $query, strlen( $prefix ) + 1 );
332 }
333 }
334 if ( trim( $parsed ) == '' ) {
335 $parsed = $query; // prefix was the whole query
336 }
337
338 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
339
340 return $parsed;
341 }
342
343 /**
344 * Make a list of searchable namespaces and their canonical names.
345 * @return Array
346 */
347 public static function searchableNamespaces() {
348 global $wgContLang;
349 $arr = array();
350 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
351 if ( $ns >= NS_MAIN ) {
352 $arr[$ns] = $name;
353 }
354 }
355
356 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
357 return $arr;
358 }
359
360 /**
361 * Extract default namespaces to search from the given user's
362 * settings, returning a list of index numbers.
363 *
364 * @param $user User
365 * @return Array
366 */
367 public static function userNamespaces( $user ) {
368 global $wgSearchEverythingOnlyLoggedIn;
369
370 $searchableNamespaces = SearchEngine::searchableNamespaces();
371
372 // get search everything preference, that can be set to be read for logged-in users
373 // it overrides other options
374 if ( !$wgSearchEverythingOnlyLoggedIn || $user->isLoggedIn() ) {
375 if ( $user->getOption( 'searcheverything' ) ) {
376 return array_keys( $searchableNamespaces );
377 }
378 }
379
380 $arr = array();
381 foreach ( $searchableNamespaces as $ns => $name ) {
382 if ( $user->getOption( 'searchNs' . $ns ) ) {
383 $arr[] = $ns;
384 }
385 }
386
387 return $arr;
388 }
389
390 /**
391 * Find snippet highlight settings for all users
392 *
393 * @return Array contextlines, contextchars
394 */
395 public static function userHighlightPrefs() {
396 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
397 $contextchars = 75; // same as above.... :P
398 return array( $contextlines, $contextchars );
399 }
400
401 /**
402 * An array of namespaces indexes to be searched by default
403 *
404 * @return Array
405 */
406 public static function defaultNamespaces() {
407 global $wgNamespacesToBeSearchedDefault;
408
409 return array_keys( $wgNamespacesToBeSearchedDefault, true );
410 }
411
412 /**
413 * Get a list of namespace names useful for showing in tooltips
414 * and preferences
415 *
416 * @param $namespaces Array
417 * @return array
418 */
419 public static function namespacesAsText( $namespaces ) {
420 global $wgContLang;
421
422 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
423 foreach ( $formatted as $key => $ns ) {
424 if ( empty( $ns ) ) {
425 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
426 }
427 }
428 return $formatted;
429 }
430
431 /**
432 * Return the help namespaces to be shown on Special:Search
433 *
434 * @return Array
435 */
436 public static function helpNamespaces() {
437 global $wgNamespacesToBeSearchedHelp;
438
439 return array_keys( $wgNamespacesToBeSearchedHelp, true );
440 }
441
442 /**
443 * Return a 'cleaned up' search string
444 *
445 * @param $text String
446 * @return String
447 */
448 function filter( $text ) {
449 $lc = $this->legalSearchChars();
450 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
451 }
452 /**
453 * Load up the appropriate search engine class for the currently
454 * active database backend, and return a configured instance.
455 *
456 * @param String $type Type of search backend, if not the default
457 * @return SearchEngine
458 */
459 public static function create( $type = null ) {
460 global $wgSearchType;
461 $dbr = null;
462
463 $alternatives = self::getSearchTypes();
464
465 if ( $type && in_array( $type, $alternatives ) ) {
466 $class = $type;
467 } elseif ( $wgSearchType !== null ) {
468 $class = $wgSearchType;
469 } else {
470 $dbr = wfGetDB( DB_SLAVE );
471 $class = $dbr->getSearchEngine();
472 }
473
474 $search = new $class( $dbr );
475 $search->setLimitOffset( 0, 0 );
476 return $search;
477 }
478
479 /**
480 * Return the search engines we support. If only $wgSearchType
481 * is set, it'll be an array of just that one item.
482 *
483 * @return array
484 */
485 public static function getSearchTypes() {
486 global $wgSearchType, $wgSearchTypeAlternatives;
487
488 $alternatives = $wgSearchTypeAlternatives ?: array();
489 array_unshift( $alternatives, $wgSearchType );
490
491 return $alternatives;
492 }
493
494 /**
495 * Create or update the search index record for the given page.
496 * Title and text should be pre-processed.
497 * STUB
498 *
499 * @param $id Integer
500 * @param $title String
501 * @param $text String
502 */
503 function update( $id, $title, $text ) {
504 // no-op
505 }
506
507 /**
508 * Update a search index record's title only.
509 * Title should be pre-processed.
510 * STUB
511 *
512 * @param $id Integer
513 * @param $title String
514 */
515 function updateTitle( $id, $title ) {
516 // no-op
517 }
518
519 /**
520 * Delete an indexed page
521 * Title should be pre-processed.
522 * STUB
523 *
524 * @param Integer $id Page id that was deleted
525 * @param String $title Title of page that was deleted
526 */
527 function delete( $id, $title ) {
528 // no-op
529 }
530
531 /**
532 * Get OpenSearch suggestion template
533 *
534 * @return String
535 */
536 public static function getOpenSearchTemplate() {
537 global $wgOpenSearchTemplate, $wgCanonicalServer;
538 if ( $wgOpenSearchTemplate ) {
539 return $wgOpenSearchTemplate;
540 } else {
541 $ns = implode( '|', SearchEngine::defaultNamespaces() );
542 if ( !$ns ) {
543 $ns = "0";
544 }
545 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
546 }
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 * @ingroup Search
577 */
578 class SearchResultSet {
579 /**
580 * Fetch an array of regular expression fragments for matching
581 * the search terms as parsed by this engine in a text extract.
582 * STUB
583 *
584 * @return Array
585 */
586 function termMatches() {
587 return array();
588 }
589
590 function numRows() {
591 return 0;
592 }
593
594 /**
595 * Return true if results are included in this result set.
596 * STUB
597 *
598 * @return Boolean
599 */
600 function hasResults() {
601 return false;
602 }
603
604 /**
605 * Some search modes return a total hit count for the query
606 * in the entire article database. This may include pages
607 * in namespaces that would not be matched on the given
608 * settings.
609 *
610 * Return null if no total hits number is supported.
611 *
612 * @return Integer
613 */
614 function getTotalHits() {
615 return null;
616 }
617
618 /**
619 * Some search modes return a suggested alternate term if there are
620 * no exact hits. Returns true if there is one on this set.
621 *
622 * @return Boolean
623 */
624 function hasSuggestion() {
625 return false;
626 }
627
628 /**
629 * @return String: suggested query, null if none
630 */
631 function getSuggestionQuery() {
632 return null;
633 }
634
635 /**
636 * @return String: HTML highlighted suggested query, '' if none
637 */
638 function getSuggestionSnippet() {
639 return '';
640 }
641
642 /**
643 * Return information about how and from where the results were fetched,
644 * should be useful for diagnostics and debugging
645 *
646 * @return String
647 */
648 function getInfo() {
649 return null;
650 }
651
652 /**
653 * Return a result set of hits on other (multiple) wikis associated with this one
654 *
655 * @return SearchResultSet
656 */
657 function getInterwikiResults() {
658 return null;
659 }
660
661 /**
662 * Check if there are results on other wikis
663 *
664 * @return Boolean
665 */
666 function hasInterwikiResults() {
667 return $this->getInterwikiResults() != null;
668 }
669
670 /**
671 * Fetches next search result, or false.
672 * STUB
673 *
674 * @return SearchResult
675 */
676 function next() {
677 return false;
678 }
679
680 /**
681 * Frees the result set, if applicable.
682 */
683 function free() {
684 // ...
685 }
686 }
687
688 /**
689 * This class is used for different SQL-based search engines shipped with MediaWiki
690 */
691 class SqlSearchResultSet extends SearchResultSet {
692
693 protected $mResultSet;
694
695 function __construct( $resultSet, $terms ) {
696 $this->mResultSet = $resultSet;
697 $this->mTerms = $terms;
698 }
699
700 function termMatches() {
701 return $this->mTerms;
702 }
703
704 function numRows() {
705 if ( $this->mResultSet === false ) {
706 return false;
707 }
708
709 return $this->mResultSet->numRows();
710 }
711
712 function next() {
713 if ( $this->mResultSet === false ) {
714 return false;
715 }
716
717 $row = $this->mResultSet->fetchObject();
718 if ( $row === false ) {
719 return false;
720 }
721
722 return SearchResult::newFromRow( $row );
723 }
724
725 function free() {
726 if ( $this->mResultSet === false ) {
727 return false;
728 }
729
730 $this->mResultSet->free();
731 }
732 }
733
734 /**
735 * @ingroup Search
736 */
737 class SearchResultTooMany {
738 # # Some search engines may bail out if too many matches are found
739 }
740
741 /**
742 * @todo FIXME: This class is horribly factored. It would probably be better to
743 * have a useful base class to which you pass some standard information, then
744 * let the fancy self-highlighters extend that.
745 * @ingroup Search
746 */
747 class SearchResult {
748
749 /**
750 * @var Revision
751 */
752 protected $mRevision = null;
753
754 /**
755 * @var File
756 */
757 protected $mImage = null;
758
759 /**
760 * @var Title
761 */
762 protected $mTitle;
763
764 /**
765 * @var String
766 */
767 protected $mText;
768
769 /**
770 * Return a new SearchResult and initializes it with a title.
771 *
772 * @param $title Title
773 * @return SearchResult
774 */
775 public static function newFromTitle( $title ) {
776 $result = new self();
777 $result->initFromTitle( $title );
778 return $result;
779 }
780 /**
781 * Return a new SearchResult and initializes it with a row.
782 *
783 * @param $row object
784 * @return SearchResult
785 */
786 public static function newFromRow( $row ) {
787 $result = new self();
788 $result->initFromRow( $row );
789 return $result;
790 }
791
792 public function __construct( $row = null ) {
793 if ( !is_null( $row ) ) {
794 // Backwards compatibility with pre-1.17 callers
795 $this->initFromRow( $row );
796 }
797 }
798
799 /**
800 * Initialize from a database row. Makes a Title and passes that to
801 * initFromTitle.
802 *
803 * @param $row object
804 */
805 protected function initFromRow( $row ) {
806 $this->initFromTitle( Title::makeTitle( $row->page_namespace, $row->page_title ) );
807 }
808
809 /**
810 * Initialize from a Title and if possible initializes a corresponding
811 * Revision and File.
812 *
813 * @param $title Title
814 */
815 protected function initFromTitle( $title ) {
816 $this->mTitle = $title;
817 if ( !is_null( $this->mTitle ) ) {
818 $id = false;
819 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
820 $this->mRevision = Revision::newFromTitle(
821 $this->mTitle, $id, Revision::READ_NORMAL );
822 if ( $this->mTitle->getNamespace() === NS_FILE ) {
823 $this->mImage = wfFindFile( $this->mTitle );
824 }
825 }
826 }
827
828 /**
829 * Check if this is result points to an invalid title
830 *
831 * @return Boolean
832 */
833 function isBrokenTitle() {
834 return is_null( $this->mTitle );
835 }
836
837 /**
838 * Check if target page is missing, happens when index is out of date
839 *
840 * @return Boolean
841 */
842 function isMissingRevision() {
843 return !$this->mRevision && !$this->mImage;
844 }
845
846 /**
847 * @return Title
848 */
849 function getTitle() {
850 return $this->mTitle;
851 }
852
853 /**
854 * Get the file for this page, if one exists
855 * @return File|null
856 */
857 function getFile() {
858 return $this->mImage;
859 }
860
861 /**
862 * @return float|null if not supported
863 */
864 function getScore() {
865 return null;
866 }
867
868 /**
869 * Lazy initialization of article text from DB
870 */
871 protected function initText() {
872 if ( !isset( $this->mText ) ) {
873 if ( $this->mRevision != null ) {
874 $this->mText = SearchEngine::create()
875 ->getTextFromContent( $this->mTitle, $this->mRevision->getContent() );
876 } else { // TODO: can we fetch raw wikitext for commons images?
877 $this->mText = '';
878 }
879 }
880 }
881
882 /**
883 * @param array $terms terms to highlight
884 * @return String: highlighted text snippet, null (and not '') if not supported
885 */
886 function getTextSnippet( $terms ) {
887 global $wgAdvancedSearchHighlighting;
888 $this->initText();
889
890 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
891 list( $contextlines, $contextchars ) = SearchEngine::userHighlightPrefs();
892 $h = new SearchHighlighter();
893 if ( $wgAdvancedSearchHighlighting ) {
894 return $h->highlightText( $this->mText, $terms, $contextlines, $contextchars );
895 } else {
896 return $h->highlightSimple( $this->mText, $terms, $contextlines, $contextchars );
897 }
898 }
899
900 /**
901 * @param array $terms terms to highlight
902 * @return String: highlighted title, '' if not supported
903 */
904 function getTitleSnippet( $terms ) {
905 return '';
906 }
907
908 /**
909 * @param array $terms terms to highlight
910 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
911 */
912 function getRedirectSnippet( $terms ) {
913 return '';
914 }
915
916 /**
917 * @return Title object for the redirect to this page, null if none or not supported
918 */
919 function getRedirectTitle() {
920 return null;
921 }
922
923 /**
924 * @return string highlighted relevant section name, null if none or not supported
925 */
926 function getSectionSnippet() {
927 return '';
928 }
929
930 /**
931 * @return Title object (pagename+fragment) for the section, null if none or not supported
932 */
933 function getSectionTitle() {
934 return null;
935 }
936
937 /**
938 * @return String: timestamp
939 */
940 function getTimestamp() {
941 if ( $this->mRevision ) {
942 return $this->mRevision->getTimestamp();
943 } elseif ( $this->mImage ) {
944 return $this->mImage->getTimestamp();
945 }
946 return '';
947 }
948
949 /**
950 * @return Integer: number of words
951 */
952 function getWordCount() {
953 $this->initText();
954 return str_word_count( $this->mText );
955 }
956
957 /**
958 * @return Integer: size in bytes
959 */
960 function getByteSize() {
961 $this->initText();
962 return strlen( $this->mText );
963 }
964
965 /**
966 * @return Boolean if hit has related articles
967 */
968 function hasRelated() {
969 return false;
970 }
971
972 /**
973 * @return String: interwiki prefix of the title (return iw even if title is broken)
974 */
975 function getInterwikiPrefix() {
976 return '';
977 }
978
979 /**
980 * Did this match file contents (eg: PDF/DJVU)?
981 */
982 function isFileMatch() {
983 return false;
984 }
985 }
986 /**
987 * A SearchResultSet wrapper for SearchEngine::getNearMatch
988 */
989 class SearchNearMatchResultSet extends SearchResultSet {
990 private $fetched = false;
991 /**
992 * @param $match mixed Title if matched, else null
993 */
994 public function __construct( $match ) {
995 $this->result = $match;
996 }
997 public function hasResult() {
998 return (bool)$this->result;
999 }
1000 public function numRows() {
1001 return $this->hasResults() ? 1 : 0;
1002 }
1003 public function next() {
1004 if ( $this->fetched || !$this->result ) {
1005 return false;
1006 }
1007 $this->fetched = true;
1008 return SearchResult::newFromTitle( $this->result );
1009 }
1010 }
1011
1012 /**
1013 * Highlight bits of wikitext
1014 *
1015 * @ingroup Search
1016 */
1017 class SearchHighlighter {
1018 var $mCleanWikitext = true;
1019
1020 function __construct( $cleanupWikitext = true ) {
1021 $this->mCleanWikitext = $cleanupWikitext;
1022 }
1023
1024 /**
1025 * Default implementation of wikitext highlighting
1026 *
1027 * @param $text String
1028 * @param array $terms terms to highlight (unescaped)
1029 * @param $contextlines Integer
1030 * @param $contextchars Integer
1031 * @return String
1032 */
1033 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
1034 global $wgContLang;
1035 global $wgSearchHighlightBoundaries;
1036 $fname = __METHOD__;
1037
1038 if ( $text == '' ) {
1039 return '';
1040 }
1041
1042 // spli text into text + templates/links/tables
1043 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
1044 // first capture group is for detecting nested templates/links/tables/references
1045 $endPatterns = array(
1046 1 => '/(\{\{)|(\}\})/', // template
1047 2 => '/(\[\[)|(\]\])/', // image
1048 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
1049
1050 // @todo FIXME: This should prolly be a hook or something
1051 if ( function_exists( 'wfCite' ) ) {
1052 $spat .= '|(<ref>)'; // references via cite extension
1053 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
1054 }
1055 $spat .= '/';
1056 $textExt = array(); // text extracts
1057 $otherExt = array(); // other extracts
1058 wfProfileIn( "$fname-split" );
1059 $start = 0;
1060 $textLen = strlen( $text );
1061 $count = 0; // sequence number to maintain ordering
1062 while ( $start < $textLen ) {
1063 // find start of template/image/table
1064 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE, $start ) ) {
1065 $epat = '';
1066 foreach ( $matches as $key => $val ) {
1067 if ( $key > 0 && $val[1] != - 1 ) {
1068 if ( $key == 2 ) {
1069 // see if this is an image link
1070 $ns = substr( $val[0], 2, - 1 );
1071 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE ) {
1072 break;
1073 }
1074
1075 }
1076 $epat = $endPatterns[$key];
1077 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1078 $start = $val[1];
1079 break;
1080 }
1081 }
1082 if ( $epat ) {
1083 // find end (and detect any nested elements)
1084 $level = 0;
1085 $offset = $start + 1;
1086 $found = false;
1087 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE, $offset ) ) {
1088 if ( array_key_exists( 2, $endMatches ) ) {
1089 // found end
1090 if ( $level == 0 ) {
1091 $len = strlen( $endMatches[2][0] );
1092 $off = $endMatches[2][1];
1093 $this->splitAndAdd( $otherExt, $count,
1094 substr( $text, $start, $off + $len - $start ) );
1095 $start = $off + $len;
1096 $found = true;
1097 break;
1098 } else {
1099 // end of nested element
1100 $level -= 1;
1101 }
1102 } else {
1103 // nested
1104 $level += 1;
1105 }
1106 $offset = $endMatches[0][1] + strlen( $endMatches[0][0] );
1107 }
1108 if ( ! $found ) {
1109 // couldn't find appropriate closing tag, skip
1110 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1111 $start += strlen( $matches[0][0] );
1112 }
1113 continue;
1114 }
1115 }
1116 // else: add as text extract
1117 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1118 break;
1119 }
1120
1121 $all = $textExt + $otherExt; // these have disjunct key sets
1122
1123 wfProfileOut( "$fname-split" );
1124
1125 // prepare regexps
1126 foreach ( $terms as $index => $term ) {
1127 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1128 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1129 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1130 } else {
1131 $terms[$index] = $term;
1132 }
1133 }
1134 $anyterm = implode( '|', $terms );
1135 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1136
1137 // @todo FIXME: A hack to scale contextchars, a correct solution
1138 // would be to have contextchars actually be char and not byte
1139 // length, and do proper utf-8 substrings and lengths everywhere,
1140 // but PHP is making that very hard and unclean to implement :(
1141 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1142 $contextchars = intval( $contextchars * $scale );
1143
1144 $patPre = "(^|$wgSearchHighlightBoundaries)";
1145 $patPost = "($wgSearchHighlightBoundaries|$)";
1146
1147 $pat1 = "/(" . $phrase . ")/ui";
1148 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1149
1150 wfProfileIn( "$fname-extract" );
1151
1152 $left = $contextlines;
1153
1154 $snippets = array();
1155 $offsets = array();
1156
1157 // show beginning only if it contains all words
1158 $first = 0;
1159 $firstText = '';
1160 foreach ( $textExt as $index => $line ) {
1161 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1162 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1163 $first = $index;
1164 break;
1165 }
1166 }
1167 if ( $firstText ) {
1168 $succ = true;
1169 // check if first text contains all terms
1170 foreach ( $terms as $term ) {
1171 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1172 $succ = false;
1173 break;
1174 }
1175 }
1176 if ( $succ ) {
1177 $snippets[$first] = $firstText;
1178 $offsets[$first] = 0;
1179 }
1180 }
1181 if ( ! $snippets ) {
1182 // match whole query on text
1183 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1184 // match whole query on templates/tables/images
1185 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1186 // match any words on text
1187 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1188 // match any words on templates/tables/images
1189 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1190
1191 ksort( $snippets );
1192 }
1193
1194 // add extra chars to each snippet to make snippets constant size
1195 $extended = array();
1196 if ( count( $snippets ) == 0 ) {
1197 // couldn't find the target words, just show beginning of article
1198 if ( array_key_exists( $first, $all ) ) {
1199 $targetchars = $contextchars * $contextlines;
1200 $snippets[$first] = '';
1201 $offsets[$first] = 0;
1202 }
1203 } else {
1204 // if begin of the article contains the whole phrase, show only that !!
1205 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1206 && $offsets[$first] < $contextchars * 2 ) {
1207 $snippets = array( $first => $snippets[$first] );
1208 }
1209
1210 // calc by how much to extend existing snippets
1211 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1212 }
1213
1214 foreach ( $snippets as $index => $line ) {
1215 $extended[$index] = $line;
1216 $len = strlen( $line );
1217 if ( $len < $targetchars - 20 ) {
1218 // complete this line
1219 if ( $len < strlen( $all[$index] ) ) {
1220 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] + $targetchars, $offsets[$index] );
1221 $len = strlen( $extended[$index] );
1222 }
1223
1224 // add more lines
1225 $add = $index + 1;
1226 while ( $len < $targetchars - 20
1227 && array_key_exists( $add, $all )
1228 && !array_key_exists( $add, $snippets ) ) {
1229 $offsets[$add] = 0;
1230 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1231 $extended[$add] = $tt;
1232 $len += strlen( $tt );
1233 $add++;
1234 }
1235 }
1236 }
1237
1238 // $snippets = array_map( 'htmlspecialchars', $extended );
1239 $snippets = $extended;
1240 $last = - 1;
1241 $extract = '';
1242 foreach ( $snippets as $index => $line ) {
1243 if ( $last == - 1 ) {
1244 $extract .= $line; // first line
1245 } elseif ( $last + 1 == $index && $offsets[$last] + strlen( $snippets[$last] ) >= strlen( $all[$last] ) ) {
1246 $extract .= " " . $line; // continous lines
1247 } else {
1248 $extract .= '<b> ... </b>' . $line;
1249 }
1250
1251 $last = $index;
1252 }
1253 if ( $extract ) {
1254 $extract .= '<b> ... </b>';
1255 }
1256
1257 $processed = array();
1258 foreach ( $terms as $term ) {
1259 if ( ! isset( $processed[$term] ) ) {
1260 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1261 $extract = preg_replace( $pat3,
1262 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1263 $processed[$term] = true;
1264 }
1265 }
1266
1267 wfProfileOut( "$fname-extract" );
1268
1269 return $extract;
1270 }
1271
1272 /**
1273 * Split text into lines and add it to extracts array
1274 *
1275 * @param array $extracts index -> $line
1276 * @param $count Integer
1277 * @param $text String
1278 */
1279 function splitAndAdd( &$extracts, &$count, $text ) {
1280 $split = explode( "\n", $this->mCleanWikitext ? $this->removeWiki( $text ) : $text );
1281 foreach ( $split as $line ) {
1282 $tt = trim( $line );
1283 if ( $tt ) {
1284 $extracts[$count++] = $tt;
1285 }
1286 }
1287 }
1288
1289 /**
1290 * Do manual case conversion for non-ascii chars
1291 *
1292 * @param $matches Array
1293 * @return string
1294 */
1295 function caseCallback( $matches ) {
1296 global $wgContLang;
1297 if ( strlen( $matches[0] ) > 1 ) {
1298 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1299 } else {
1300 return $matches[0];
1301 }
1302 }
1303
1304 /**
1305 * Extract part of the text from start to end, but by
1306 * not chopping up words
1307 * @param $text String
1308 * @param $start Integer
1309 * @param $end Integer
1310 * @param $posStart Integer: (out) actual start position
1311 * @param $posEnd Integer: (out) actual end position
1312 * @return String
1313 */
1314 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1315 if ( $start != 0 ) {
1316 $start = $this->position( $text, $start, 1 );
1317 }
1318 if ( $end >= strlen( $text ) ) {
1319 $end = strlen( $text );
1320 } else {
1321 $end = $this->position( $text, $end );
1322 }
1323
1324 if ( !is_null( $posStart ) ) {
1325 $posStart = $start;
1326 }
1327 if ( !is_null( $posEnd ) ) {
1328 $posEnd = $end;
1329 }
1330
1331 if ( $end > $start ) {
1332 return substr( $text, $start, $end - $start );
1333 } else {
1334 return '';
1335 }
1336 }
1337
1338 /**
1339 * Find a nonletter near a point (index) in the text
1340 *
1341 * @param $text String
1342 * @param $point Integer
1343 * @param $offset Integer: offset to found index
1344 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1345 */
1346 function position( $text, $point, $offset = 0 ) {
1347 $tolerance = 10;
1348 $s = max( 0, $point - $tolerance );
1349 $l = min( strlen( $text ), $point + $tolerance ) - $s;
1350 $m = array();
1351 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE ) ) {
1352 return $m[0][1] + $s + $offset;
1353 } else {
1354 // check if point is on a valid first UTF8 char
1355 $char = ord( $text[$point] );
1356 while ( $char >= 0x80 && $char < 0xc0 ) {
1357 // skip trailing bytes
1358 $point++;
1359 if ( $point >= strlen( $text ) ) {
1360 return strlen( $text );
1361 }
1362 $char = ord( $text[$point] );
1363 }
1364 return $point;
1365
1366 }
1367 }
1368
1369 /**
1370 * Search extracts for a pattern, and return snippets
1371 *
1372 * @param string $pattern regexp for matching lines
1373 * @param array $extracts extracts to search
1374 * @param $linesleft Integer: number of extracts to make
1375 * @param $contextchars Integer: length of snippet
1376 * @param array $out map for highlighted snippets
1377 * @param array $offsets map of starting points of snippets
1378 * @protected
1379 */
1380 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1381 if ( $linesleft == 0 ) {
1382 return; // nothing to do
1383 }
1384 foreach ( $extracts as $index => $line ) {
1385 if ( array_key_exists( $index, $out ) ) {
1386 continue; // this line already highlighted
1387 }
1388
1389 $m = array();
1390 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) ) {
1391 continue;
1392 }
1393
1394 $offset = $m[0][1];
1395 $len = strlen( $m[0][0] );
1396 if ( $offset + $len < $contextchars ) {
1397 $begin = 0;
1398 } elseif ( $len > $contextchars ) {
1399 $begin = $offset;
1400 } else {
1401 $begin = $offset + intval( ( $len - $contextchars ) / 2 );
1402 }
1403
1404 $end = $begin + $contextchars;
1405
1406 $posBegin = $begin;
1407 // basic snippet from this line
1408 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1409 $offsets[$index] = $posBegin;
1410 $linesleft--;
1411 if ( $linesleft == 0 ) {
1412 return;
1413 }
1414 }
1415 }
1416
1417 /**
1418 * Basic wikitext removal
1419 * @protected
1420 * @return mixed
1421 */
1422 function removeWiki( $text ) {
1423 $fname = __METHOD__;
1424 wfProfileIn( $fname );
1425
1426 // $text = preg_replace( "/'{2,5}/", "", $text );
1427 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1428 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1429 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1430 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1431 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1432 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1433 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1434 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1435 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1436 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1437 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1438 $text = preg_replace( "/'''''/", "", $text );
1439 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1440 $text = preg_replace( "/''/", "", $text );
1441
1442 wfProfileOut( $fname );
1443 return $text;
1444 }
1445
1446 /**
1447 * callback to replace [[target|caption]] kind of links, if
1448 * the target is category or image, leave it
1449 *
1450 * @param $matches Array
1451 */
1452 function linkReplace( $matches ) {
1453 $colon = strpos( $matches[1], ':' );
1454 if ( $colon === false ) {
1455 return $matches[2]; // replace with caption
1456 }
1457 global $wgContLang;
1458 $ns = substr( $matches[1], 0, $colon );
1459 $index = $wgContLang->getNsIndex( $ns );
1460 if ( $index !== false && ( $index == NS_FILE || $index == NS_CATEGORY ) ) {
1461 return $matches[0]; // return the whole thing
1462 } else {
1463 return $matches[2];
1464 }
1465 }
1466
1467 /**
1468 * Simple & fast snippet extraction, but gives completely unrelevant
1469 * snippets
1470 *
1471 * @param $text String
1472 * @param $terms Array
1473 * @param $contextlines Integer
1474 * @param $contextchars Integer
1475 * @return String
1476 */
1477 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1478 global $wgContLang;
1479 $fname = __METHOD__;
1480
1481 $lines = explode( "\n", $text );
1482
1483 $terms = implode( '|', $terms );
1484 $max = intval( $contextchars ) + 1;
1485 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1486
1487 $lineno = 0;
1488
1489 $extract = "";
1490 wfProfileIn( "$fname-extract" );
1491 foreach ( $lines as $line ) {
1492 if ( 0 == $contextlines ) {
1493 break;
1494 }
1495 ++$lineno;
1496 $m = array();
1497 if ( ! preg_match( $pat1, $line, $m ) ) {
1498 continue;
1499 }
1500 --$contextlines;
1501 // truncate function changes ... to relevant i18n message.
1502 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1503
1504 if ( count( $m ) < 3 ) {
1505 $post = '';
1506 } else {
1507 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1508 }
1509
1510 $found = $m[2];
1511
1512 $line = htmlspecialchars( $pre . $found . $post );
1513 $pat2 = '/(' . $terms . ")/i";
1514 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1515
1516 $extract .= "${line}\n";
1517 }
1518 wfProfileOut( "$fname-extract" );
1519
1520 return $extract;
1521 }
1522
1523 }
1524
1525 /**
1526 * Dummy class to be used when non-supported Database engine is present.
1527 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1528 * such as a LIKE search through titles.
1529 * @ingroup Search
1530 */
1531 class SearchEngineDummy extends SearchEngine {
1532 // no-op
1533 }