Don't display multiple language links to the same language
[mediawiki.git] / includes / search / SearchEngine.php
blob2ccb6d3164d7cd02b0056bc76c5aeb74f74ebf72
1 <?php
2 /**
3 * Basic search engine
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.
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.
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
20 * @file
21 * @ingroup Search
24 /**
25 * @defgroup Search Search
28 /**
29 * Contain a class for special pages
30 * @ingroup Search
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;
40 /// Feature values
41 protected $features = array();
43 /**
44 * @var DatabaseBase
46 protected $db;
48 function __construct($db = null) {
49 if ( $db ) {
50 $this->db = $db;
51 } else {
52 $this->db = wfGetDB( DB_SLAVE );
56 /**
57 * Perform a full text search query and return a result set.
58 * If title searches are not supported or disabled, return null.
59 * STUB
61 * @param $term String: raw search term
62 * @return SearchResultSet
64 function searchText( $term ) {
65 return null;
68 /**
69 * Perform a title-only search query and return a result set.
70 * If title searches are not supported or disabled, return null.
71 * STUB
73 * @param $term String: raw search term
74 * @return SearchResultSet
76 function searchTitle( $term ) {
77 return null;
80 /**
81 * If this search backend can list/unlist redirects
82 * @deprecated since 1.18 Call supports( 'list-redirects' );
83 * @return bool
85 function acceptListRedirects() {
86 wfDeprecated( __METHOD__, '1.18' );
87 return $this->supports( 'list-redirects' );
90 /**
91 * @since 1.18
92 * @param $feature String
93 * @return Boolean
95 public function supports( $feature ) {
96 switch( $feature ) {
97 case 'list-redirects':
98 return true;
99 case 'title-suffix-filter':
100 default:
101 return false;
106 * Way to pass custom data for engines
107 * @since 1.18
108 * @param $feature String
109 * @param $data Mixed
110 * @return bool
112 public function setFeatureData( $feature, $data ) {
113 $this->features[$feature] = $data;
117 * When overridden in derived class, performs database-specific conversions
118 * on text to be used for searching or updating search index.
119 * Default implementation does nothing (simply returns $string).
121 * @param $string string: String to process
122 * @return string
124 public function normalizeText( $string ) {
125 global $wgContLang;
127 // Some languages such as Chinese require word segmentation
128 return $wgContLang->segmentByWord( $string );
132 * Transform search term in cases when parts of the query came as different GET params (when supported)
133 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
135 function transformSearchTerm( $term ) {
136 return $term;
140 * If an exact title match can be found, or a very slightly close match,
141 * return the title. If no match, returns NULL.
143 * @param $searchterm String
144 * @return Title
146 public static function getNearMatch( $searchterm ) {
147 $title = self::getNearMatchInternal( $searchterm );
149 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
150 return $title;
154 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
155 * SearchResultSet.
157 * @param $searchterm string
158 * @return SearchResultSet
160 public static function getNearMatchResultSet( $searchterm ) {
161 return new SearchNearMatchResultSet( self::getNearMatch( $searchterm ) );
165 * Really find the title match.
166 * @return null|\Title
168 private static function getNearMatchInternal( $searchterm ) {
169 global $wgContLang, $wgEnableSearchContributorsByIP;
171 $allSearchTerms = array( $searchterm );
173 if ( $wgContLang->hasVariants() ) {
174 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
177 $titleResult = null;
178 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
179 return $titleResult;
182 foreach ( $allSearchTerms as $term ) {
184 # Exact match? No need to look further.
185 $title = Title::newFromText( $term );
186 if ( is_null( $title ) ){
187 return null;
190 if ( $title->isSpecialPage() || $title->isExternal() || $title->exists() ) {
191 return $title;
194 # See if it still otherwise has content is some sane sense
195 $page = WikiPage::factory( $title );
196 if ( $page->hasViewableContent() ) {
197 return $title;
200 # 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;
207 # Now try capitalized string
209 $title = Title::newFromText( $wgContLang->ucwords( $term ) );
210 if ( $title && $title->exists() ) {
211 return $title;
214 # Now try all upper case
216 $title = Title::newFromText( $wgContLang->uc( $term ) );
217 if ( $title && $title->exists() ) {
218 return $title;
221 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
222 $title = Title::newFromText( $wgContLang->ucwordbreaks( $term ) );
223 if ( $title && $title->exists() ) {
224 return $title;
227 // Give hooks a chance at better match variants
228 $title = null;
229 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
230 return $title;
234 $title = Title::newFromText( $searchterm );
237 # Entering an IP address goes to the contributions page
238 if ( $wgEnableSearchContributorsByIP ) {
239 if ( ( $title->getNamespace() == NS_USER && User::isIP( $title->getText() ) )
240 || User::isIP( trim( $searchterm ) ) ) {
241 return SpecialPage::getTitleFor( 'Contributions', $title->getDBkey() );
246 # Entering a user goes to the user page whether it's there or not
247 if ( $title->getNamespace() == NS_USER ) {
248 return $title;
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;
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() ) );
267 # Quoted term? Try without the quotes...
268 $matches = array();
269 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
270 return SearchEngine::getNearMatch( $matches[1] );
273 return null;
276 public static function legalSearchChars() {
277 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
281 * Set the maximum number of results to return
282 * and how many to skip before returning the first.
284 * @param $limit Integer
285 * @param $offset Integer
287 function setLimitOffset( $limit, $offset = 0 ) {
288 $this->limit = intval( $limit );
289 $this->offset = intval( $offset );
293 * Set which namespaces the search should include.
294 * Give an array of namespace index numbers.
296 * @param $namespaces Array
298 function setNamespaces( $namespaces ) {
299 $this->namespaces = $namespaces;
303 * Parse some common prefixes: all (search everything)
304 * or namespace names
306 * @param $query String
307 * @return string
309 function replacePrefixes( $query ) {
310 global $wgContLang;
312 $parsed = $query;
313 if ( strpos( $query, ':' ) === false ) { // nothing to do
314 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
315 return $parsed;
318 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
319 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
320 $this->namespaces = null;
321 $parsed = substr( $query, strlen( $allkeyword ) );
322 } elseif ( strpos( $query, ':' ) !== false ) {
323 $prefix = substr( $query, 0, strpos( $query, ':' ) );
324 $index = $wgContLang->getNsIndex( $prefix );
325 if ( $index !== false ) {
326 $this->namespaces = array( $index );
327 $parsed = substr( $query, strlen( $prefix ) + 1 );
330 if ( trim( $parsed ) == '' )
331 $parsed = $query; // prefix was the whole query
333 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
335 return $parsed;
339 * Make a list of searchable namespaces and their canonical names.
340 * @return Array
342 public static function searchableNamespaces() {
343 global $wgContLang;
344 $arr = array();
345 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
346 if ( $ns >= NS_MAIN ) {
347 $arr[$ns] = $name;
351 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
352 return $arr;
356 * Extract default namespaces to search from the given user's
357 * settings, returning a list of index numbers.
359 * @param $user User
360 * @return Array
362 public static function userNamespaces( $user ) {
363 global $wgSearchEverythingOnlyLoggedIn;
365 $searchableNamespaces = SearchEngine::searchableNamespaces();
367 // get search everything preference, that can be set to be read for logged-in users
368 // it overrides other options
369 if ( !$wgSearchEverythingOnlyLoggedIn || $user->isLoggedIn() ) {
370 if ( $user->getOption( 'searcheverything' ) ) {
371 return array_keys( $searchableNamespaces );
375 $arr = array();
376 foreach ( $searchableNamespaces as $ns => $name ) {
377 if ( $user->getOption( 'searchNs' . $ns ) ) {
378 $arr[] = $ns;
382 return $arr;
386 * Find snippet highlight settings for all users
388 * @return Array contextlines, contextchars
390 public static function userHighlightPrefs() {
391 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
392 $contextchars = 75; // same as above.... :P
393 return array( $contextlines, $contextchars );
397 * An array of namespaces indexes to be searched by default
399 * @return Array
401 public static function defaultNamespaces() {
402 global $wgNamespacesToBeSearchedDefault;
404 return array_keys( $wgNamespacesToBeSearchedDefault, true );
408 * Get a list of namespace names useful for showing in tooltips
409 * and preferences
411 * @param $namespaces Array
412 * @return array
414 public static function namespacesAsText( $namespaces ) {
415 global $wgContLang;
417 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
418 foreach ( $formatted as $key => $ns ) {
419 if ( empty( $ns ) )
420 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
422 return $formatted;
426 * Return the help namespaces to be shown on Special:Search
428 * @return Array
430 public static function helpNamespaces() {
431 global $wgNamespacesToBeSearchedHelp;
433 return array_keys( $wgNamespacesToBeSearchedHelp, true );
437 * Return a 'cleaned up' search string
439 * @param $text String
440 * @return String
442 function filter( $text ) {
443 $lc = $this->legalSearchChars();
444 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
447 * Load up the appropriate search engine class for the currently
448 * active database backend, and return a configured instance.
450 * @return SearchEngine
452 public static function create() {
453 global $wgSearchType;
454 $dbr = null;
455 if ( $wgSearchType ) {
456 $class = $wgSearchType;
457 } else {
458 $dbr = wfGetDB( DB_SLAVE );
459 $class = $dbr->getSearchEngine();
461 $search = new $class( $dbr );
462 $search->setLimitOffset( 0, 0 );
463 return $search;
467 * Create or update the search index record for the given page.
468 * Title and text should be pre-processed.
469 * STUB
471 * @param $id Integer
472 * @param $title String
473 * @param $text String
475 function update( $id, $title, $text ) {
476 // no-op
480 * Update a search index record's title only.
481 * Title should be pre-processed.
482 * STUB
484 * @param $id Integer
485 * @param $title String
487 function updateTitle( $id, $title ) {
488 // no-op
492 * Get OpenSearch suggestion template
494 * @return String
496 public static function getOpenSearchTemplate() {
497 global $wgOpenSearchTemplate, $wgCanonicalServer;
498 if ( $wgOpenSearchTemplate ) {
499 return $wgOpenSearchTemplate;
500 } else {
501 $ns = implode( '|', SearchEngine::defaultNamespaces() );
502 if ( !$ns ) {
503 $ns = "0";
505 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
510 * Get internal MediaWiki Suggest template
512 * @return String
514 public static function getMWSuggestTemplate() {
515 global $wgMWSuggestTemplate, $wgServer;
516 if ( $wgMWSuggestTemplate )
517 return $wgMWSuggestTemplate;
518 else
519 return $wgServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
524 * @ingroup Search
526 class SearchResultSet {
528 * Fetch an array of regular expression fragments for matching
529 * the search terms as parsed by this engine in a text extract.
530 * STUB
532 * @return Array
534 function termMatches() {
535 return array();
538 function numRows() {
539 return 0;
543 * Return true if results are included in this result set.
544 * STUB
546 * @return Boolean
548 function hasResults() {
549 return false;
553 * Some search modes return a total hit count for the query
554 * in the entire article database. This may include pages
555 * in namespaces that would not be matched on the given
556 * settings.
558 * Return null if no total hits number is supported.
560 * @return Integer
562 function getTotalHits() {
563 return null;
567 * Some search modes return a suggested alternate term if there are
568 * no exact hits. Returns true if there is one on this set.
570 * @return Boolean
572 function hasSuggestion() {
573 return false;
577 * @return String: suggested query, null if none
579 function getSuggestionQuery() {
580 return null;
584 * @return String: HTML highlighted suggested query, '' if none
586 function getSuggestionSnippet() {
587 return '';
591 * Return information about how and from where the results were fetched,
592 * should be useful for diagnostics and debugging
594 * @return String
596 function getInfo() {
597 return null;
601 * Return a result set of hits on other (multiple) wikis associated with this one
603 * @return SearchResultSet
605 function getInterwikiResults() {
606 return null;
610 * Check if there are results on other wikis
612 * @return Boolean
614 function hasInterwikiResults() {
615 return $this->getInterwikiResults() != null;
619 * Fetches next search result, or false.
620 * STUB
622 * @return SearchResult
624 function next() {
625 return false;
629 * Frees the result set, if applicable.
631 function free() {
632 // ...
637 * This class is used for different SQL-based search engines shipped with MediaWiki
639 class SqlSearchResultSet extends SearchResultSet {
641 protected $mResultSet;
643 function __construct( $resultSet, $terms ) {
644 $this->mResultSet = $resultSet;
645 $this->mTerms = $terms;
648 function termMatches() {
649 return $this->mTerms;
652 function numRows() {
653 if ( $this->mResultSet === false )
654 return false;
656 return $this->mResultSet->numRows();
659 function next() {
660 if ( $this->mResultSet === false )
661 return false;
663 $row = $this->mResultSet->fetchObject();
664 if ( $row === false )
665 return false;
667 return SearchResult::newFromRow( $row );
670 function free() {
671 if ( $this->mResultSet === false )
672 return false;
674 $this->mResultSet->free();
679 * @ingroup Search
681 class SearchResultTooMany {
682 # # Some search engines may bail out if too many matches are found
687 * @todo FIXME: This class is horribly factored. It would probably be better to
688 * have a useful base class to which you pass some standard information, then
689 * let the fancy self-highlighters extend that.
690 * @ingroup Search
692 class SearchResult {
695 * @var Revision
697 var $mRevision = null;
698 var $mImage = null;
701 * @var Title
703 var $mTitle;
706 * @var String
708 var $mText;
711 * Return a new SearchResult and initializes it with a title.
713 * @param $title Title
714 * @return SearchResult
716 public static function newFromTitle( $title ) {
717 $result = new self();
718 $result->initFromTitle( $title );
719 return $result;
722 * Return a new SearchResult and initializes it with a row.
724 * @param $row object
725 * @return SearchResult
727 public static function newFromRow( $row ) {
728 $result = new self();
729 $result->initFromRow( $row );
730 return $result;
733 public function __construct( $row = null ) {
734 if ( !is_null( $row ) ) {
735 // Backwards compatibility with pre-1.17 callers
736 $this->initFromRow( $row );
741 * Initialize from a database row. Makes a Title and passes that to
742 * initFromTitle.
744 * @param $row object
746 protected function initFromRow( $row ) {
747 $this->initFromTitle( Title::makeTitle( $row->page_namespace, $row->page_title ) );
751 * Initialize from a Title and if possible initializes a corresponding
752 * Revision and File.
754 * @param $title Title
756 protected function initFromTitle( $title ) {
757 $this->mTitle = $title;
758 if ( !is_null( $this->mTitle ) ) {
759 $id = false;
760 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
761 $this->mRevision = Revision::newFromTitle(
762 $this->mTitle, $id, Revision::READ_NORMAL );
763 if ( $this->mTitle->getNamespace() === NS_FILE )
764 $this->mImage = wfFindFile( $this->mTitle );
769 * Check if this is result points to an invalid title
771 * @return Boolean
773 function isBrokenTitle() {
774 if ( is_null( $this->mTitle ) )
775 return true;
776 return false;
780 * Check if target page is missing, happens when index is out of date
782 * @return Boolean
784 function isMissingRevision() {
785 return !$this->mRevision && !$this->mImage;
789 * @return Title
791 function getTitle() {
792 return $this->mTitle;
796 * @return float|null if not supported
798 function getScore() {
799 return null;
803 * Lazy initialization of article text from DB
805 protected function initText() {
806 if ( !isset( $this->mText ) ) {
807 if ( $this->mRevision != null )
808 $this->mText = $this->mRevision->getText();
809 else // TODO: can we fetch raw wikitext for commons images?
810 $this->mText = '';
816 * @param $terms Array: terms to highlight
817 * @return String: highlighted text snippet, null (and not '') if not supported
819 function getTextSnippet( $terms ) {
820 global $wgUser, $wgAdvancedSearchHighlighting;
821 $this->initText();
822 list( $contextlines, $contextchars ) = SearchEngine::userHighlightPrefs( $wgUser );
823 $h = new SearchHighlighter();
824 if ( $wgAdvancedSearchHighlighting )
825 return $h->highlightText( $this->mText, $terms, $contextlines, $contextchars );
826 else
827 return $h->highlightSimple( $this->mText, $terms, $contextlines, $contextchars );
831 * @param $terms Array: terms to highlight
832 * @return String: highlighted title, '' if not supported
834 function getTitleSnippet( $terms ) {
835 return '';
839 * @param $terms Array: terms to highlight
840 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
842 function getRedirectSnippet( $terms ) {
843 return '';
847 * @return Title object for the redirect to this page, null if none or not supported
849 function getRedirectTitle() {
850 return null;
854 * @return string highlighted relevant section name, null if none or not supported
856 function getSectionSnippet() {
857 return '';
861 * @return Title object (pagename+fragment) for the section, null if none or not supported
863 function getSectionTitle() {
864 return null;
868 * @return String: timestamp
870 function getTimestamp() {
871 if ( $this->mRevision )
872 return $this->mRevision->getTimestamp();
873 elseif ( $this->mImage )
874 return $this->mImage->getTimestamp();
875 return '';
879 * @return Integer: number of words
881 function getWordCount() {
882 $this->initText();
883 return str_word_count( $this->mText );
887 * @return Integer: size in bytes
889 function getByteSize() {
890 $this->initText();
891 return strlen( $this->mText );
895 * @return Boolean if hit has related articles
897 function hasRelated() {
898 return false;
902 * @return String: interwiki prefix of the title (return iw even if title is broken)
904 function getInterwikiPrefix() {
905 return '';
909 * A SearchResultSet wrapper for SearchEngine::getNearMatch
911 class SearchNearMatchResultSet extends SearchResultSet {
912 private $fetched = false;
914 * @param $match mixed Title if matched, else null
916 public function __construct( $match ) {
917 $this->result = $match;
919 public function hasResult() {
920 return (bool)$this->result;
922 public function numRows() {
923 return $this->hasResults() ? 1 : 0;
925 public function next() {
926 if ( $this->fetched || !$this->result ) {
927 return false;
929 $this->fetched = true;
930 return SearchResult::newFromTitle( $this->result );
935 * Highlight bits of wikitext
937 * @ingroup Search
939 class SearchHighlighter {
940 var $mCleanWikitext = true;
942 function __construct( $cleanupWikitext = true ) {
943 $this->mCleanWikitext = $cleanupWikitext;
947 * Default implementation of wikitext highlighting
949 * @param $text String
950 * @param $terms Array: terms to highlight (unescaped)
951 * @param $contextlines Integer
952 * @param $contextchars Integer
953 * @return String
955 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
956 global $wgContLang;
957 global $wgSearchHighlightBoundaries;
958 $fname = __METHOD__;
960 if ( $text == '' )
961 return '';
963 // spli text into text + templates/links/tables
964 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
965 // first capture group is for detecting nested templates/links/tables/references
966 $endPatterns = array(
967 1 => '/(\{\{)|(\}\})/', // template
968 2 => '/(\[\[)|(\]\])/', // image
969 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
971 // @todo FIXME: This should prolly be a hook or something
972 if ( function_exists( 'wfCite' ) ) {
973 $spat .= '|(<ref>)'; // references via cite extension
974 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
976 $spat .= '/';
977 $textExt = array(); // text extracts
978 $otherExt = array(); // other extracts
979 wfProfileIn( "$fname-split" );
980 $start = 0;
981 $textLen = strlen( $text );
982 $count = 0; // sequence number to maintain ordering
983 while ( $start < $textLen ) {
984 // find start of template/image/table
985 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE, $start ) ) {
986 $epat = '';
987 foreach ( $matches as $key => $val ) {
988 if ( $key > 0 && $val[1] != - 1 ) {
989 if ( $key == 2 ) {
990 // see if this is an image link
991 $ns = substr( $val[0], 2, - 1 );
992 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE )
993 break;
996 $epat = $endPatterns[$key];
997 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
998 $start = $val[1];
999 break;
1002 if ( $epat ) {
1003 // find end (and detect any nested elements)
1004 $level = 0;
1005 $offset = $start + 1;
1006 $found = false;
1007 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE, $offset ) ) {
1008 if ( array_key_exists( 2, $endMatches ) ) {
1009 // found end
1010 if ( $level == 0 ) {
1011 $len = strlen( $endMatches[2][0] );
1012 $off = $endMatches[2][1];
1013 $this->splitAndAdd( $otherExt, $count,
1014 substr( $text, $start, $off + $len - $start ) );
1015 $start = $off + $len;
1016 $found = true;
1017 break;
1018 } else {
1019 // end of nested element
1020 $level -= 1;
1022 } else {
1023 // nested
1024 $level += 1;
1026 $offset = $endMatches[0][1] + strlen( $endMatches[0][0] );
1028 if ( ! $found ) {
1029 // couldn't find appropriate closing tag, skip
1030 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1031 $start += strlen( $matches[0][0] );
1033 continue;
1036 // else: add as text extract
1037 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1038 break;
1041 $all = $textExt + $otherExt; // these have disjunct key sets
1043 wfProfileOut( "$fname-split" );
1045 // prepare regexps
1046 foreach ( $terms as $index => $term ) {
1047 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1048 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1049 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1050 } else {
1051 $terms[$index] = $term;
1054 $anyterm = implode( '|', $terms );
1055 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1057 // @todo FIXME: A hack to scale contextchars, a correct solution
1058 // would be to have contextchars actually be char and not byte
1059 // length, and do proper utf-8 substrings and lengths everywhere,
1060 // but PHP is making that very hard and unclean to implement :(
1061 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1062 $contextchars = intval( $contextchars * $scale );
1064 $patPre = "(^|$wgSearchHighlightBoundaries)";
1065 $patPost = "($wgSearchHighlightBoundaries|$)";
1067 $pat1 = "/(" . $phrase . ")/ui";
1068 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1070 wfProfileIn( "$fname-extract" );
1072 $left = $contextlines;
1074 $snippets = array();
1075 $offsets = array();
1077 // show beginning only if it contains all words
1078 $first = 0;
1079 $firstText = '';
1080 foreach ( $textExt as $index => $line ) {
1081 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1082 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1083 $first = $index;
1084 break;
1087 if ( $firstText ) {
1088 $succ = true;
1089 // check if first text contains all terms
1090 foreach ( $terms as $term ) {
1091 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1092 $succ = false;
1093 break;
1096 if ( $succ ) {
1097 $snippets[$first] = $firstText;
1098 $offsets[$first] = 0;
1101 if ( ! $snippets ) {
1102 // match whole query on text
1103 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1104 // match whole query on templates/tables/images
1105 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1106 // match any words on text
1107 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1108 // match any words on templates/tables/images
1109 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1111 ksort( $snippets );
1114 // add extra chars to each snippet to make snippets constant size
1115 $extended = array();
1116 if ( count( $snippets ) == 0 ) {
1117 // couldn't find the target words, just show beginning of article
1118 if ( array_key_exists( $first, $all ) ) {
1119 $targetchars = $contextchars * $contextlines;
1120 $snippets[$first] = '';
1121 $offsets[$first] = 0;
1123 } else {
1124 // if begin of the article contains the whole phrase, show only that !!
1125 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1126 && $offsets[$first] < $contextchars * 2 ) {
1127 $snippets = array ( $first => $snippets[$first] );
1130 // calc by how much to extend existing snippets
1131 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1134 foreach ( $snippets as $index => $line ) {
1135 $extended[$index] = $line;
1136 $len = strlen( $line );
1137 if ( $len < $targetchars - 20 ) {
1138 // complete this line
1139 if ( $len < strlen( $all[$index] ) ) {
1140 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] + $targetchars, $offsets[$index] );
1141 $len = strlen( $extended[$index] );
1144 // add more lines
1145 $add = $index + 1;
1146 while ( $len < $targetchars - 20
1147 && array_key_exists( $add, $all )
1148 && !array_key_exists( $add, $snippets ) ) {
1149 $offsets[$add] = 0;
1150 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1151 $extended[$add] = $tt;
1152 $len += strlen( $tt );
1153 $add++;
1158 // $snippets = array_map('htmlspecialchars', $extended);
1159 $snippets = $extended;
1160 $last = - 1;
1161 $extract = '';
1162 foreach ( $snippets as $index => $line ) {
1163 if ( $last == - 1 )
1164 $extract .= $line; // first line
1165 elseif ( $last + 1 == $index && $offsets[$last] + strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1166 $extract .= " " . $line; // continous lines
1167 else
1168 $extract .= '<b> ... </b>' . $line;
1170 $last = $index;
1172 if ( $extract )
1173 $extract .= '<b> ... </b>';
1175 $processed = array();
1176 foreach ( $terms as $term ) {
1177 if ( ! isset( $processed[$term] ) ) {
1178 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1179 $extract = preg_replace( $pat3,
1180 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1181 $processed[$term] = true;
1185 wfProfileOut( "$fname-extract" );
1187 return $extract;
1191 * Split text into lines and add it to extracts array
1193 * @param $extracts Array: index -> $line
1194 * @param $count Integer
1195 * @param $text String
1197 function splitAndAdd( &$extracts, &$count, $text ) {
1198 $split = explode( "\n", $this->mCleanWikitext ? $this->removeWiki( $text ) : $text );
1199 foreach ( $split as $line ) {
1200 $tt = trim( $line );
1201 if ( $tt )
1202 $extracts[$count++] = $tt;
1207 * Do manual case conversion for non-ascii chars
1209 * @param $matches Array
1210 * @return string
1212 function caseCallback( $matches ) {
1213 global $wgContLang;
1214 if ( strlen( $matches[0] ) > 1 ) {
1215 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1216 } else {
1217 return $matches[0];
1222 * Extract part of the text from start to end, but by
1223 * not chopping up words
1224 * @param $text String
1225 * @param $start Integer
1226 * @param $end Integer
1227 * @param $posStart Integer: (out) actual start position
1228 * @param $posEnd Integer: (out) actual end position
1229 * @return String
1231 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1232 if ( $start != 0 ) {
1233 $start = $this->position( $text, $start, 1 );
1235 if ( $end >= strlen( $text ) ) {
1236 $end = strlen( $text );
1237 } else {
1238 $end = $this->position( $text, $end );
1241 if ( !is_null( $posStart ) ) {
1242 $posStart = $start;
1244 if ( !is_null( $posEnd ) ) {
1245 $posEnd = $end;
1248 if ( $end > $start ) {
1249 return substr( $text, $start, $end - $start );
1250 } else {
1251 return '';
1256 * Find a nonletter near a point (index) in the text
1258 * @param $text String
1259 * @param $point Integer
1260 * @param $offset Integer: offset to found index
1261 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1263 function position( $text, $point, $offset = 0 ) {
1264 $tolerance = 10;
1265 $s = max( 0, $point - $tolerance );
1266 $l = min( strlen( $text ), $point + $tolerance ) - $s;
1267 $m = array();
1268 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE ) ) {
1269 return $m[0][1] + $s + $offset;
1270 } else {
1271 // check if point is on a valid first UTF8 char
1272 $char = ord( $text[$point] );
1273 while ( $char >= 0x80 && $char < 0xc0 ) {
1274 // skip trailing bytes
1275 $point++;
1276 if ( $point >= strlen( $text ) )
1277 return strlen( $text );
1278 $char = ord( $text[$point] );
1280 return $point;
1286 * Search extracts for a pattern, and return snippets
1288 * @param $pattern String: regexp for matching lines
1289 * @param $extracts Array: extracts to search
1290 * @param $linesleft Integer: number of extracts to make
1291 * @param $contextchars Integer: length of snippet
1292 * @param $out Array: map for highlighted snippets
1293 * @param $offsets Array: map of starting points of snippets
1294 * @protected
1296 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1297 if ( $linesleft == 0 )
1298 return; // nothing to do
1299 foreach ( $extracts as $index => $line ) {
1300 if ( array_key_exists( $index, $out ) )
1301 continue; // this line already highlighted
1303 $m = array();
1304 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) )
1305 continue;
1307 $offset = $m[0][1];
1308 $len = strlen( $m[0][0] );
1309 if ( $offset + $len < $contextchars )
1310 $begin = 0;
1311 elseif ( $len > $contextchars )
1312 $begin = $offset;
1313 else
1314 $begin = $offset + intval( ( $len - $contextchars ) / 2 );
1316 $end = $begin + $contextchars;
1318 $posBegin = $begin;
1319 // basic snippet from this line
1320 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1321 $offsets[$index] = $posBegin;
1322 $linesleft--;
1323 if ( $linesleft == 0 )
1324 return;
1329 * Basic wikitext removal
1330 * @protected
1331 * @return mixed
1333 function removeWiki( $text ) {
1334 $fname = __METHOD__;
1335 wfProfileIn( $fname );
1337 // $text = preg_replace("/'{2,5}/", "", $text);
1338 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1339 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1340 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1341 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1342 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1343 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1344 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1345 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1346 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1347 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1348 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1349 $text = preg_replace( "/'''''/", "", $text );
1350 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1351 $text = preg_replace( "/''/", "", $text );
1353 wfProfileOut( $fname );
1354 return $text;
1358 * callback to replace [[target|caption]] kind of links, if
1359 * the target is category or image, leave it
1361 * @param $matches Array
1363 function linkReplace( $matches ) {
1364 $colon = strpos( $matches[1], ':' );
1365 if ( $colon === false )
1366 return $matches[2]; // replace with caption
1367 global $wgContLang;
1368 $ns = substr( $matches[1], 0, $colon );
1369 $index = $wgContLang->getNsIndex( $ns );
1370 if ( $index !== false && ( $index == NS_FILE || $index == NS_CATEGORY ) )
1371 return $matches[0]; // return the whole thing
1372 else
1373 return $matches[2];
1378 * Simple & fast snippet extraction, but gives completely unrelevant
1379 * snippets
1381 * @param $text String
1382 * @param $terms Array
1383 * @param $contextlines Integer
1384 * @param $contextchars Integer
1385 * @return String
1387 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1388 global $wgContLang;
1389 $fname = __METHOD__;
1391 $lines = explode( "\n", $text );
1393 $terms = implode( '|', $terms );
1394 $max = intval( $contextchars ) + 1;
1395 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1397 $lineno = 0;
1399 $extract = "";
1400 wfProfileIn( "$fname-extract" );
1401 foreach ( $lines as $line ) {
1402 if ( 0 == $contextlines ) {
1403 break;
1405 ++$lineno;
1406 $m = array();
1407 if ( ! preg_match( $pat1, $line, $m ) ) {
1408 continue;
1410 --$contextlines;
1411 // truncate function changes ... to relevant i18n message.
1412 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1414 if ( count( $m ) < 3 ) {
1415 $post = '';
1416 } else {
1417 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1420 $found = $m[2];
1422 $line = htmlspecialchars( $pre . $found . $post );
1423 $pat2 = '/(' . $terms . ")/i";
1424 $line = preg_replace( $pat2,
1425 "<span class='searchmatch'>\\1</span>", $line );
1427 $extract .= "${line}\n";
1429 wfProfileOut( "$fname-extract" );
1431 return $extract;
1437 * Dummy class to be used when non-supported Database engine is present.
1438 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1439 * such as a LIKE search through titles.
1440 * @ingroup Search
1442 class SearchEngineDummy extends SearchEngine {
1443 // no-op