10 * @defgroup Search Search
14 * Contain a class for special pages
21 var $searchTerms = array();
22 var $namespaces = array( NS_MAIN
);
23 var $showRedirects = false;
26 protected $features = array();
33 function __construct($db = null) {
37 $this->db
= wfGetDB( DB_SLAVE
);
42 * Perform a full text search query and return a result set.
43 * If title searches are not supported or disabled, return null.
46 * @param $term String: raw search term
47 * @return SearchResultSet
49 function searchText( $term ) {
54 * Perform a title-only search query and return a result set.
55 * If title searches are not supported or disabled, return null.
58 * @param $term String: raw search term
59 * @return SearchResultSet
61 function searchTitle( $term ) {
66 * If this search backend can list/unlist redirects
67 * @deprecated since 1.18 Call supports( 'list-redirects' );
70 function acceptListRedirects() {
71 wfDeprecated( __METHOD__
, '1.18' );
72 return $this->supports( 'list-redirects' );
77 * @param $feature String
80 public function supports( $feature ) {
82 case 'list-redirects':
84 case 'title-suffix-filter':
91 * Way to pass custom data for engines
93 * @param $feature String
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
109 public function normalizeText( $string ) {
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 ) {
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
131 public static function getNearMatch( $searchterm ) {
132 $title = self
::getNearMatchInternal( $searchterm );
134 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
139 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
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 ) );
163 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
167 foreach ( $allSearchTerms as $term ) {
169 # Exact match? No need to look further.
170 $title = Title
::newFromText( $term );
171 if ( is_null( $title ) ){
175 if ( $title->isSpecialPage() ||
$title->isExternal() ||
$title->exists() ) {
179 # See if it still otherwise has content is some sane sense
180 $page = WikiPage
::factory( $title );
181 if ( $page->hasViewableContent() ) {
185 # Now try all lower case (i.e. first letter capitalized)
187 $title = Title
::newFromText( $wgContLang->lc( $term ) );
188 if ( $title && $title->exists() ) {
192 # Now try capitalized string
194 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
195 if ( $title && $title->exists() ) {
199 # Now try all upper case
201 $title = Title
::newFromText( $wgContLang->uc( $term ) );
202 if ( $title && $title->exists() ) {
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() ) {
212 // Give hooks a chance at better match variants
214 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$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
) {
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 );
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...
254 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
255 return SearchEngine
::getNearMatch( $matches[1] );
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)
291 * @param $query String
294 function replacePrefixes( $query ) {
298 if ( strpos( $query, ':' ) === false ) { // nothing to do
299 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$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 ) );
324 * Make a list of searchable namespaces and their canonical names.
327 public static function searchableNamespaces() {
330 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
331 if ( $ns >= NS_MAIN
) {
336 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
341 * Extract default namespaces to search from the given user's
342 * settings, returning a list of index numbers.
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 );
361 foreach ( $searchableNamespaces as $ns => $name ) {
362 if ( $user->getOption( 'searchNs' . $ns ) ) {
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
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
396 * @param $namespaces Array
399 public static function namespacesAsText( $namespaces ) {
402 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
403 foreach ( $formatted as $key => $ns ) {
405 $formatted[$key] = wfMsg( 'blanknamespace' );
411 * Return the help namespaces to be shown on Special:Search
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
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;
440 if ( $wgSearchType ) {
441 $class = $wgSearchType;
443 $dbr = wfGetDB( DB_SLAVE
);
444 $class = $dbr->getSearchEngine();
446 $search = new $class( $dbr );
447 $search->setLimitOffset( 0, 0 );
452 * Create or update the search index record for the given page.
453 * Title and text should be pre-processed.
457 * @param $title String
458 * @param $text String
460 function update( $id, $title, $text ) {
465 * Update a search index record's title only.
466 * Title should be pre-processed.
470 * @param $title String
472 function updateTitle( $id, $title ) {
477 * Get OpenSearch suggestion template
481 public static function getOpenSearchTemplate() {
482 global $wgOpenSearchTemplate, $wgCanonicalServer;
483 if ( $wgOpenSearchTemplate ) {
484 return $wgOpenSearchTemplate;
486 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
490 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
495 * Get internal MediaWiki Suggest template
499 public static function getMWSuggestTemplate() {
500 global $wgMWSuggestTemplate, $wgServer;
501 if ( $wgMWSuggestTemplate )
502 return $wgMWSuggestTemplate;
504 return $wgServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
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.
519 function termMatches() {
528 * Return true if results are included in this result set.
533 function hasResults() {
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
543 * Return null if no total hits number is supported.
547 function getTotalHits() {
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.
557 function hasSuggestion() {
562 * @return String: suggested query, null if none
564 function getSuggestionQuery() {
569 * @return String: HTML highlighted suggested query, '' if none
571 function getSuggestionSnippet() {
576 * Return information about how and from where the results were fetched,
577 * should be useful for diagnostics and debugging
586 * Return a result set of hits on other (multiple) wikis associated with this one
588 * @return SearchResultSet
590 function getInterwikiResults() {
595 * Check if there are results on other wikis
599 function hasInterwikiResults() {
600 return $this->getInterwikiResults() != null;
604 * Fetches next search result, or false.
607 * @return SearchResult
614 * Frees the result set, if applicable.
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
;
638 if ( $this->mResultSet
=== false )
641 return $this->mResultSet
->numRows();
645 if ( $this->mResultSet
=== false )
648 $row = $this->mResultSet
->fetchObject();
649 if ( $row === false )
652 return SearchResult
::newFromRow( $row );
656 if ( $this->mResultSet
=== false )
659 $this->mResultSet
->free();
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.
682 var $mRevision = null;
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 );
707 * Return a new SearchResult and initializes it with a row.
710 * @return SearchResult
712 public static function newFromRow( $row ) {
713 $result = new self();
714 $result->initFromRow( $row );
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
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
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
755 function isBrokenTitle() {
756 if ( is_null( $this->mTitle
) )
762 * Check if target page is missing, happens when index is out of date
766 function isMissingRevision() {
767 return !$this->mRevision
&& !$this->mImage
;
773 function getTitle() {
774 return $this->mTitle
;
778 * @return float|null if not supported
780 function getScore() {
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?
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;
804 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
805 $h = new SearchHighlighter();
806 if ( $wgAdvancedSearchHighlighting )
807 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
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 ) {
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 ) {
829 * @return Title object for the redirect to this page, null if none or not supported
831 function getRedirectTitle() {
836 * @return string highlighted relevant section name, null if none or not supported
838 function getSectionSnippet() {
843 * @return Title object (pagename+fragment) for the section, null if none or not supported
845 function getSectionTitle() {
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();
861 * @return Integer: number of words
863 function getWordCount() {
865 return str_word_count( $this->mText
);
869 * @return Integer: size in bytes
871 function getByteSize() {
873 return strlen( $this->mText
);
877 * @return Boolean if hit has related articles
879 function hasRelated() {
884 * @return String: interwiki prefix of the title (return iw even if title is broken)
886 function getInterwikiPrefix() {
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
) {
911 $this->fetched
= true;
912 return SearchResult
::newFromTitle( $this->result
);
917 * Highlight bits of wikitext
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
937 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
939 global $wgSearchHighlightBoundaries;
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>)/';
959 $textExt = array(); // text extracts
960 $otherExt = array(); // other extracts
961 wfProfileIn( "$fname-split" );
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 ) ) {
969 foreach ( $matches as $key => $val ) {
970 if ( $key > 0 && $val[1] != - 1 ) {
972 // see if this is an image link
973 $ns = substr( $val[0], 2, - 1 );
974 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
)
978 $epat = $endPatterns[$key];
979 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
985 // find end (and detect any nested elements)
987 $offset = $start +
1;
989 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
990 if ( array_key_exists( 2, $endMatches ) ) {
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;
1001 // end of nested element
1008 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
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] );
1018 // else: add as text extract
1019 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1023 $all = $textExt +
$otherExt; // these have disjunct key sets
1025 wfProfileOut( "$fname-split" );
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] );
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();
1059 // show beginning only if it contains all words
1062 foreach ( $textExt as $index => $line ) {
1063 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1064 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1071 // check if first text contains all terms
1072 foreach ( $terms as $term ) {
1073 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
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 );
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;
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] );
1128 while ( $len < $targetchars - 20
1129 && array_key_exists( $add, $all )
1130 && !array_key_exists( $add, $snippets ) ) {
1132 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1133 $extended[$add] = $tt;
1134 $len +
= strlen( $tt );
1140 // $snippets = array_map('htmlspecialchars', $extended);
1141 $snippets = $extended;
1144 foreach ( $snippets as $index => $line ) {
1146 $extract .= $line; // first line
1147 elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1148 $extract .= " " . $line; // continous lines
1150 $extract .= '<b> ... </b>' . $line;
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" );
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 );
1184 $extracts[$count++
] = $tt;
1189 * Do manual case conversion for non-ascii chars
1191 * @param $matches Array
1194 function caseCallback( $matches ) {
1196 if ( strlen( $matches[0] ) > 1 ) {
1197 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $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
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 );
1220 $end = $this->position( $text, $end );
1223 if ( !is_null( $posStart ) ) {
1226 if ( !is_null( $posEnd ) ) {
1230 if ( $end > $start ) {
1231 return substr( $text, $start, $end - $start );
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 ) {
1247 $s = max( 0, $point - $tolerance );
1248 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1250 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1251 return $m[0][1] +
$s +
$offset;
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
1258 if ( $point >= strlen( $text ) )
1259 return strlen( $text );
1260 $char = ord( $text[$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
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
1286 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1290 $len = strlen( $m[0][0] );
1291 if ( $offset +
$len < $contextchars )
1293 elseif ( $len > $contextchars )
1296 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1298 $end = $begin +
$contextchars;
1301 // basic snippet from this line
1302 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1303 $offsets[$index] = $posBegin;
1305 if ( $linesleft == 0 )
1311 * Basic wikitext removal
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 );
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
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
1360 * Simple & fast snippet extraction, but gives completely unrelevant
1363 * @param $text String
1364 * @param $terms Array
1365 * @param $contextlines Integer
1366 * @param $contextchars Integer
1369 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1371 $fname = __METHOD__
;
1373 $lines = explode( "\n", $text );
1375 $terms = implode( '|', $terms );
1376 $max = intval( $contextchars ) +
1;
1377 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1382 wfProfileIn( "$fname-extract" );
1383 foreach ( $lines as $line ) {
1384 if ( 0 == $contextlines ) {
1389 if ( ! preg_match( $pat1, $line, $m ) ) {
1393 // truncate function changes ... to relevant i18n message.
1394 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1396 if ( count( $m ) < 3 ) {
1399 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
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" );
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.
1424 class SearchEngineDummy
extends SearchEngine
{