141f67278d3be67ebc2075db6f820ee198a89cad
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;
30 function __construct($db = null) {
34 $this->db
= wfGetDB( DB_SLAVE
);
39 * Perform a full text search query and return a result set.
40 * If title searches are not supported or disabled, return null.
43 * @param $term String: raw search term
44 * @return SearchResultSet
46 function searchText( $term ) {
51 * Perform a title-only search query and return a result set.
52 * If title searches are not supported or disabled, return null.
55 * @param $term String: raw search term
56 * @return SearchResultSet
58 function searchTitle( $term ) {
62 /** If this search backend can list/unlist redirects */
63 function acceptListRedirects() {
68 * When overridden in derived class, performs database-specific conversions
69 * on text to be used for searching or updating search index.
70 * Default implementation does nothing (simply returns $string).
72 * @param $string string: String to process
75 public function normalizeText( $string ) {
78 // Some languages such as Chinese require word segmentation
79 return $wgContLang->segmentByWord( $string );
83 * Transform search term in cases when parts of the query came as different GET params (when supported)
84 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
86 function transformSearchTerm( $term ) {
91 * If an exact title match can be found, or a very slightly close match,
92 * return the title. If no match, returns NULL.
94 * @param $searchterm String
97 public static function getNearMatch( $searchterm ) {
98 $title = self
::getNearMatchInternal( $searchterm );
100 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
105 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
108 * @param $searchterm string
109 * @return SearchResultSet
111 public static function getNearMatchResultSet( $searchterm ) {
112 return new SearchNearMatchResultSet( self
::getNearMatch( $searchterm ) );
116 * Really find the title match.
118 private static function getNearMatchInternal( $searchterm ) {
121 $allSearchTerms = array( $searchterm );
123 if ( $wgContLang->hasVariants() ) {
124 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
128 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
132 foreach ( $allSearchTerms as $term ) {
134 # Exact match? No need to look further.
135 $title = Title
::newFromText( $term );
136 if ( is_null( $title ) )
139 if ( $title->getNamespace() == NS_SPECIAL ||
$title->isExternal() ||
$title->exists() ) {
143 # See if it still otherwise has content is some sane sense
144 $article = MediaWiki
::articleFromTitle( $title );
145 if ( $article->hasViewableContent() ) {
149 # Now try all lower case (i.e. first letter capitalized)
151 $title = Title
::newFromText( $wgContLang->lc( $term ) );
152 if ( $title && $title->exists() ) {
156 # Now try capitalized string
158 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
159 if ( $title && $title->exists() ) {
163 # Now try all upper case
165 $title = Title
::newFromText( $wgContLang->uc( $term ) );
166 if ( $title && $title->exists() ) {
170 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
171 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
172 if ( $title && $title->exists() ) {
176 // Give hooks a chance at better match variants
178 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
183 $title = Title
::newFromText( $searchterm );
185 # Entering an IP address goes to the contributions page
186 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
187 || User
::isIP( trim( $searchterm ) ) ) {
188 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
192 # Entering a user goes to the user page whether it's there or not
193 if ( $title->getNamespace() == NS_USER
) {
197 # Go to images that exist even if there's no local page.
198 # There may have been a funny upload, or it may be on a shared
199 # file repository such as Wikimedia Commons.
200 if ( $title->getNamespace() == NS_FILE
) {
201 $image = wfFindFile( $title );
207 # MediaWiki namespace? Page may be "implied" if not customized.
208 # Just return it, with caps forced as the message system likes it.
209 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
210 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
213 # Quoted term? Try without the quotes...
215 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
216 return SearchEngine
::getNearMatch( $matches[1] );
222 public static function legalSearchChars() {
223 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
227 * Set the maximum number of results to return
228 * and how many to skip before returning the first.
230 * @param $limit Integer
231 * @param $offset Integer
233 function setLimitOffset( $limit, $offset = 0 ) {
234 $this->limit
= intval( $limit );
235 $this->offset
= intval( $offset );
239 * Set which namespaces the search should include.
240 * Give an array of namespace index numbers.
242 * @param $namespaces Array
244 function setNamespaces( $namespaces ) {
245 $this->namespaces
= $namespaces;
249 * Parse some common prefixes: all (search everything)
252 * @param $query String
254 function replacePrefixes( $query ) {
258 if ( strpos( $query, ':' ) === false ) { // nothing to do
259 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
263 $allkeyword = wfMsgForContent( 'searchall' ) . ":";
264 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
265 $this->namespaces
= null;
266 $parsed = substr( $query, strlen( $allkeyword ) );
267 } else if ( strpos( $query, ':' ) !== false ) {
268 $prefix = substr( $query, 0, strpos( $query, ':' ) );
269 $index = $wgContLang->getNsIndex( $prefix );
270 if ( $index !== false ) {
271 $this->namespaces
= array( $index );
272 $parsed = substr( $query, strlen( $prefix ) +
1 );
275 if ( trim( $parsed ) == '' )
276 $parsed = $query; // prefix was the whole query
278 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
284 * Make a list of searchable namespaces and their canonical names.
287 public static function searchableNamespaces() {
290 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
291 if ( $ns >= NS_MAIN
) {
296 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
301 * Extract default namespaces to search from the given user's
302 * settings, returning a list of index numbers.
307 public static function userNamespaces( $user ) {
308 global $wgSearchEverythingOnlyLoggedIn;
310 // get search everything preference, that can be set to be read for logged-in users
311 $searcheverything = false;
312 if ( ( $wgSearchEverythingOnlyLoggedIn && $user->isLoggedIn() )
313 ||
!$wgSearchEverythingOnlyLoggedIn )
314 $searcheverything = $user->getOption( 'searcheverything' );
316 // searcheverything overrides other options
317 if ( $searcheverything )
318 return array_keys( SearchEngine
::searchableNamespaces() );
320 $arr = Preferences
::loadOldSearchNs( $user );
321 $searchableNamespaces = SearchEngine
::searchableNamespaces();
323 $arr = array_intersect( $arr, array_keys( $searchableNamespaces ) ); // Filter
329 * Find snippet highlight settings for a given user
332 * @return Array contextlines, contextchars
334 public static function userHighlightPrefs( &$user ) {
335 // $contextlines = $user->getOption( 'contextlines', 5 );
336 // $contextchars = $user->getOption( 'contextchars', 50 );
337 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
338 $contextchars = 75; // same as above.... :P
339 return array( $contextlines, $contextchars );
343 * An array of namespaces indexes to be searched by default
347 public static function defaultNamespaces() {
348 global $wgNamespacesToBeSearchedDefault;
350 return array_keys( $wgNamespacesToBeSearchedDefault, true );
354 * Get a list of namespace names useful for showing in tooltips
357 * @param $namespaces Array
359 public static function namespacesAsText( $namespaces ) {
362 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
363 foreach ( $formatted as $key => $ns ) {
365 $formatted[$key] = wfMsg( 'blanknamespace' );
371 * Return the help namespaces to be shown on Special:Search
375 public static function helpNamespaces() {
376 global $wgNamespacesToBeSearchedHelp;
378 return array_keys( $wgNamespacesToBeSearchedHelp, true );
382 * Return a 'cleaned up' search string
384 * @param $text String
387 function filter( $text ) {
388 $lc = $this->legalSearchChars();
389 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
392 * Load up the appropriate search engine class for the currently
393 * active database backend, and return a configured instance.
395 * @return SearchEngine
397 public static function create() {
398 global $wgSearchType;
400 if ( $wgSearchType ) {
401 $class = $wgSearchType;
403 $dbr = wfGetDB( DB_SLAVE
);
404 $class = $dbr->getSearchEngine();
406 $search = new $class( $dbr );
407 $search->setLimitOffset( 0, 0 );
412 * Create or update the search index record for the given page.
413 * Title and text should be pre-processed.
417 * @param $title String
418 * @param $text String
420 function update( $id, $title, $text ) {
425 * Update a search index record's title only.
426 * Title should be pre-processed.
430 * @param $title String
432 function updateTitle( $id, $title ) {
437 * Get OpenSearch suggestion template
441 public static function getOpenSearchTemplate() {
442 global $wgOpenSearchTemplate, $wgServer, $wgScriptPath;
443 if ( $wgOpenSearchTemplate ) {
444 return $wgOpenSearchTemplate;
446 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
447 if ( !$ns ) $ns = "0";
448 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace=' . $ns;
453 * Get internal MediaWiki Suggest template
457 public static function getMWSuggestTemplate() {
458 global $wgMWSuggestTemplate, $wgServer, $wgScriptPath;
459 if ( $wgMWSuggestTemplate )
460 return $wgMWSuggestTemplate;
462 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
469 class SearchResultSet
{
471 * Fetch an array of regular expression fragments for matching
472 * the search terms as parsed by this engine in a text extract.
477 function termMatches() {
486 * Return true if results are included in this result set.
491 function hasResults() {
496 * Some search modes return a total hit count for the query
497 * in the entire article database. This may include pages
498 * in namespaces that would not be matched on the given
501 * Return null if no total hits number is supported.
505 function getTotalHits() {
510 * Some search modes return a suggested alternate term if there are
511 * no exact hits. Returns true if there is one on this set.
515 function hasSuggestion() {
520 * @return String: suggested query, null if none
522 function getSuggestionQuery() {
527 * @return String: HTML highlighted suggested query, '' if none
529 function getSuggestionSnippet() {
534 * Return information about how and from where the results were fetched,
535 * should be useful for diagnostics and debugging
544 * Return a result set of hits on other (multiple) wikis associated with this one
546 * @return SearchResultSet
548 function getInterwikiResults() {
553 * Check if there are results on other wikis
557 function hasInterwikiResults() {
558 return $this->getInterwikiResults() != null;
562 * Fetches next search result, or false.
565 * @return SearchResult
572 * Frees the result set, if applicable.
580 * This class is used for different SQL-based search engines shipped with MediaWiki
582 class SqlSearchResultSet
extends SearchResultSet
{
583 function __construct( $resultSet, $terms ) {
584 $this->mResultSet
= $resultSet;
585 $this->mTerms
= $terms;
588 function termMatches() {
589 return $this->mTerms
;
593 if ( $this->mResultSet
=== false )
596 return $this->mResultSet
->numRows();
600 if ( $this->mResultSet
=== false )
603 $row = $this->mResultSet
->fetchObject();
604 if ( $row === false )
607 return SearchResult
::newFromRow( $row );
611 if ( $this->mResultSet
=== false )
614 $this->mResultSet
->free();
621 class SearchResultTooMany
{
622 # # Some search engines may bail out if too many matches are found
627 * @todo Fixme: This class is horribly factored. It would probably be better to
628 * have a useful base class to which you pass some standard information, then
629 * let the fancy self-highlighters extend that.
633 var $mRevision = null;
637 * Return a new SearchResult and initializes it with a title.
639 * @param $title Title
640 * @return SearchResult
642 public static function newFromTitle( $title ) {
643 $result = new self();
644 $result->initFromTitle( $title );
648 * Return a new SearchResult and initializes it with a row.
651 * @return SearchResult
653 public static function newFromRow( $row ) {
654 $result = new self();
655 $result->initFromRow( $row );
659 public function __construct( $row = null ) {
660 if ( !is_null( $row ) ) {
661 // Backwards compatibility with pre-1.17 callers
662 $this->initFromRow( $row );
667 * Initialize from a database row. Makes a Title and passes that to
672 protected function initFromRow( $row ) {
673 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
677 * Initialize from a Title and if possible initializes a corresponding
680 * @param $title Title
682 protected function initFromTitle( $title ) {
683 $this->mTitle
= $title;
684 if ( !is_null( $this->mTitle
) ) {
685 $this->mRevision
= Revision
::newFromTitle( $this->mTitle
);
686 if ( $this->mTitle
->getNamespace() === NS_FILE
)
687 $this->mImage
= wfFindFile( $this->mTitle
);
692 * Check if this is result points to an invalid title
696 function isBrokenTitle() {
697 if ( is_null( $this->mTitle
) )
703 * Check if target page is missing, happens when index is out of date
707 function isMissingRevision() {
708 return !$this->mRevision
&& !$this->mImage
;
714 function getTitle() {
715 return $this->mTitle
;
719 * @return Double or null if not supported
721 function getScore() {
726 * Lazy initialization of article text from DB
728 protected function initText() {
729 if ( !isset( $this->mText
) ) {
730 if ( $this->mRevision
!= null )
731 $this->mText
= $this->mRevision
->getText();
732 else // TODO: can we fetch raw wikitext for commons images?
739 * @param $terms Array: terms to highlight
740 * @return String: highlighted text snippet, null (and not '') if not supported
742 function getTextSnippet( $terms ) {
743 global $wgUser, $wgAdvancedSearchHighlighting;
745 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
746 $h = new SearchHighlighter();
747 if ( $wgAdvancedSearchHighlighting )
748 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
750 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
754 * @param $terms Array: terms to highlight
755 * @return String: highlighted title, '' if not supported
757 function getTitleSnippet( $terms ) {
762 * @param $terms Array: terms to highlight
763 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
765 function getRedirectSnippet( $terms ) {
770 * @return Title object for the redirect to this page, null if none or not supported
772 function getRedirectTitle() {
777 * @return string highlighted relevant section name, null if none or not supported
779 function getSectionSnippet() {
784 * @return Title object (pagename+fragment) for the section, null if none or not supported
786 function getSectionTitle() {
791 * @return String: timestamp
793 function getTimestamp() {
794 if ( $this->mRevision
)
795 return $this->mRevision
->getTimestamp();
796 else if ( $this->mImage
)
797 return $this->mImage
->getTimestamp();
802 * @return Integer: number of words
804 function getWordCount() {
806 return str_word_count( $this->mText
);
810 * @return Integer: size in bytes
812 function getByteSize() {
814 return strlen( $this->mText
);
818 * @return Boolean if hit has related articles
820 function hasRelated() {
825 * @return String: interwiki prefix of the title (return iw even if title is broken)
827 function getInterwikiPrefix() {
832 * A SearchResultSet wrapper for SearchEngine::getNearMatch
834 class SearchNearMatchResultSet
extends SearchResultSet
{
835 private $fetched = false;
837 * @param $match mixed Title if matched, else null
839 public function __construct( $match ) {
840 $this->result
= $match;
842 public function hasResult() {
843 return (bool)$this->result
;
845 public function numRows() {
846 return $this->hasResults() ?
1 : 0;
848 public function next() {
849 if ( $this->fetched ||
!$this->result
) {
852 $this->fetched
= true;
853 return SearchResult
::newFromTitle( $this->result
);
858 * Highlight bits of wikitext
862 class SearchHighlighter
{
863 var $mCleanWikitext = true;
865 function __construct( $cleanupWikitext = true ) {
866 $this->mCleanWikitext
= $cleanupWikitext;
870 * Default implementation of wikitext highlighting
872 * @param $text String
873 * @param $terms Array: terms to highlight (unescaped)
874 * @param $contextlines Integer
875 * @param $contextchars Integer
878 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
880 global $wgSearchHighlightBoundaries;
886 // spli text into text + templates/links/tables
887 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
888 // first capture group is for detecting nested templates/links/tables/references
889 $endPatterns = array(
890 1 => '/(\{\{)|(\}\})/', // template
891 2 => '/(\[\[)|(\]\])/', // image
892 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
894 // FIXME: this should prolly be a hook or something
895 if ( function_exists( 'wfCite' ) ) {
896 $spat .= '|(<ref>)'; // references via cite extension
897 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
900 $textExt = array(); // text extracts
901 $otherExt = array(); // other extracts
902 wfProfileIn( "$fname-split" );
904 $textLen = strlen( $text );
905 $count = 0; // sequence number to maintain ordering
906 while ( $start < $textLen ) {
907 // find start of template/image/table
908 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
910 foreach ( $matches as $key => $val ) {
911 if ( $key > 0 && $val[1] != - 1 ) {
913 // see if this is an image link
914 $ns = substr( $val[0], 2, - 1 );
915 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
)
919 $epat = $endPatterns[$key];
920 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
926 // find end (and detect any nested elements)
928 $offset = $start +
1;
930 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
931 if ( array_key_exists( 2, $endMatches ) ) {
934 $len = strlen( $endMatches[2][0] );
935 $off = $endMatches[2][1];
936 $this->splitAndAdd( $otherExt, $count,
937 substr( $text, $start, $off +
$len - $start ) );
938 $start = $off +
$len;
942 // end of nested element
949 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
952 // couldn't find appropriate closing tag, skip
953 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
954 $start +
= strlen( $matches[0][0] );
959 // else: add as text extract
960 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
964 $all = $textExt +
$otherExt; // these have disjunct key sets
966 wfProfileOut( "$fname-split" );
969 foreach ( $terms as $index => $term ) {
970 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
971 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
972 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
974 $terms[$index] = $term;
977 $anyterm = implode( '|', $terms );
978 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
980 // FIXME: a hack to scale contextchars, a correct solution
981 // would be to have contextchars actually be char and not byte
982 // length, and do proper utf-8 substrings and lengths everywhere,
983 // but PHP is making that very hard and unclean to implement :(
984 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
985 $contextchars = intval( $contextchars * $scale );
987 $patPre = "(^|$wgSearchHighlightBoundaries)";
988 $patPost = "($wgSearchHighlightBoundaries|$)";
990 $pat1 = "/(" . $phrase . ")/ui";
991 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
993 wfProfileIn( "$fname-extract" );
995 $left = $contextlines;
1000 // show beginning only if it contains all words
1003 foreach ( $textExt as $index => $line ) {
1004 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1005 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1012 // check if first text contains all terms
1013 foreach ( $terms as $term ) {
1014 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1020 $snippets[$first] = $firstText;
1021 $offsets[$first] = 0;
1024 if ( ! $snippets ) {
1025 // match whole query on text
1026 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1027 // match whole query on templates/tables/images
1028 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1029 // match any words on text
1030 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1031 // match any words on templates/tables/images
1032 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1037 // add extra chars to each snippet to make snippets constant size
1038 $extended = array();
1039 if ( count( $snippets ) == 0 ) {
1040 // couldn't find the target words, just show beginning of article
1041 if ( array_key_exists( $first, $all ) ) {
1042 $targetchars = $contextchars * $contextlines;
1043 $snippets[$first] = '';
1044 $offsets[$first] = 0;
1047 // if begin of the article contains the whole phrase, show only that !!
1048 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1049 && $offsets[$first] < $contextchars * 2 ) {
1050 $snippets = array ( $first => $snippets[$first] );
1053 // calc by how much to extend existing snippets
1054 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1057 foreach ( $snippets as $index => $line ) {
1058 $extended[$index] = $line;
1059 $len = strlen( $line );
1060 if ( $len < $targetchars - 20 ) {
1061 // complete this line
1062 if ( $len < strlen( $all[$index] ) ) {
1063 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1064 $len = strlen( $extended[$index] );
1069 while ( $len < $targetchars - 20
1070 && array_key_exists( $add, $all )
1071 && !array_key_exists( $add, $snippets ) ) {
1073 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1074 $extended[$add] = $tt;
1075 $len +
= strlen( $tt );
1081 // $snippets = array_map('htmlspecialchars', $extended);
1082 $snippets = $extended;
1085 foreach ( $snippets as $index => $line ) {
1087 $extract .= $line; // first line
1088 elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1089 $extract .= " " . $line; // continous lines
1091 $extract .= '<b> ... </b>' . $line;
1096 $extract .= '<b> ... </b>';
1098 $processed = array();
1099 foreach ( $terms as $term ) {
1100 if ( ! isset( $processed[$term] ) ) {
1101 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1102 $extract = preg_replace( $pat3,
1103 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1104 $processed[$term] = true;
1108 wfProfileOut( "$fname-extract" );
1114 * Split text into lines and add it to extracts array
1116 * @param $extracts Array: index -> $line
1117 * @param $count Integer
1118 * @param $text String
1120 function splitAndAdd( &$extracts, &$count, $text ) {
1121 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1122 foreach ( $split as $line ) {
1123 $tt = trim( $line );
1125 $extracts[$count++
] = $tt;
1130 * Do manual case conversion for non-ascii chars
1132 * @param $matches Array
1134 function caseCallback( $matches ) {
1136 if ( strlen( $matches[0] ) > 1 ) {
1137 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1143 * Extract part of the text from start to end, but by
1144 * not chopping up words
1145 * @param $text String
1146 * @param $start Integer
1147 * @param $end Integer
1148 * @param $posStart Integer: (out) actual start position
1149 * @param $posEnd Integer: (out) actual end position
1152 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1154 $start = $this->position( $text, $start, 1 );
1155 if ( $end >= strlen( $text ) )
1156 $end = strlen( $text );
1158 $end = $this->position( $text, $end );
1160 if ( !is_null( $posStart ) )
1162 if ( !is_null( $posEnd ) )
1165 if ( $end > $start )
1166 return substr( $text, $start, $end - $start );
1172 * Find a nonletter near a point (index) in the text
1174 * @param $text String
1175 * @param $point Integer
1176 * @param $offset Integer: offset to found index
1177 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1179 function position( $text, $point, $offset = 0 ) {
1181 $s = max( 0, $point - $tolerance );
1182 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1184 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1185 return $m[0][1] +
$s +
$offset;
1187 // check if point is on a valid first UTF8 char
1188 $char = ord( $text[$point] );
1189 while ( $char >= 0x80 && $char < 0xc0 ) {
1190 // skip trailing bytes
1192 if ( $point >= strlen( $text ) )
1193 return strlen( $text );
1194 $char = ord( $text[$point] );
1202 * Search extracts for a pattern, and return snippets
1204 * @param $pattern String: regexp for matching lines
1205 * @param $extracts Array: extracts to search
1206 * @param $linesleft Integer: number of extracts to make
1207 * @param $contextchars Integer: length of snippet
1208 * @param $out Array: map for highlighted snippets
1209 * @param $offsets Array: map of starting points of snippets
1212 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1213 if ( $linesleft == 0 )
1214 return; // nothing to do
1215 foreach ( $extracts as $index => $line ) {
1216 if ( array_key_exists( $index, $out ) )
1217 continue; // this line already highlighted
1220 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1224 $len = strlen( $m[0][0] );
1225 if ( $offset +
$len < $contextchars )
1227 elseif ( $len > $contextchars )
1230 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1232 $end = $begin +
$contextchars;
1235 // basic snippet from this line
1236 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1237 $offsets[$index] = $posBegin;
1239 if ( $linesleft == 0 )
1245 * Basic wikitext removal
1248 function removeWiki( $text ) {
1249 $fname = __METHOD__
;
1250 wfProfileIn( $fname );
1252 // $text = preg_replace("/'{2,5}/", "", $text);
1253 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1254 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1255 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1256 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1257 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1258 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1259 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1260 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1261 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1262 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1263 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1264 $text = preg_replace( "/'''''/", "", $text );
1265 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1266 $text = preg_replace( "/''/", "", $text );
1268 wfProfileOut( $fname );
1273 * callback to replace [[target|caption]] kind of links, if
1274 * the target is category or image, leave it
1276 * @param $matches Array
1278 function linkReplace( $matches ) {
1279 $colon = strpos( $matches[1], ':' );
1280 if ( $colon === false )
1281 return $matches[2]; // replace with caption
1283 $ns = substr( $matches[1], 0, $colon );
1284 $index = $wgContLang->getNsIndex( $ns );
1285 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) )
1286 return $matches[0]; // return the whole thing
1293 * Simple & fast snippet extraction, but gives completely unrelevant
1296 * @param $text String
1297 * @param $terms Array
1298 * @param $contextlines Integer
1299 * @param $contextchars Integer
1302 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1304 $fname = __METHOD__
;
1306 $lines = explode( "\n", $text );
1308 $terms = implode( '|', $terms );
1309 $max = intval( $contextchars ) +
1;
1310 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1315 wfProfileIn( "$fname-extract" );
1316 foreach ( $lines as $line ) {
1317 if ( 0 == $contextlines ) {
1322 if ( ! preg_match( $pat1, $line, $m ) ) {
1326 // truncate function changes ... to relevant i18n message.
1327 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1329 if ( count( $m ) < 3 ) {
1332 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1337 $line = htmlspecialchars( $pre . $found . $post );
1338 $pat2 = '/(' . $terms . ")/i";
1339 $line = preg_replace( $pat2,
1340 "<span class='searchmatch'>\\1</span>", $line );
1342 $extract .= "${line}\n";
1344 wfProfileOut( "$fname-extract" );
1352 * Dummy class to be used when non-supported Database engine is present.
1353 * @todo Fixme: dummy class should probably try something at least mildly useful,
1354 * such as a LIKE search through titles.
1357 class SearchEngineDummy
extends SearchEngine
{