Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / search / SearchEngine.php
blob0348ed1cbd83dacdcfdb07860e809cb4578ea41b
1 <?php
2 /**
3 * Basic search engine
5 * @file
6 * @ingroup Search
7 */
9 /**
10 * @defgroup Search Search
13 /**
14 * Contain a class for special pages
15 * @ingroup Search
17 class SearchEngine {
18 var $limit = 10;
19 var $offset = 0;
20 var $prefix = '';
21 var $searchTerms = array();
22 var $namespaces = array( NS_MAIN );
23 var $showRedirects = false;
25 /// Feature values
26 protected $features = array();
28 /**
29 * @var DatabaseBase
31 protected $db;
33 function __construct($db = null) {
34 if ( $db ) {
35 $this->db = $db;
36 } else {
37 $this->db = wfGetDB( DB_SLAVE );
41 /**
42 * Perform a full text search query and return a result set.
43 * If title searches are not supported or disabled, return null.
44 * STUB
46 * @param $term String: raw search term
47 * @return SearchResultSet
49 function searchText( $term ) {
50 return null;
53 /**
54 * Perform a title-only search query and return a result set.
55 * If title searches are not supported or disabled, return null.
56 * STUB
58 * @param $term String: raw search term
59 * @return SearchResultSet
61 function searchTitle( $term ) {
62 return null;
65 /**
66 * If this search backend can list/unlist redirects
67 * @deprecated since 1.18 Call supports( 'list-redirects' );
68 * @return bool
70 function acceptListRedirects() {
71 wfDeprecated( __METHOD__, '1.18' );
72 return $this->supports( 'list-redirects' );
75 /**
76 * @since 1.18
77 * @param $feature String
78 * @return Boolean
80 public function supports( $feature ) {
81 switch( $feature ) {
82 case 'list-redirects':
83 return true;
84 case 'title-suffix-filter':
85 default:
86 return false;
90 /**
91 * Way to pass custom data for engines
92 * @since 1.18
93 * @param $feature String
94 * @param $data Mixed
95 * @return bool
97 public function setFeatureData( $feature, $data ) {
98 $this->features[$feature] = $data;
102 * When overridden in derived class, performs database-specific conversions
103 * on text to be used for searching or updating search index.
104 * Default implementation does nothing (simply returns $string).
106 * @param $string string: String to process
107 * @return string
109 public function normalizeText( $string ) {
110 global $wgContLang;
112 // Some languages such as Chinese require word segmentation
113 return $wgContLang->segmentByWord( $string );
117 * Transform search term in cases when parts of the query came as different GET params (when supported)
118 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
120 function transformSearchTerm( $term ) {
121 return $term;
125 * If an exact title match can be found, or a very slightly close match,
126 * return the title. If no match, returns NULL.
128 * @param $searchterm String
129 * @return Title
131 public static function getNearMatch( $searchterm ) {
132 $title = self::getNearMatchInternal( $searchterm );
134 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
135 return $title;
139 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
140 * SearchResultSet.
142 * @param $searchterm string
143 * @return SearchResultSet
145 public static function getNearMatchResultSet( $searchterm ) {
146 return new SearchNearMatchResultSet( self::getNearMatch( $searchterm ) );
150 * Really find the title match.
151 * @return null|\Title
153 private static function getNearMatchInternal( $searchterm ) {
154 global $wgContLang, $wgEnableSearchContributorsByIP;
156 $allSearchTerms = array( $searchterm );
158 if ( $wgContLang->hasVariants() ) {
159 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
162 $titleResult = null;
163 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
164 return $titleResult;
167 foreach ( $allSearchTerms as $term ) {
169 # Exact match? No need to look further.
170 $title = Title::newFromText( $term );
171 if ( is_null( $title ) ){
172 return null;
175 if ( $title->isSpecialPage() || $title->isExternal() || $title->exists() ) {
176 return $title;
179 # See if it still otherwise has content is some sane sense
180 $page = WikiPage::factory( $title );
181 if ( $page->hasViewableContent() ) {
182 return $title;
185 # Now try all lower case (i.e. first letter capitalized)
187 $title = Title::newFromText( $wgContLang->lc( $term ) );
188 if ( $title && $title->exists() ) {
189 return $title;
192 # Now try capitalized string
194 $title = Title::newFromText( $wgContLang->ucwords( $term ) );
195 if ( $title && $title->exists() ) {
196 return $title;
199 # Now try all upper case
201 $title = Title::newFromText( $wgContLang->uc( $term ) );
202 if ( $title && $title->exists() ) {
203 return $title;
206 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
207 $title = Title::newFromText( $wgContLang->ucwordbreaks( $term ) );
208 if ( $title && $title->exists() ) {
209 return $title;
212 // Give hooks a chance at better match variants
213 $title = null;
214 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
215 return $title;
219 $title = Title::newFromText( $searchterm );
222 # Entering an IP address goes to the contributions page
223 if ( $wgEnableSearchContributorsByIP ) {
224 if ( ( $title->getNamespace() == NS_USER && User::isIP( $title->getText() ) )
225 || User::isIP( trim( $searchterm ) ) ) {
226 return SpecialPage::getTitleFor( 'Contributions', $title->getDBkey() );
231 # Entering a user goes to the user page whether it's there or not
232 if ( $title->getNamespace() == NS_USER ) {
233 return $title;
236 # Go to images that exist even if there's no local page.
237 # There may have been a funny upload, or it may be on a shared
238 # file repository such as Wikimedia Commons.
239 if ( $title->getNamespace() == NS_FILE ) {
240 $image = wfFindFile( $title );
241 if ( $image ) {
242 return $title;
246 # MediaWiki namespace? Page may be "implied" if not customized.
247 # Just return it, with caps forced as the message system likes it.
248 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
249 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( $title->getText() ) );
252 # Quoted term? Try without the quotes...
253 $matches = array();
254 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
255 return SearchEngine::getNearMatch( $matches[1] );
258 return null;
261 public static function legalSearchChars() {
262 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
266 * Set the maximum number of results to return
267 * and how many to skip before returning the first.
269 * @param $limit Integer
270 * @param $offset Integer
272 function setLimitOffset( $limit, $offset = 0 ) {
273 $this->limit = intval( $limit );
274 $this->offset = intval( $offset );
278 * Set which namespaces the search should include.
279 * Give an array of namespace index numbers.
281 * @param $namespaces Array
283 function setNamespaces( $namespaces ) {
284 $this->namespaces = $namespaces;
288 * Parse some common prefixes: all (search everything)
289 * or namespace names
291 * @param $query String
292 * @return string
294 function replacePrefixes( $query ) {
295 global $wgContLang;
297 $parsed = $query;
298 if ( strpos( $query, ':' ) === false ) { // nothing to do
299 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
300 return $parsed;
303 $allkeyword = wfMsgForContent( 'searchall' ) . ":";
304 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
305 $this->namespaces = null;
306 $parsed = substr( $query, strlen( $allkeyword ) );
307 } elseif ( strpos( $query, ':' ) !== false ) {
308 $prefix = substr( $query, 0, strpos( $query, ':' ) );
309 $index = $wgContLang->getNsIndex( $prefix );
310 if ( $index !== false ) {
311 $this->namespaces = array( $index );
312 $parsed = substr( $query, strlen( $prefix ) + 1 );
315 if ( trim( $parsed ) == '' )
316 $parsed = $query; // prefix was the whole query
318 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
320 return $parsed;
324 * Make a list of searchable namespaces and their canonical names.
325 * @return Array
327 public static function searchableNamespaces() {
328 global $wgContLang;
329 $arr = array();
330 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
331 if ( $ns >= NS_MAIN ) {
332 $arr[$ns] = $name;
336 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
337 return $arr;
341 * Extract default namespaces to search from the given user's
342 * settings, returning a list of index numbers.
344 * @param $user User
345 * @return Array
347 public static function userNamespaces( $user ) {
348 global $wgSearchEverythingOnlyLoggedIn;
350 $searchableNamespaces = SearchEngine::searchableNamespaces();
352 // get search everything preference, that can be set to be read for logged-in users
353 // it overrides other options
354 if ( !$wgSearchEverythingOnlyLoggedIn || $user->isLoggedIn() ) {
355 if ( $user->getOption( 'searcheverything' ) ) {
356 return array_keys( $searchableNamespaces );
360 $arr = array();
361 foreach ( $searchableNamespaces as $ns => $name ) {
362 if ( $user->getOption( 'searchNs' . $ns ) ) {
363 $arr[] = $ns;
367 return $arr;
371 * Find snippet highlight settings for all users
373 * @return Array contextlines, contextchars
375 public static function userHighlightPrefs() {
376 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
377 $contextchars = 75; // same as above.... :P
378 return array( $contextlines, $contextchars );
382 * An array of namespaces indexes to be searched by default
384 * @return Array
386 public static function defaultNamespaces() {
387 global $wgNamespacesToBeSearchedDefault;
389 return array_keys( $wgNamespacesToBeSearchedDefault, true );
393 * Get a list of namespace names useful for showing in tooltips
394 * and preferences
396 * @param $namespaces Array
397 * @return array
399 public static function namespacesAsText( $namespaces ) {
400 global $wgContLang;
402 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
403 foreach ( $formatted as $key => $ns ) {
404 if ( empty( $ns ) )
405 $formatted[$key] = wfMsg( 'blanknamespace' );
407 return $formatted;
411 * Return the help namespaces to be shown on Special:Search
413 * @return Array
415 public static function helpNamespaces() {
416 global $wgNamespacesToBeSearchedHelp;
418 return array_keys( $wgNamespacesToBeSearchedHelp, true );
422 * Return a 'cleaned up' search string
424 * @param $text String
425 * @return String
427 function filter( $text ) {
428 $lc = $this->legalSearchChars();
429 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
432 * Load up the appropriate search engine class for the currently
433 * active database backend, and return a configured instance.
435 * @return SearchEngine
437 public static function create() {
438 global $wgSearchType;
439 $dbr = null;
440 if ( $wgSearchType ) {
441 $class = $wgSearchType;
442 } else {
443 $dbr = wfGetDB( DB_SLAVE );
444 $class = $dbr->getSearchEngine();
446 $search = new $class( $dbr );
447 $search->setLimitOffset( 0, 0 );
448 return $search;
452 * Create or update the search index record for the given page.
453 * Title and text should be pre-processed.
454 * STUB
456 * @param $id Integer
457 * @param $title String
458 * @param $text String
460 function update( $id, $title, $text ) {
461 // no-op
465 * Update a search index record's title only.
466 * Title should be pre-processed.
467 * STUB
469 * @param $id Integer
470 * @param $title String
472 function updateTitle( $id, $title ) {
473 // no-op
477 * Get OpenSearch suggestion template
479 * @return String
481 public static function getOpenSearchTemplate() {
482 global $wgOpenSearchTemplate, $wgCanonicalServer;
483 if ( $wgOpenSearchTemplate ) {
484 return $wgOpenSearchTemplate;
485 } else {
486 $ns = implode( '|', SearchEngine::defaultNamespaces() );
487 if ( !$ns ) {
488 $ns = "0";
490 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
495 * Get internal MediaWiki Suggest template
497 * @return String
499 public static function getMWSuggestTemplate() {
500 global $wgMWSuggestTemplate, $wgServer;
501 if ( $wgMWSuggestTemplate )
502 return $wgMWSuggestTemplate;
503 else
504 return $wgServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
509 * @ingroup Search
511 class SearchResultSet {
513 * Fetch an array of regular expression fragments for matching
514 * the search terms as parsed by this engine in a text extract.
515 * STUB
517 * @return Array
519 function termMatches() {
520 return array();
523 function numRows() {
524 return 0;
528 * Return true if results are included in this result set.
529 * STUB
531 * @return Boolean
533 function hasResults() {
534 return false;
538 * Some search modes return a total hit count for the query
539 * in the entire article database. This may include pages
540 * in namespaces that would not be matched on the given
541 * settings.
543 * Return null if no total hits number is supported.
545 * @return Integer
547 function getTotalHits() {
548 return null;
552 * Some search modes return a suggested alternate term if there are
553 * no exact hits. Returns true if there is one on this set.
555 * @return Boolean
557 function hasSuggestion() {
558 return false;
562 * @return String: suggested query, null if none
564 function getSuggestionQuery() {
565 return null;
569 * @return String: HTML highlighted suggested query, '' if none
571 function getSuggestionSnippet() {
572 return '';
576 * Return information about how and from where the results were fetched,
577 * should be useful for diagnostics and debugging
579 * @return String
581 function getInfo() {
582 return null;
586 * Return a result set of hits on other (multiple) wikis associated with this one
588 * @return SearchResultSet
590 function getInterwikiResults() {
591 return null;
595 * Check if there are results on other wikis
597 * @return Boolean
599 function hasInterwikiResults() {
600 return $this->getInterwikiResults() != null;
604 * Fetches next search result, or false.
605 * STUB
607 * @return SearchResult
609 function next() {
610 return false;
614 * Frees the result set, if applicable.
616 function free() {
617 // ...
622 * This class is used for different SQL-based search engines shipped with MediaWiki
624 class SqlSearchResultSet extends SearchResultSet {
626 protected $mResultSet;
628 function __construct( $resultSet, $terms ) {
629 $this->mResultSet = $resultSet;
630 $this->mTerms = $terms;
633 function termMatches() {
634 return $this->mTerms;
637 function numRows() {
638 if ( $this->mResultSet === false )
639 return false;
641 return $this->mResultSet->numRows();
644 function next() {
645 if ( $this->mResultSet === false )
646 return false;
648 $row = $this->mResultSet->fetchObject();
649 if ( $row === false )
650 return false;
652 return SearchResult::newFromRow( $row );
655 function free() {
656 if ( $this->mResultSet === false )
657 return false;
659 $this->mResultSet->free();
664 * @ingroup Search
666 class SearchResultTooMany {
667 # # Some search engines may bail out if too many matches are found
672 * @todo FIXME: This class is horribly factored. It would probably be better to
673 * have a useful base class to which you pass some standard information, then
674 * let the fancy self-highlighters extend that.
675 * @ingroup Search
677 class SearchResult {
680 * @var Revision
682 var $mRevision = null;
683 var $mImage = null;
686 * @var Title
688 var $mTitle;
691 * @var String
693 var $mText;
696 * Return a new SearchResult and initializes it with a title.
698 * @param $title Title
699 * @return SearchResult
701 public static function newFromTitle( $title ) {
702 $result = new self();
703 $result->initFromTitle( $title );
704 return $result;
707 * Return a new SearchResult and initializes it with a row.
709 * @param $row object
710 * @return SearchResult
712 public static function newFromRow( $row ) {
713 $result = new self();
714 $result->initFromRow( $row );
715 return $result;
718 public function __construct( $row = null ) {
719 if ( !is_null( $row ) ) {
720 // Backwards compatibility with pre-1.17 callers
721 $this->initFromRow( $row );
726 * Initialize from a database row. Makes a Title and passes that to
727 * initFromTitle.
729 * @param $row object
731 protected function initFromRow( $row ) {
732 $this->initFromTitle( Title::makeTitle( $row->page_namespace, $row->page_title ) );
736 * Initialize from a Title and if possible initializes a corresponding
737 * Revision and File.
739 * @param $title Title
741 protected function initFromTitle( $title ) {
742 $this->mTitle = $title;
743 if ( !is_null( $this->mTitle ) ) {
744 $this->mRevision = Revision::newFromTitle( $this->mTitle );
745 if ( $this->mTitle->getNamespace() === NS_FILE )
746 $this->mImage = wfFindFile( $this->mTitle );
751 * Check if this is result points to an invalid title
753 * @return Boolean
755 function isBrokenTitle() {
756 if ( is_null( $this->mTitle ) )
757 return true;
758 return false;
762 * Check if target page is missing, happens when index is out of date
764 * @return Boolean
766 function isMissingRevision() {
767 return !$this->mRevision && !$this->mImage;
771 * @return Title
773 function getTitle() {
774 return $this->mTitle;
778 * @return float|null if not supported
780 function getScore() {
781 return null;
785 * Lazy initialization of article text from DB
787 protected function initText() {
788 if ( !isset( $this->mText ) ) {
789 if ( $this->mRevision != null )
790 $this->mText = $this->mRevision->getText();
791 else // TODO: can we fetch raw wikitext for commons images?
792 $this->mText = '';
798 * @param $terms Array: terms to highlight
799 * @return String: highlighted text snippet, null (and not '') if not supported
801 function getTextSnippet( $terms ) {
802 global $wgUser, $wgAdvancedSearchHighlighting;
803 $this->initText();
804 list( $contextlines, $contextchars ) = SearchEngine::userHighlightPrefs( $wgUser );
805 $h = new SearchHighlighter();
806 if ( $wgAdvancedSearchHighlighting )
807 return $h->highlightText( $this->mText, $terms, $contextlines, $contextchars );
808 else
809 return $h->highlightSimple( $this->mText, $terms, $contextlines, $contextchars );
813 * @param $terms Array: terms to highlight
814 * @return String: highlighted title, '' if not supported
816 function getTitleSnippet( $terms ) {
817 return '';
821 * @param $terms Array: terms to highlight
822 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
824 function getRedirectSnippet( $terms ) {
825 return '';
829 * @return Title object for the redirect to this page, null if none or not supported
831 function getRedirectTitle() {
832 return null;
836 * @return string highlighted relevant section name, null if none or not supported
838 function getSectionSnippet() {
839 return '';
843 * @return Title object (pagename+fragment) for the section, null if none or not supported
845 function getSectionTitle() {
846 return null;
850 * @return String: timestamp
852 function getTimestamp() {
853 if ( $this->mRevision )
854 return $this->mRevision->getTimestamp();
855 elseif ( $this->mImage )
856 return $this->mImage->getTimestamp();
857 return '';
861 * @return Integer: number of words
863 function getWordCount() {
864 $this->initText();
865 return str_word_count( $this->mText );
869 * @return Integer: size in bytes
871 function getByteSize() {
872 $this->initText();
873 return strlen( $this->mText );
877 * @return Boolean if hit has related articles
879 function hasRelated() {
880 return false;
884 * @return String: interwiki prefix of the title (return iw even if title is broken)
886 function getInterwikiPrefix() {
887 return '';
891 * A SearchResultSet wrapper for SearchEngine::getNearMatch
893 class SearchNearMatchResultSet extends SearchResultSet {
894 private $fetched = false;
896 * @param $match mixed Title if matched, else null
898 public function __construct( $match ) {
899 $this->result = $match;
901 public function hasResult() {
902 return (bool)$this->result;
904 public function numRows() {
905 return $this->hasResults() ? 1 : 0;
907 public function next() {
908 if ( $this->fetched || !$this->result ) {
909 return false;
911 $this->fetched = true;
912 return SearchResult::newFromTitle( $this->result );
917 * Highlight bits of wikitext
919 * @ingroup Search
921 class SearchHighlighter {
922 var $mCleanWikitext = true;
924 function __construct( $cleanupWikitext = true ) {
925 $this->mCleanWikitext = $cleanupWikitext;
929 * Default implementation of wikitext highlighting
931 * @param $text String
932 * @param $terms Array: terms to highlight (unescaped)
933 * @param $contextlines Integer
934 * @param $contextchars Integer
935 * @return String
937 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
938 global $wgContLang;
939 global $wgSearchHighlightBoundaries;
940 $fname = __METHOD__;
942 if ( $text == '' )
943 return '';
945 // spli text into text + templates/links/tables
946 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
947 // first capture group is for detecting nested templates/links/tables/references
948 $endPatterns = array(
949 1 => '/(\{\{)|(\}\})/', // template
950 2 => '/(\[\[)|(\]\])/', // image
951 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
953 // @todo FIXME: This should prolly be a hook or something
954 if ( function_exists( 'wfCite' ) ) {
955 $spat .= '|(<ref>)'; // references via cite extension
956 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
958 $spat .= '/';
959 $textExt = array(); // text extracts
960 $otherExt = array(); // other extracts
961 wfProfileIn( "$fname-split" );
962 $start = 0;
963 $textLen = strlen( $text );
964 $count = 0; // sequence number to maintain ordering
965 while ( $start < $textLen ) {
966 // find start of template/image/table
967 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE, $start ) ) {
968 $epat = '';
969 foreach ( $matches as $key => $val ) {
970 if ( $key > 0 && $val[1] != - 1 ) {
971 if ( $key == 2 ) {
972 // see if this is an image link
973 $ns = substr( $val[0], 2, - 1 );
974 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE )
975 break;
978 $epat = $endPatterns[$key];
979 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
980 $start = $val[1];
981 break;
984 if ( $epat ) {
985 // find end (and detect any nested elements)
986 $level = 0;
987 $offset = $start + 1;
988 $found = false;
989 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE, $offset ) ) {
990 if ( array_key_exists( 2, $endMatches ) ) {
991 // found end
992 if ( $level == 0 ) {
993 $len = strlen( $endMatches[2][0] );
994 $off = $endMatches[2][1];
995 $this->splitAndAdd( $otherExt, $count,
996 substr( $text, $start, $off + $len - $start ) );
997 $start = $off + $len;
998 $found = true;
999 break;
1000 } else {
1001 // end of nested element
1002 $level -= 1;
1004 } else {
1005 // nested
1006 $level += 1;
1008 $offset = $endMatches[0][1] + strlen( $endMatches[0][0] );
1010 if ( ! $found ) {
1011 // couldn't find appropriate closing tag, skip
1012 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1013 $start += strlen( $matches[0][0] );
1015 continue;
1018 // else: add as text extract
1019 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1020 break;
1023 $all = $textExt + $otherExt; // these have disjunct key sets
1025 wfProfileOut( "$fname-split" );
1027 // prepare regexps
1028 foreach ( $terms as $index => $term ) {
1029 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1030 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1031 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1032 } else {
1033 $terms[$index] = $term;
1036 $anyterm = implode( '|', $terms );
1037 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1039 // @todo FIXME: A hack to scale contextchars, a correct solution
1040 // would be to have contextchars actually be char and not byte
1041 // length, and do proper utf-8 substrings and lengths everywhere,
1042 // but PHP is making that very hard and unclean to implement :(
1043 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1044 $contextchars = intval( $contextchars * $scale );
1046 $patPre = "(^|$wgSearchHighlightBoundaries)";
1047 $patPost = "($wgSearchHighlightBoundaries|$)";
1049 $pat1 = "/(" . $phrase . ")/ui";
1050 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1052 wfProfileIn( "$fname-extract" );
1054 $left = $contextlines;
1056 $snippets = array();
1057 $offsets = array();
1059 // show beginning only if it contains all words
1060 $first = 0;
1061 $firstText = '';
1062 foreach ( $textExt as $index => $line ) {
1063 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1064 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1065 $first = $index;
1066 break;
1069 if ( $firstText ) {
1070 $succ = true;
1071 // check if first text contains all terms
1072 foreach ( $terms as $term ) {
1073 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1074 $succ = false;
1075 break;
1078 if ( $succ ) {
1079 $snippets[$first] = $firstText;
1080 $offsets[$first] = 0;
1083 if ( ! $snippets ) {
1084 // match whole query on text
1085 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1086 // match whole query on templates/tables/images
1087 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1088 // match any words on text
1089 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1090 // match any words on templates/tables/images
1091 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1093 ksort( $snippets );
1096 // add extra chars to each snippet to make snippets constant size
1097 $extended = array();
1098 if ( count( $snippets ) == 0 ) {
1099 // couldn't find the target words, just show beginning of article
1100 if ( array_key_exists( $first, $all ) ) {
1101 $targetchars = $contextchars * $contextlines;
1102 $snippets[$first] = '';
1103 $offsets[$first] = 0;
1105 } else {
1106 // if begin of the article contains the whole phrase, show only that !!
1107 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1108 && $offsets[$first] < $contextchars * 2 ) {
1109 $snippets = array ( $first => $snippets[$first] );
1112 // calc by how much to extend existing snippets
1113 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1116 foreach ( $snippets as $index => $line ) {
1117 $extended[$index] = $line;
1118 $len = strlen( $line );
1119 if ( $len < $targetchars - 20 ) {
1120 // complete this line
1121 if ( $len < strlen( $all[$index] ) ) {
1122 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] + $targetchars, $offsets[$index] );
1123 $len = strlen( $extended[$index] );
1126 // add more lines
1127 $add = $index + 1;
1128 while ( $len < $targetchars - 20
1129 && array_key_exists( $add, $all )
1130 && !array_key_exists( $add, $snippets ) ) {
1131 $offsets[$add] = 0;
1132 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1133 $extended[$add] = $tt;
1134 $len += strlen( $tt );
1135 $add++;
1140 // $snippets = array_map('htmlspecialchars', $extended);
1141 $snippets = $extended;
1142 $last = - 1;
1143 $extract = '';
1144 foreach ( $snippets as $index => $line ) {
1145 if ( $last == - 1 )
1146 $extract .= $line; // first line
1147 elseif ( $last + 1 == $index && $offsets[$last] + strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1148 $extract .= " " . $line; // continous lines
1149 else
1150 $extract .= '<b> ... </b>' . $line;
1152 $last = $index;
1154 if ( $extract )
1155 $extract .= '<b> ... </b>';
1157 $processed = array();
1158 foreach ( $terms as $term ) {
1159 if ( ! isset( $processed[$term] ) ) {
1160 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1161 $extract = preg_replace( $pat3,
1162 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1163 $processed[$term] = true;
1167 wfProfileOut( "$fname-extract" );
1169 return $extract;
1173 * Split text into lines and add it to extracts array
1175 * @param $extracts Array: index -> $line
1176 * @param $count Integer
1177 * @param $text String
1179 function splitAndAdd( &$extracts, &$count, $text ) {
1180 $split = explode( "\n", $this->mCleanWikitext ? $this->removeWiki( $text ) : $text );
1181 foreach ( $split as $line ) {
1182 $tt = trim( $line );
1183 if ( $tt )
1184 $extracts[$count++] = $tt;
1189 * Do manual case conversion for non-ascii chars
1191 * @param $matches Array
1192 * @return string
1194 function caseCallback( $matches ) {
1195 global $wgContLang;
1196 if ( strlen( $matches[0] ) > 1 ) {
1197 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1198 } else {
1199 return $matches[0];
1204 * Extract part of the text from start to end, but by
1205 * not chopping up words
1206 * @param $text String
1207 * @param $start Integer
1208 * @param $end Integer
1209 * @param $posStart Integer: (out) actual start position
1210 * @param $posEnd Integer: (out) actual end position
1211 * @return String
1213 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1214 if ( $start != 0 ) {
1215 $start = $this->position( $text, $start, 1 );
1217 if ( $end >= strlen( $text ) ) {
1218 $end = strlen( $text );
1219 } else {
1220 $end = $this->position( $text, $end );
1223 if ( !is_null( $posStart ) ) {
1224 $posStart = $start;
1226 if ( !is_null( $posEnd ) ) {
1227 $posEnd = $end;
1230 if ( $end > $start ) {
1231 return substr( $text, $start, $end - $start );
1232 } else {
1233 return '';
1238 * Find a nonletter near a point (index) in the text
1240 * @param $text String
1241 * @param $point Integer
1242 * @param $offset Integer: offset to found index
1243 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1245 function position( $text, $point, $offset = 0 ) {
1246 $tolerance = 10;
1247 $s = max( 0, $point - $tolerance );
1248 $l = min( strlen( $text ), $point + $tolerance ) - $s;
1249 $m = array();
1250 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE ) ) {
1251 return $m[0][1] + $s + $offset;
1252 } else {
1253 // check if point is on a valid first UTF8 char
1254 $char = ord( $text[$point] );
1255 while ( $char >= 0x80 && $char < 0xc0 ) {
1256 // skip trailing bytes
1257 $point++;
1258 if ( $point >= strlen( $text ) )
1259 return strlen( $text );
1260 $char = ord( $text[$point] );
1262 return $point;
1268 * Search extracts for a pattern, and return snippets
1270 * @param $pattern String: regexp for matching lines
1271 * @param $extracts Array: extracts to search
1272 * @param $linesleft Integer: number of extracts to make
1273 * @param $contextchars Integer: length of snippet
1274 * @param $out Array: map for highlighted snippets
1275 * @param $offsets Array: map of starting points of snippets
1276 * @protected
1278 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1279 if ( $linesleft == 0 )
1280 return; // nothing to do
1281 foreach ( $extracts as $index => $line ) {
1282 if ( array_key_exists( $index, $out ) )
1283 continue; // this line already highlighted
1285 $m = array();
1286 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) )
1287 continue;
1289 $offset = $m[0][1];
1290 $len = strlen( $m[0][0] );
1291 if ( $offset + $len < $contextchars )
1292 $begin = 0;
1293 elseif ( $len > $contextchars )
1294 $begin = $offset;
1295 else
1296 $begin = $offset + intval( ( $len - $contextchars ) / 2 );
1298 $end = $begin + $contextchars;
1300 $posBegin = $begin;
1301 // basic snippet from this line
1302 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1303 $offsets[$index] = $posBegin;
1304 $linesleft--;
1305 if ( $linesleft == 0 )
1306 return;
1311 * Basic wikitext removal
1312 * @protected
1313 * @return mixed
1315 function removeWiki( $text ) {
1316 $fname = __METHOD__;
1317 wfProfileIn( $fname );
1319 // $text = preg_replace("/'{2,5}/", "", $text);
1320 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1321 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1322 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1323 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1324 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1325 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1326 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1327 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1328 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1329 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1330 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1331 $text = preg_replace( "/'''''/", "", $text );
1332 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1333 $text = preg_replace( "/''/", "", $text );
1335 wfProfileOut( $fname );
1336 return $text;
1340 * callback to replace [[target|caption]] kind of links, if
1341 * the target is category or image, leave it
1343 * @param $matches Array
1345 function linkReplace( $matches ) {
1346 $colon = strpos( $matches[1], ':' );
1347 if ( $colon === false )
1348 return $matches[2]; // replace with caption
1349 global $wgContLang;
1350 $ns = substr( $matches[1], 0, $colon );
1351 $index = $wgContLang->getNsIndex( $ns );
1352 if ( $index !== false && ( $index == NS_FILE || $index == NS_CATEGORY ) )
1353 return $matches[0]; // return the whole thing
1354 else
1355 return $matches[2];
1360 * Simple & fast snippet extraction, but gives completely unrelevant
1361 * snippets
1363 * @param $text String
1364 * @param $terms Array
1365 * @param $contextlines Integer
1366 * @param $contextchars Integer
1367 * @return String
1369 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1370 global $wgContLang;
1371 $fname = __METHOD__;
1373 $lines = explode( "\n", $text );
1375 $terms = implode( '|', $terms );
1376 $max = intval( $contextchars ) + 1;
1377 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1379 $lineno = 0;
1381 $extract = "";
1382 wfProfileIn( "$fname-extract" );
1383 foreach ( $lines as $line ) {
1384 if ( 0 == $contextlines ) {
1385 break;
1387 ++$lineno;
1388 $m = array();
1389 if ( ! preg_match( $pat1, $line, $m ) ) {
1390 continue;
1392 --$contextlines;
1393 // truncate function changes ... to relevant i18n message.
1394 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1396 if ( count( $m ) < 3 ) {
1397 $post = '';
1398 } else {
1399 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1402 $found = $m[2];
1404 $line = htmlspecialchars( $pre . $found . $post );
1405 $pat2 = '/(' . $terms . ")/i";
1406 $line = preg_replace( $pat2,
1407 "<span class='searchmatch'>\\1</span>", $line );
1409 $extract .= "${line}\n";
1411 wfProfileOut( "$fname-extract" );
1413 return $extract;
1419 * Dummy class to be used when non-supported Database engine is present.
1420 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1421 * such as a LIKE search through titles.
1422 * @ingroup Search
1424 class SearchEngineDummy extends SearchEngine {
1425 // no-op