Simplify the check to make it more understandable
[mediawiki.git] / includes / search / SearchEngine.php
blobb3f5da90999eb92e71ce9f33f8c2b5dd034a24a3
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' );
69 function acceptListRedirects() {
70 wfDeprecated( __METHOD__, '1.18' );
71 return $this->supports( 'list-redirects' );
74 /**
75 * @since 1.18
76 * @param $feature String
77 * @return Boolean
79 public function supports( $feature ) {
80 switch( $feature ) {
81 case 'list-redirects':
82 return true;
83 case 'title-suffix-filter':
84 default:
85 return false;
89 /**
90 * Way to pass custom data for engines
91 * @since 1.18
92 * @param $feature String
93 * @param $data Mixed
94 * @return Noolean
96 public function setFeatureData( $feature, $data ) {
97 $this->features[$feature] = $data;
101 * When overridden in derived class, performs database-specific conversions
102 * on text to be used for searching or updating search index.
103 * Default implementation does nothing (simply returns $string).
105 * @param $string string: String to process
106 * @return string
108 public function normalizeText( $string ) {
109 global $wgContLang;
111 // Some languages such as Chinese require word segmentation
112 return $wgContLang->segmentByWord( $string );
116 * Transform search term in cases when parts of the query came as different GET params (when supported)
117 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
119 function transformSearchTerm( $term ) {
120 return $term;
124 * If an exact title match can be found, or a very slightly close match,
125 * return the title. If no match, returns NULL.
127 * @param $searchterm String
128 * @return Title
130 public static function getNearMatch( $searchterm ) {
131 $title = self::getNearMatchInternal( $searchterm );
133 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
134 return $title;
138 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
139 * SearchResultSet.
141 * @param $searchterm string
142 * @return SearchResultSet
144 public static function getNearMatchResultSet( $searchterm ) {
145 return new SearchNearMatchResultSet( self::getNearMatch( $searchterm ) );
149 * Really find the title match.
151 private static function getNearMatchInternal( $searchterm ) {
152 global $wgContLang, $wgEnableSearchContributorsByIP;
154 $allSearchTerms = array( $searchterm );
156 if ( $wgContLang->hasVariants() ) {
157 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
160 $titleResult = null;
161 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
162 return $titleResult;
165 foreach ( $allSearchTerms as $term ) {
167 # Exact match? No need to look further.
168 $title = Title::newFromText( $term );
169 if ( is_null( $title ) ){
170 return null;
173 if ( $title->isSpecialPage() || $title->isExternal() || $title->exists() ) {
174 return $title;
177 # See if it still otherwise has content is some sane sense
178 $page = WikiPage::factory( $title );
179 if ( $page->hasViewableContent() ) {
180 return $title;
183 # Now try all lower case (i.e. first letter capitalized)
185 $title = Title::newFromText( $wgContLang->lc( $term ) );
186 if ( $title && $title->exists() ) {
187 return $title;
190 # Now try capitalized string
192 $title = Title::newFromText( $wgContLang->ucwords( $term ) );
193 if ( $title && $title->exists() ) {
194 return $title;
197 # Now try all upper case
199 $title = Title::newFromText( $wgContLang->uc( $term ) );
200 if ( $title && $title->exists() ) {
201 return $title;
204 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
205 $title = Title::newFromText( $wgContLang->ucwordbreaks( $term ) );
206 if ( $title && $title->exists() ) {
207 return $title;
210 // Give hooks a chance at better match variants
211 $title = null;
212 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
213 return $title;
217 $title = Title::newFromText( $searchterm );
220 # Entering an IP address goes to the contributions page
221 if ( $wgEnableSearchContributorsByIP ) {
222 if ( ( $title->getNamespace() == NS_USER && User::isIP( $title->getText() ) )
223 || User::isIP( trim( $searchterm ) ) ) {
224 return SpecialPage::getTitleFor( 'Contributions', $title->getDBkey() );
229 # Entering a user goes to the user page whether it's there or not
230 if ( $title->getNamespace() == NS_USER ) {
231 return $title;
234 # Go to images that exist even if there's no local page.
235 # There may have been a funny upload, or it may be on a shared
236 # file repository such as Wikimedia Commons.
237 if ( $title->getNamespace() == NS_FILE ) {
238 $image = wfFindFile( $title );
239 if ( $image ) {
240 return $title;
244 # MediaWiki namespace? Page may be "implied" if not customized.
245 # Just return it, with caps forced as the message system likes it.
246 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
247 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( $title->getText() ) );
250 # Quoted term? Try without the quotes...
251 $matches = array();
252 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
253 return SearchEngine::getNearMatch( $matches[1] );
256 return null;
259 public static function legalSearchChars() {
260 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
264 * Set the maximum number of results to return
265 * and how many to skip before returning the first.
267 * @param $limit Integer
268 * @param $offset Integer
270 function setLimitOffset( $limit, $offset = 0 ) {
271 $this->limit = intval( $limit );
272 $this->offset = intval( $offset );
276 * Set which namespaces the search should include.
277 * Give an array of namespace index numbers.
279 * @param $namespaces Array
281 function setNamespaces( $namespaces ) {
282 $this->namespaces = $namespaces;
286 * Parse some common prefixes: all (search everything)
287 * or namespace names
289 * @param $query String
291 function replacePrefixes( $query ) {
292 global $wgContLang;
294 $parsed = $query;
295 if ( strpos( $query, ':' ) === false ) { // nothing to do
296 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
297 return $parsed;
300 $allkeyword = wfMsgForContent( 'searchall' ) . ":";
301 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
302 $this->namespaces = null;
303 $parsed = substr( $query, strlen( $allkeyword ) );
304 } elseif ( strpos( $query, ':' ) !== false ) {
305 $prefix = substr( $query, 0, strpos( $query, ':' ) );
306 $index = $wgContLang->getNsIndex( $prefix );
307 if ( $index !== false ) {
308 $this->namespaces = array( $index );
309 $parsed = substr( $query, strlen( $prefix ) + 1 );
312 if ( trim( $parsed ) == '' )
313 $parsed = $query; // prefix was the whole query
315 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
317 return $parsed;
321 * Make a list of searchable namespaces and their canonical names.
322 * @return Array
324 public static function searchableNamespaces() {
325 global $wgContLang;
326 $arr = array();
327 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
328 if ( $ns >= NS_MAIN ) {
329 $arr[$ns] = $name;
333 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
334 return $arr;
338 * Extract default namespaces to search from the given user's
339 * settings, returning a list of index numbers.
341 * @param $user User
342 * @return Array
344 public static function userNamespaces( $user ) {
345 global $wgSearchEverythingOnlyLoggedIn;
347 // get search everything preference, that can be set to be read for logged-in users
348 $searcheverything = false;
349 if ( ( $wgSearchEverythingOnlyLoggedIn && $user->isLoggedIn() )
350 || !$wgSearchEverythingOnlyLoggedIn )
351 $searcheverything = $user->getOption( 'searcheverything' );
353 // searcheverything overrides other options
354 if ( $searcheverything )
355 return array_keys( SearchEngine::searchableNamespaces() );
357 $arr = Preferences::loadOldSearchNs( $user );
358 $searchableNamespaces = SearchEngine::searchableNamespaces();
360 $arr = array_intersect( $arr, array_keys( $searchableNamespaces ) ); // Filter
362 return $arr;
366 * Find snippet highlight settings for all users
368 * @return Array contextlines, contextchars
370 public static function userHighlightPrefs() {
371 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
372 $contextchars = 75; // same as above.... :P
373 return array( $contextlines, $contextchars );
377 * An array of namespaces indexes to be searched by default
379 * @return Array
381 public static function defaultNamespaces() {
382 global $wgNamespacesToBeSearchedDefault;
384 return array_keys( $wgNamespacesToBeSearchedDefault, true );
388 * Get a list of namespace names useful for showing in tooltips
389 * and preferences
391 * @param $namespaces Array
393 public static function namespacesAsText( $namespaces ) {
394 global $wgContLang;
396 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
397 foreach ( $formatted as $key => $ns ) {
398 if ( empty( $ns ) )
399 $formatted[$key] = wfMsg( 'blanknamespace' );
401 return $formatted;
405 * Return the help namespaces to be shown on Special:Search
407 * @return Array
409 public static function helpNamespaces() {
410 global $wgNamespacesToBeSearchedHelp;
412 return array_keys( $wgNamespacesToBeSearchedHelp, true );
416 * Return a 'cleaned up' search string
418 * @param $text String
419 * @return String
421 function filter( $text ) {
422 $lc = $this->legalSearchChars();
423 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
426 * Load up the appropriate search engine class for the currently
427 * active database backend, and return a configured instance.
429 * @return SearchEngine
431 public static function create() {
432 global $wgSearchType;
433 $dbr = null;
434 if ( $wgSearchType ) {
435 $class = $wgSearchType;
436 } else {
437 $dbr = wfGetDB( DB_SLAVE );
438 $class = $dbr->getSearchEngine();
440 $search = new $class( $dbr );
441 $search->setLimitOffset( 0, 0 );
442 return $search;
446 * Create or update the search index record for the given page.
447 * Title and text should be pre-processed.
448 * STUB
450 * @param $id Integer
451 * @param $title String
452 * @param $text String
454 function update( $id, $title, $text ) {
455 // no-op
459 * Update a search index record's title only.
460 * Title should be pre-processed.
461 * STUB
463 * @param $id Integer
464 * @param $title String
466 function updateTitle( $id, $title ) {
467 // no-op
471 * Get OpenSearch suggestion template
473 * @return String
475 public static function getOpenSearchTemplate() {
476 global $wgOpenSearchTemplate, $wgCanonicalServer;
477 if ( $wgOpenSearchTemplate ) {
478 return $wgOpenSearchTemplate;
479 } else {
480 $ns = implode( '|', SearchEngine::defaultNamespaces() );
481 if ( !$ns ) {
482 $ns = "0";
484 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
489 * Get internal MediaWiki Suggest template
491 * @return String
493 public static function getMWSuggestTemplate() {
494 global $wgMWSuggestTemplate, $wgServer;
495 if ( $wgMWSuggestTemplate )
496 return $wgMWSuggestTemplate;
497 else
498 return $wgServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
503 * @ingroup Search
505 class SearchResultSet {
507 * Fetch an array of regular expression fragments for matching
508 * the search terms as parsed by this engine in a text extract.
509 * STUB
511 * @return Array
513 function termMatches() {
514 return array();
517 function numRows() {
518 return 0;
522 * Return true if results are included in this result set.
523 * STUB
525 * @return Boolean
527 function hasResults() {
528 return false;
532 * Some search modes return a total hit count for the query
533 * in the entire article database. This may include pages
534 * in namespaces that would not be matched on the given
535 * settings.
537 * Return null if no total hits number is supported.
539 * @return Integer
541 function getTotalHits() {
542 return null;
546 * Some search modes return a suggested alternate term if there are
547 * no exact hits. Returns true if there is one on this set.
549 * @return Boolean
551 function hasSuggestion() {
552 return false;
556 * @return String: suggested query, null if none
558 function getSuggestionQuery() {
559 return null;
563 * @return String: HTML highlighted suggested query, '' if none
565 function getSuggestionSnippet() {
566 return '';
570 * Return information about how and from where the results were fetched,
571 * should be useful for diagnostics and debugging
573 * @return String
575 function getInfo() {
576 return null;
580 * Return a result set of hits on other (multiple) wikis associated with this one
582 * @return SearchResultSet
584 function getInterwikiResults() {
585 return null;
589 * Check if there are results on other wikis
591 * @return Boolean
593 function hasInterwikiResults() {
594 return $this->getInterwikiResults() != null;
598 * Fetches next search result, or false.
599 * STUB
601 * @return SearchResult
603 function next() {
604 return false;
608 * Frees the result set, if applicable.
610 function free() {
611 // ...
616 * This class is used for different SQL-based search engines shipped with MediaWiki
618 class SqlSearchResultSet extends SearchResultSet {
620 protected $mResultSet;
622 function __construct( $resultSet, $terms ) {
623 $this->mResultSet = $resultSet;
624 $this->mTerms = $terms;
627 function termMatches() {
628 return $this->mTerms;
631 function numRows() {
632 if ( $this->mResultSet === false )
633 return false;
635 return $this->mResultSet->numRows();
638 function next() {
639 if ( $this->mResultSet === false )
640 return false;
642 $row = $this->mResultSet->fetchObject();
643 if ( $row === false )
644 return false;
646 return SearchResult::newFromRow( $row );
649 function free() {
650 if ( $this->mResultSet === false )
651 return false;
653 $this->mResultSet->free();
658 * @ingroup Search
660 class SearchResultTooMany {
661 # # Some search engines may bail out if too many matches are found
666 * @todo FIXME: This class is horribly factored. It would probably be better to
667 * have a useful base class to which you pass some standard information, then
668 * let the fancy self-highlighters extend that.
669 * @ingroup Search
671 class SearchResult {
674 * @var Revision
676 var $mRevision = null;
677 var $mImage = null;
680 * @var Title
682 var $mTitle;
685 * @var String
687 var $mText;
690 * Return a new SearchResult and initializes it with a title.
692 * @param $title Title
693 * @return SearchResult
695 public static function newFromTitle( $title ) {
696 $result = new self();
697 $result->initFromTitle( $title );
698 return $result;
701 * Return a new SearchResult and initializes it with a row.
703 * @param $row object
704 * @return SearchResult
706 public static function newFromRow( $row ) {
707 $result = new self();
708 $result->initFromRow( $row );
709 return $result;
712 public function __construct( $row = null ) {
713 if ( !is_null( $row ) ) {
714 // Backwards compatibility with pre-1.17 callers
715 $this->initFromRow( $row );
720 * Initialize from a database row. Makes a Title and passes that to
721 * initFromTitle.
723 * @param $row object
725 protected function initFromRow( $row ) {
726 $this->initFromTitle( Title::makeTitle( $row->page_namespace, $row->page_title ) );
730 * Initialize from a Title and if possible initializes a corresponding
731 * Revision and File.
733 * @param $title Title
735 protected function initFromTitle( $title ) {
736 $this->mTitle = $title;
737 if ( !is_null( $this->mTitle ) ) {
738 $this->mRevision = Revision::newFromTitle( $this->mTitle );
739 if ( $this->mTitle->getNamespace() === NS_FILE )
740 $this->mImage = wfFindFile( $this->mTitle );
745 * Check if this is result points to an invalid title
747 * @return Boolean
749 function isBrokenTitle() {
750 if ( is_null( $this->mTitle ) )
751 return true;
752 return false;
756 * Check if target page is missing, happens when index is out of date
758 * @return Boolean
760 function isMissingRevision() {
761 return !$this->mRevision && !$this->mImage;
765 * @return Title
767 function getTitle() {
768 return $this->mTitle;
772 * @return Double or null if not supported
774 function getScore() {
775 return null;
779 * Lazy initialization of article text from DB
781 protected function initText() {
782 if ( !isset( $this->mText ) ) {
783 if ( $this->mRevision != null )
784 $this->mText = $this->mRevision->getText();
785 else // TODO: can we fetch raw wikitext for commons images?
786 $this->mText = '';
792 * @param $terms Array: terms to highlight
793 * @return String: highlighted text snippet, null (and not '') if not supported
795 function getTextSnippet( $terms ) {
796 global $wgUser, $wgAdvancedSearchHighlighting;
797 $this->initText();
798 list( $contextlines, $contextchars ) = SearchEngine::userHighlightPrefs( $wgUser );
799 $h = new SearchHighlighter();
800 if ( $wgAdvancedSearchHighlighting )
801 return $h->highlightText( $this->mText, $terms, $contextlines, $contextchars );
802 else
803 return $h->highlightSimple( $this->mText, $terms, $contextlines, $contextchars );
807 * @param $terms Array: terms to highlight
808 * @return String: highlighted title, '' if not supported
810 function getTitleSnippet( $terms ) {
811 return '';
815 * @param $terms Array: terms to highlight
816 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
818 function getRedirectSnippet( $terms ) {
819 return '';
823 * @return Title object for the redirect to this page, null if none or not supported
825 function getRedirectTitle() {
826 return null;
830 * @return string highlighted relevant section name, null if none or not supported
832 function getSectionSnippet() {
833 return '';
837 * @return Title object (pagename+fragment) for the section, null if none or not supported
839 function getSectionTitle() {
840 return null;
844 * @return String: timestamp
846 function getTimestamp() {
847 if ( $this->mRevision )
848 return $this->mRevision->getTimestamp();
849 elseif ( $this->mImage )
850 return $this->mImage->getTimestamp();
851 return '';
855 * @return Integer: number of words
857 function getWordCount() {
858 $this->initText();
859 return str_word_count( $this->mText );
863 * @return Integer: size in bytes
865 function getByteSize() {
866 $this->initText();
867 return strlen( $this->mText );
871 * @return Boolean if hit has related articles
873 function hasRelated() {
874 return false;
878 * @return String: interwiki prefix of the title (return iw even if title is broken)
880 function getInterwikiPrefix() {
881 return '';
885 * A SearchResultSet wrapper for SearchEngine::getNearMatch
887 class SearchNearMatchResultSet extends SearchResultSet {
888 private $fetched = false;
890 * @param $match mixed Title if matched, else null
892 public function __construct( $match ) {
893 $this->result = $match;
895 public function hasResult() {
896 return (bool)$this->result;
898 public function numRows() {
899 return $this->hasResults() ? 1 : 0;
901 public function next() {
902 if ( $this->fetched || !$this->result ) {
903 return false;
905 $this->fetched = true;
906 return SearchResult::newFromTitle( $this->result );
911 * Highlight bits of wikitext
913 * @ingroup Search
915 class SearchHighlighter {
916 var $mCleanWikitext = true;
918 function __construct( $cleanupWikitext = true ) {
919 $this->mCleanWikitext = $cleanupWikitext;
923 * Default implementation of wikitext highlighting
925 * @param $text String
926 * @param $terms Array: terms to highlight (unescaped)
927 * @param $contextlines Integer
928 * @param $contextchars Integer
929 * @return String
931 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
932 global $wgContLang;
933 global $wgSearchHighlightBoundaries;
934 $fname = __METHOD__;
936 if ( $text == '' )
937 return '';
939 // spli text into text + templates/links/tables
940 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
941 // first capture group is for detecting nested templates/links/tables/references
942 $endPatterns = array(
943 1 => '/(\{\{)|(\}\})/', // template
944 2 => '/(\[\[)|(\]\])/', // image
945 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
947 // @todo FIXME: This should prolly be a hook or something
948 if ( function_exists( 'wfCite' ) ) {
949 $spat .= '|(<ref>)'; // references via cite extension
950 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
952 $spat .= '/';
953 $textExt = array(); // text extracts
954 $otherExt = array(); // other extracts
955 wfProfileIn( "$fname-split" );
956 $start = 0;
957 $textLen = strlen( $text );
958 $count = 0; // sequence number to maintain ordering
959 while ( $start < $textLen ) {
960 // find start of template/image/table
961 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE, $start ) ) {
962 $epat = '';
963 foreach ( $matches as $key => $val ) {
964 if ( $key > 0 && $val[1] != - 1 ) {
965 if ( $key == 2 ) {
966 // see if this is an image link
967 $ns = substr( $val[0], 2, - 1 );
968 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE )
969 break;
972 $epat = $endPatterns[$key];
973 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
974 $start = $val[1];
975 break;
978 if ( $epat ) {
979 // find end (and detect any nested elements)
980 $level = 0;
981 $offset = $start + 1;
982 $found = false;
983 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE, $offset ) ) {
984 if ( array_key_exists( 2, $endMatches ) ) {
985 // found end
986 if ( $level == 0 ) {
987 $len = strlen( $endMatches[2][0] );
988 $off = $endMatches[2][1];
989 $this->splitAndAdd( $otherExt, $count,
990 substr( $text, $start, $off + $len - $start ) );
991 $start = $off + $len;
992 $found = true;
993 break;
994 } else {
995 // end of nested element
996 $level -= 1;
998 } else {
999 // nested
1000 $level += 1;
1002 $offset = $endMatches[0][1] + strlen( $endMatches[0][0] );
1004 if ( ! $found ) {
1005 // couldn't find appropriate closing tag, skip
1006 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1007 $start += strlen( $matches[0][0] );
1009 continue;
1012 // else: add as text extract
1013 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1014 break;
1017 $all = $textExt + $otherExt; // these have disjunct key sets
1019 wfProfileOut( "$fname-split" );
1021 // prepare regexps
1022 foreach ( $terms as $index => $term ) {
1023 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1024 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1025 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1026 } else {
1027 $terms[$index] = $term;
1030 $anyterm = implode( '|', $terms );
1031 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1033 // @todo FIXME: A hack to scale contextchars, a correct solution
1034 // would be to have contextchars actually be char and not byte
1035 // length, and do proper utf-8 substrings and lengths everywhere,
1036 // but PHP is making that very hard and unclean to implement :(
1037 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1038 $contextchars = intval( $contextchars * $scale );
1040 $patPre = "(^|$wgSearchHighlightBoundaries)";
1041 $patPost = "($wgSearchHighlightBoundaries|$)";
1043 $pat1 = "/(" . $phrase . ")/ui";
1044 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1046 wfProfileIn( "$fname-extract" );
1048 $left = $contextlines;
1050 $snippets = array();
1051 $offsets = array();
1053 // show beginning only if it contains all words
1054 $first = 0;
1055 $firstText = '';
1056 foreach ( $textExt as $index => $line ) {
1057 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1058 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1059 $first = $index;
1060 break;
1063 if ( $firstText ) {
1064 $succ = true;
1065 // check if first text contains all terms
1066 foreach ( $terms as $term ) {
1067 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1068 $succ = false;
1069 break;
1072 if ( $succ ) {
1073 $snippets[$first] = $firstText;
1074 $offsets[$first] = 0;
1077 if ( ! $snippets ) {
1078 // match whole query on text
1079 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1080 // match whole query on templates/tables/images
1081 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1082 // match any words on text
1083 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1084 // match any words on templates/tables/images
1085 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1087 ksort( $snippets );
1090 // add extra chars to each snippet to make snippets constant size
1091 $extended = array();
1092 if ( count( $snippets ) == 0 ) {
1093 // couldn't find the target words, just show beginning of article
1094 if ( array_key_exists( $first, $all ) ) {
1095 $targetchars = $contextchars * $contextlines;
1096 $snippets[$first] = '';
1097 $offsets[$first] = 0;
1099 } else {
1100 // if begin of the article contains the whole phrase, show only that !!
1101 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1102 && $offsets[$first] < $contextchars * 2 ) {
1103 $snippets = array ( $first => $snippets[$first] );
1106 // calc by how much to extend existing snippets
1107 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1110 foreach ( $snippets as $index => $line ) {
1111 $extended[$index] = $line;
1112 $len = strlen( $line );
1113 if ( $len < $targetchars - 20 ) {
1114 // complete this line
1115 if ( $len < strlen( $all[$index] ) ) {
1116 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] + $targetchars, $offsets[$index] );
1117 $len = strlen( $extended[$index] );
1120 // add more lines
1121 $add = $index + 1;
1122 while ( $len < $targetchars - 20
1123 && array_key_exists( $add, $all )
1124 && !array_key_exists( $add, $snippets ) ) {
1125 $offsets[$add] = 0;
1126 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1127 $extended[$add] = $tt;
1128 $len += strlen( $tt );
1129 $add++;
1134 // $snippets = array_map('htmlspecialchars', $extended);
1135 $snippets = $extended;
1136 $last = - 1;
1137 $extract = '';
1138 foreach ( $snippets as $index => $line ) {
1139 if ( $last == - 1 )
1140 $extract .= $line; // first line
1141 elseif ( $last + 1 == $index && $offsets[$last] + strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1142 $extract .= " " . $line; // continous lines
1143 else
1144 $extract .= '<b> ... </b>' . $line;
1146 $last = $index;
1148 if ( $extract )
1149 $extract .= '<b> ... </b>';
1151 $processed = array();
1152 foreach ( $terms as $term ) {
1153 if ( ! isset( $processed[$term] ) ) {
1154 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1155 $extract = preg_replace( $pat3,
1156 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1157 $processed[$term] = true;
1161 wfProfileOut( "$fname-extract" );
1163 return $extract;
1167 * Split text into lines and add it to extracts array
1169 * @param $extracts Array: index -> $line
1170 * @param $count Integer
1171 * @param $text String
1173 function splitAndAdd( &$extracts, &$count, $text ) {
1174 $split = explode( "\n", $this->mCleanWikitext ? $this->removeWiki( $text ) : $text );
1175 foreach ( $split as $line ) {
1176 $tt = trim( $line );
1177 if ( $tt )
1178 $extracts[$count++] = $tt;
1183 * Do manual case conversion for non-ascii chars
1185 * @param $matches Array
1187 function caseCallback( $matches ) {
1188 global $wgContLang;
1189 if ( strlen( $matches[0] ) > 1 ) {
1190 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1191 } else {
1192 return $matches[0];
1197 * Extract part of the text from start to end, but by
1198 * not chopping up words
1199 * @param $text String
1200 * @param $start Integer
1201 * @param $end Integer
1202 * @param $posStart Integer: (out) actual start position
1203 * @param $posEnd Integer: (out) actual end position
1204 * @return String
1206 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1207 if ( $start != 0 ) {
1208 $start = $this->position( $text, $start, 1 );
1210 if ( $end >= strlen( $text ) ) {
1211 $end = strlen( $text );
1212 } else {
1213 $end = $this->position( $text, $end );
1216 if ( !is_null( $posStart ) ) {
1217 $posStart = $start;
1219 if ( !is_null( $posEnd ) ) {
1220 $posEnd = $end;
1223 if ( $end > $start ) {
1224 return substr( $text, $start, $end - $start );
1225 } else {
1226 return '';
1231 * Find a nonletter near a point (index) in the text
1233 * @param $text String
1234 * @param $point Integer
1235 * @param $offset Integer: offset to found index
1236 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1238 function position( $text, $point, $offset = 0 ) {
1239 $tolerance = 10;
1240 $s = max( 0, $point - $tolerance );
1241 $l = min( strlen( $text ), $point + $tolerance ) - $s;
1242 $m = array();
1243 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE ) ) {
1244 return $m[0][1] + $s + $offset;
1245 } else {
1246 // check if point is on a valid first UTF8 char
1247 $char = ord( $text[$point] );
1248 while ( $char >= 0x80 && $char < 0xc0 ) {
1249 // skip trailing bytes
1250 $point++;
1251 if ( $point >= strlen( $text ) )
1252 return strlen( $text );
1253 $char = ord( $text[$point] );
1255 return $point;
1261 * Search extracts for a pattern, and return snippets
1263 * @param $pattern String: regexp for matching lines
1264 * @param $extracts Array: extracts to search
1265 * @param $linesleft Integer: number of extracts to make
1266 * @param $contextchars Integer: length of snippet
1267 * @param $out Array: map for highlighted snippets
1268 * @param $offsets Array: map of starting points of snippets
1269 * @protected
1271 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1272 if ( $linesleft == 0 )
1273 return; // nothing to do
1274 foreach ( $extracts as $index => $line ) {
1275 if ( array_key_exists( $index, $out ) )
1276 continue; // this line already highlighted
1278 $m = array();
1279 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) )
1280 continue;
1282 $offset = $m[0][1];
1283 $len = strlen( $m[0][0] );
1284 if ( $offset + $len < $contextchars )
1285 $begin = 0;
1286 elseif ( $len > $contextchars )
1287 $begin = $offset;
1288 else
1289 $begin = $offset + intval( ( $len - $contextchars ) / 2 );
1291 $end = $begin + $contextchars;
1293 $posBegin = $begin;
1294 // basic snippet from this line
1295 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1296 $offsets[$index] = $posBegin;
1297 $linesleft--;
1298 if ( $linesleft == 0 )
1299 return;
1304 * Basic wikitext removal
1305 * @protected
1307 function removeWiki( $text ) {
1308 $fname = __METHOD__;
1309 wfProfileIn( $fname );
1311 // $text = preg_replace("/'{2,5}/", "", $text);
1312 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1313 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1314 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1315 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1316 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1317 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1318 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1319 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1320 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1321 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1322 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1323 $text = preg_replace( "/'''''/", "", $text );
1324 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1325 $text = preg_replace( "/''/", "", $text );
1327 wfProfileOut( $fname );
1328 return $text;
1332 * callback to replace [[target|caption]] kind of links, if
1333 * the target is category or image, leave it
1335 * @param $matches Array
1337 function linkReplace( $matches ) {
1338 $colon = strpos( $matches[1], ':' );
1339 if ( $colon === false )
1340 return $matches[2]; // replace with caption
1341 global $wgContLang;
1342 $ns = substr( $matches[1], 0, $colon );
1343 $index = $wgContLang->getNsIndex( $ns );
1344 if ( $index !== false && ( $index == NS_FILE || $index == NS_CATEGORY ) )
1345 return $matches[0]; // return the whole thing
1346 else
1347 return $matches[2];
1352 * Simple & fast snippet extraction, but gives completely unrelevant
1353 * snippets
1355 * @param $text String
1356 * @param $terms Array
1357 * @param $contextlines Integer
1358 * @param $contextchars Integer
1359 * @return String
1361 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1362 global $wgContLang;
1363 $fname = __METHOD__;
1365 $lines = explode( "\n", $text );
1367 $terms = implode( '|', $terms );
1368 $max = intval( $contextchars ) + 1;
1369 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1371 $lineno = 0;
1373 $extract = "";
1374 wfProfileIn( "$fname-extract" );
1375 foreach ( $lines as $line ) {
1376 if ( 0 == $contextlines ) {
1377 break;
1379 ++$lineno;
1380 $m = array();
1381 if ( ! preg_match( $pat1, $line, $m ) ) {
1382 continue;
1384 --$contextlines;
1385 // truncate function changes ... to relevant i18n message.
1386 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1388 if ( count( $m ) < 3 ) {
1389 $post = '';
1390 } else {
1391 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1394 $found = $m[2];
1396 $line = htmlspecialchars( $pre . $found . $post );
1397 $pat2 = '/(' . $terms . ")/i";
1398 $line = preg_replace( $pat2,
1399 "<span class='searchmatch'>\\1</span>", $line );
1401 $extract .= "${line}\n";
1403 wfProfileOut( "$fname-extract" );
1405 return $extract;
1411 * Dummy class to be used when non-supported Database engine is present.
1412 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1413 * such as a LIKE search through titles.
1414 * @ingroup Search
1416 class SearchEngineDummy extends SearchEngine {
1417 // no-op