a62104f68a7901380727acfb1a2c36487abbfc6e
3 * @defgroup Search Search
10 * Contain a class for special pages
17 var $searchTerms = array();
18 var $namespaces = array( NS_MAIN
);
19 var $showRedirects = false;
22 * Perform a full text search query and return a result set.
23 * If title searches are not supported or disabled, return null.
26 * @param $term String: raw search term
27 * @return SearchResultSet
29 function searchText( $term ) {
34 * Perform a title-only search query and return a result set.
35 * If title searches are not supported or disabled, return null.
38 * @param $term String: raw search term
39 * @return SearchResultSet
41 function searchTitle( $term ) {
45 /** If this search backend can list/unlist redirects */
46 function acceptListRedirects() {
51 * When overridden in derived class, performs database-specific conversions
52 * on text to be used for searching or updating search index.
53 * Default implementation does nothing (simply returns $string).
55 * @param $string string: String to process
58 public function normalizeText( $string ) {
61 // Some languages such as Chinese require word segmentation
62 return $wgContLang->segmentByWord( $string );
66 * Transform search term in cases when parts of the query came as different GET params (when supported)
67 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
69 function transformSearchTerm( $term ) {
74 * If an exact title match can be found, or a very slightly close match,
75 * return the title. If no match, returns NULL.
77 * @param $searchterm String
80 public static function getNearMatch( $searchterm ) {
81 $title = self
::getNearMatchInternal( $searchterm );
83 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
88 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
91 * @param $searchterm string
92 * @return SearchResultSet
94 public static function getNearMatchResultSet( $searchterm ) {
95 return new SearchNearMatchResultSet( self
::getNearMatch( $searchterm ) );
99 * Really find the title match.
101 private static function getNearMatchInternal( $searchterm ) {
104 $allSearchTerms = array( $searchterm );
106 if ( $wgContLang->hasVariants() ) {
107 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->convertLinkToAllVariants( $searchterm ) );
110 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
114 foreach ( $allSearchTerms as $term ) {
116 # Exact match? No need to look further.
117 $title = Title
::newFromText( $term );
118 if ( is_null( $title ) )
121 if ( $title->getNamespace() == NS_SPECIAL ||
$title->isExternal() ||
$title->exists() ) {
125 # See if it still otherwise has content is some sane sense
126 $article = MediaWiki
::articleFromTitle( $title );
127 if ( $article->hasViewableContent() ) {
131 # Now try all lower case (i.e. first letter capitalized)
133 $title = Title
::newFromText( $wgContLang->lc( $term ) );
134 if ( $title && $title->exists() ) {
138 # Now try capitalized string
140 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
141 if ( $title && $title->exists() ) {
145 # Now try all upper case
147 $title = Title
::newFromText( $wgContLang->uc( $term ) );
148 if ( $title && $title->exists() ) {
152 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
153 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
154 if ( $title && $title->exists() ) {
158 // Give hooks a chance at better match variants
160 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
165 $title = Title
::newFromText( $searchterm );
167 # Entering an IP address goes to the contributions page
168 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
169 || User
::isIP( trim( $searchterm ) ) ) {
170 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
174 # Entering a user goes to the user page whether it's there or not
175 if ( $title->getNamespace() == NS_USER
) {
179 # Go to images that exist even if there's no local page.
180 # There may have been a funny upload, or it may be on a shared
181 # file repository such as Wikimedia Commons.
182 if ( $title->getNamespace() == NS_FILE
) {
183 $image = wfFindFile( $title );
189 # MediaWiki namespace? Page may be "implied" if not customized.
190 # Just return it, with caps forced as the message system likes it.
191 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
192 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
195 # Quoted term? Try without the quotes...
197 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
198 return SearchEngine
::getNearMatch( $matches[1] );
204 public static function legalSearchChars() {
205 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
209 * Set the maximum number of results to return
210 * and how many to skip before returning the first.
212 * @param $limit Integer
213 * @param $offset Integer
215 function setLimitOffset( $limit, $offset = 0 ) {
216 $this->limit
= intval( $limit );
217 $this->offset
= intval( $offset );
221 * Set which namespaces the search should include.
222 * Give an array of namespace index numbers.
224 * @param $namespaces Array
226 function setNamespaces( $namespaces ) {
227 $this->namespaces
= $namespaces;
231 * Parse some common prefixes: all (search everything)
234 * @param $query String
236 function replacePrefixes( $query ) {
240 if ( strpos( $query, ':' ) === false ) { // nothing to do
241 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
245 $allkeyword = wfMsgForContent( 'searchall' ) . ":";
246 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
247 $this->namespaces
= null;
248 $parsed = substr( $query, strlen( $allkeyword ) );
249 } else if ( strpos( $query, ':' ) !== false ) {
250 $prefix = substr( $query, 0, strpos( $query, ':' ) );
251 $index = $wgContLang->getNsIndex( $prefix );
252 if ( $index !== false ) {
253 $this->namespaces
= array( $index );
254 $parsed = substr( $query, strlen( $prefix ) +
1 );
257 if ( trim( $parsed ) == '' )
258 $parsed = $query; // prefix was the whole query
260 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
266 * Make a list of searchable namespaces and their canonical names.
269 public static function searchableNamespaces() {
272 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
273 if ( $ns >= NS_MAIN
) {
278 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
283 * Extract default namespaces to search from the given user's
284 * settings, returning a list of index numbers.
289 public static function userNamespaces( $user ) {
290 global $wgSearchEverythingOnlyLoggedIn;
292 // get search everything preference, that can be set to be read for logged-in users
293 $searcheverything = false;
294 if ( ( $wgSearchEverythingOnlyLoggedIn && $user->isLoggedIn() )
295 ||
!$wgSearchEverythingOnlyLoggedIn )
296 $searcheverything = $user->getOption( 'searcheverything' );
298 // searcheverything overrides other options
299 if ( $searcheverything )
300 return array_keys( SearchEngine
::searchableNamespaces() );
302 $arr = Preferences
::loadOldSearchNs( $user );
303 $searchableNamespaces = SearchEngine
::searchableNamespaces();
305 $arr = array_intersect( $arr, array_keys( $searchableNamespaces ) ); // Filter
311 * Find snippet highlight settings for a given user
314 * @return Array contextlines, contextchars
316 public static function userHighlightPrefs( &$user ) {
317 // $contextlines = $user->getOption( 'contextlines', 5 );
318 // $contextchars = $user->getOption( 'contextchars', 50 );
319 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
320 $contextchars = 75; // same as above.... :P
321 return array( $contextlines, $contextchars );
325 * An array of namespaces indexes to be searched by default
329 public static function defaultNamespaces() {
330 global $wgNamespacesToBeSearchedDefault;
332 return array_keys( $wgNamespacesToBeSearchedDefault, true );
336 * Get a list of namespace names useful for showing in tooltips
339 * @param $namespaces Array
341 public static function namespacesAsText( $namespaces ) {
344 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
345 foreach ( $formatted as $key => $ns ) {
347 $formatted[$key] = wfMsg( 'blanknamespace' );
353 * Return the help namespaces to be shown on Special:Search
357 public static function helpNamespaces() {
358 global $wgNamespacesToBeSearchedHelp;
360 return array_keys( $wgNamespacesToBeSearchedHelp, true );
364 * Return a 'cleaned up' search string
366 * @param $text String
369 function filter( $text ) {
370 $lc = $this->legalSearchChars();
371 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
374 * Load up the appropriate search engine class for the currently
375 * active database backend, and return a configured instance.
377 * @return SearchEngine
379 public static function create() {
380 global $wgSearchType;
381 $dbr = wfGetDB( DB_SLAVE
);
382 if ( $wgSearchType ) {
383 $class = $wgSearchType;
385 $class = $dbr->getSearchEngine();
387 $search = new $class( $dbr );
388 $search->setLimitOffset( 0, 0 );
393 * Create or update the search index record for the given page.
394 * Title and text should be pre-processed.
398 * @param $title String
399 * @param $text String
401 function update( $id, $title, $text ) {
406 * Update a search index record's title only.
407 * Title should be pre-processed.
411 * @param $title String
413 function updateTitle( $id, $title ) {
418 * Get OpenSearch suggestion template
422 public static function getOpenSearchTemplate() {
423 global $wgOpenSearchTemplate, $wgServer, $wgScriptPath;
424 if ( $wgOpenSearchTemplate ) {
425 return $wgOpenSearchTemplate;
427 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
428 if ( !$ns ) $ns = "0";
429 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace=' . $ns;
434 * Get internal MediaWiki Suggest template
438 public static function getMWSuggestTemplate() {
439 global $wgMWSuggestTemplate, $wgServer, $wgScriptPath;
440 if ( $wgMWSuggestTemplate )
441 return $wgMWSuggestTemplate;
443 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
450 class SearchResultSet
{
452 * Fetch an array of regular expression fragments for matching
453 * the search terms as parsed by this engine in a text extract.
458 function termMatches() {
467 * Return true if results are included in this result set.
472 function hasResults() {
477 * Some search modes return a total hit count for the query
478 * in the entire article database. This may include pages
479 * in namespaces that would not be matched on the given
482 * Return null if no total hits number is supported.
486 function getTotalHits() {
491 * Some search modes return a suggested alternate term if there are
492 * no exact hits. Returns true if there is one on this set.
496 function hasSuggestion() {
501 * @return String: suggested query, null if none
503 function getSuggestionQuery() {
508 * @return String: HTML highlighted suggested query, '' if none
510 function getSuggestionSnippet() {
515 * Return information about how and from where the results were fetched,
516 * should be useful for diagnostics and debugging
525 * Return a result set of hits on other (multiple) wikis associated with this one
527 * @return SearchResultSet
529 function getInterwikiResults() {
534 * Check if there are results on other wikis
538 function hasInterwikiResults() {
539 return $this->getInterwikiResults() != null;
543 * Fetches next search result, or false.
546 * @return SearchResult
553 * Frees the result set, if applicable.
561 * This class is used for different SQL-based search engines shipped with MediaWiki
563 class SqlSearchResultSet
extends SearchResultSet
{
564 function __construct( $resultSet, $terms ) {
565 $this->mResultSet
= $resultSet;
566 $this->mTerms
= $terms;
569 function termMatches() {
570 return $this->mTerms
;
574 if ( $this->mResultSet
=== false )
577 return $this->mResultSet
->numRows();
581 if ( $this->mResultSet
=== false )
584 $row = $this->mResultSet
->fetchObject();
585 if ( $row === false )
588 return SearchResult
::newFromRow( $row );
592 if ( $this->mResultSet
=== false )
595 $this->mResultSet
->free();
602 class SearchResultTooMany
{
603 # # Some search engines may bail out if too many matches are found
608 * @todo Fixme: This class is horribly factored. It would probably be better to
609 * have a useful base class to which you pass some standard information, then
610 * let the fancy self-highlighters extend that.
614 var $mRevision = null;
618 * Return a new SearchResult and initializes it with a title.
620 * @param $title Title
621 * @return SearchResult
623 public static function newFromTitle( $title ) {
624 $result = new self();
625 $result->initFromTitle( $title );
629 * Return a new SearchResult and initializes it with a row.
632 * @return SearchResult
634 public static function newFromRow( $row ) {
635 $result = new self();
636 $result->initFromRow( $row );
640 public function __construct( $row = null ) {
641 if ( !is_null( $row ) ) {
642 // Backwards compatibility with pre-1.17 callers
643 $this->initFromRow( $row );
648 * Initialize from a database row. Makes a Title and passes that to
653 protected function initFromRow( $row ) {
654 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
658 * Initialize from a Title and if possible initializes a corresponding
661 * @param $title Title
663 protected function initFromTitle( $title ) {
664 $this->mTitle
= $title;
665 if ( !is_null( $this->mTitle
) ) {
666 $this->mRevision
= Revision
::newFromTitle( $this->mTitle
);
667 if ( $this->mTitle
->getNamespace() === NS_FILE
)
668 $this->mImage
= wfFindFile( $this->mTitle
);
673 * Check if this is result points to an invalid title
677 function isBrokenTitle() {
678 if ( is_null( $this->mTitle
) )
684 * Check if target page is missing, happens when index is out of date
688 function isMissingRevision() {
689 return !$this->mRevision
&& !$this->mImage
;
695 function getTitle() {
696 return $this->mTitle
;
700 * @return Double or null if not supported
702 function getScore() {
707 * Lazy initialization of article text from DB
709 protected function initText() {
710 if ( !isset( $this->mText
) ) {
711 if ( $this->mRevision
!= null )
712 $this->mText
= $this->mRevision
->getText();
713 else // TODO: can we fetch raw wikitext for commons images?
720 * @param $terms Array: terms to highlight
721 * @return String: highlighted text snippet, null (and not '') if not supported
723 function getTextSnippet( $terms ) {
724 global $wgUser, $wgAdvancedSearchHighlighting;
726 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
727 $h = new SearchHighlighter();
728 if ( $wgAdvancedSearchHighlighting )
729 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
731 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
735 * @param $terms Array: terms to highlight
736 * @return String: highlighted title, '' if not supported
738 function getTitleSnippet( $terms ) {
743 * @param $terms Array: terms to highlight
744 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
746 function getRedirectSnippet( $terms ) {
751 * @return Title object for the redirect to this page, null if none or not supported
753 function getRedirectTitle() {
758 * @return string highlighted relevant section name, null if none or not supported
760 function getSectionSnippet() {
765 * @return Title object (pagename+fragment) for the section, null if none or not supported
767 function getSectionTitle() {
772 * @return String: timestamp
774 function getTimestamp() {
775 if ( $this->mRevision
)
776 return $this->mRevision
->getTimestamp();
777 else if ( $this->mImage
)
778 return $this->mImage
->getTimestamp();
783 * @return Integer: number of words
785 function getWordCount() {
787 return str_word_count( $this->mText
);
791 * @return Integer: size in bytes
793 function getByteSize() {
795 return strlen( $this->mText
);
799 * @return Boolean if hit has related articles
801 function hasRelated() {
806 * @return String: interwiki prefix of the title (return iw even if title is broken)
808 function getInterwikiPrefix() {
813 * A SearchResultSet wrapper for SearchEngine::getNearMatch
815 class SearchNearMatchResultSet
extends SearchResultSet
{
816 private $fetched = false;
818 * @param $match mixed Title if matched, else null
820 public function __construct( $match ) {
821 $this->result
= $match;
823 public function hasResult() {
824 return (bool)$this->result
;
826 public function numRows() {
827 return $this->hasResults() ?
1 : 0;
829 public function next() {
830 if ( $this->fetched ||
!$this->result
) {
833 $this->fetched
= true;
834 return SearchResult
::newFromTitle( $this->result
);
839 * Highlight bits of wikitext
843 class SearchHighlighter
{
844 var $mCleanWikitext = true;
846 function SearchHighlighter( $cleanupWikitext = true ) {
847 $this->mCleanWikitext
= $cleanupWikitext;
851 * Default implementation of wikitext highlighting
853 * @param $text String
854 * @param $terms Array: terms to highlight (unescaped)
855 * @param $contextlines Integer
856 * @param $contextchars Integer
859 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
861 global $wgSearchHighlightBoundaries;
867 // spli text into text + templates/links/tables
868 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
869 // first capture group is for detecting nested templates/links/tables/references
870 $endPatterns = array(
871 1 => '/(\{\{)|(\}\})/', // template
872 2 => '/(\[\[)|(\]\])/', // image
873 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
875 // FIXME: this should prolly be a hook or something
876 if ( function_exists( 'wfCite' ) ) {
877 $spat .= '|(<ref>)'; // references via cite extension
878 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
881 $textExt = array(); // text extracts
882 $otherExt = array(); // other extracts
883 wfProfileIn( "$fname-split" );
885 $textLen = strlen( $text );
886 $count = 0; // sequence number to maintain ordering
887 while ( $start < $textLen ) {
888 // find start of template/image/table
889 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
891 foreach ( $matches as $key => $val ) {
892 if ( $key > 0 && $val[1] != - 1 ) {
894 // see if this is an image link
895 $ns = substr( $val[0], 2, - 1 );
896 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
)
900 $epat = $endPatterns[$key];
901 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
907 // find end (and detect any nested elements)
909 $offset = $start +
1;
911 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
912 if ( array_key_exists( 2, $endMatches ) ) {
915 $len = strlen( $endMatches[2][0] );
916 $off = $endMatches[2][1];
917 $this->splitAndAdd( $otherExt, $count,
918 substr( $text, $start, $off +
$len - $start ) );
919 $start = $off +
$len;
923 // end of nested element
930 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
933 // couldn't find appropriate closing tag, skip
934 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
935 $start +
= strlen( $matches[0][0] );
940 // else: add as text extract
941 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
945 $all = $textExt +
$otherExt; // these have disjunct key sets
947 wfProfileOut( "$fname-split" );
950 foreach ( $terms as $index => $term ) {
951 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
952 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
953 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
955 $terms[$index] = $term;
958 $anyterm = implode( '|', $terms );
959 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
961 // FIXME: a hack to scale contextchars, a correct solution
962 // would be to have contextchars actually be char and not byte
963 // length, and do proper utf-8 substrings and lengths everywhere,
964 // but PHP is making that very hard and unclean to implement :(
965 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
966 $contextchars = intval( $contextchars * $scale );
968 $patPre = "(^|$wgSearchHighlightBoundaries)";
969 $patPost = "($wgSearchHighlightBoundaries|$)";
971 $pat1 = "/(" . $phrase . ")/ui";
972 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
974 wfProfileIn( "$fname-extract" );
976 $left = $contextlines;
981 // show beginning only if it contains all words
984 foreach ( $textExt as $index => $line ) {
985 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
986 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
993 // check if first text contains all terms
994 foreach ( $terms as $term ) {
995 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1001 $snippets[$first] = $firstText;
1002 $offsets[$first] = 0;
1005 if ( ! $snippets ) {
1006 // match whole query on text
1007 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1008 // match whole query on templates/tables/images
1009 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1010 // match any words on text
1011 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1012 // match any words on templates/tables/images
1013 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1018 // add extra chars to each snippet to make snippets constant size
1019 $extended = array();
1020 if ( count( $snippets ) == 0 ) {
1021 // couldn't find the target words, just show beginning of article
1022 if ( array_key_exists( $first, $all ) ) {
1023 $targetchars = $contextchars * $contextlines;
1024 $snippets[$first] = '';
1025 $offsets[$first] = 0;
1028 // if begin of the article contains the whole phrase, show only that !!
1029 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1030 && $offsets[$first] < $contextchars * 2 ) {
1031 $snippets = array ( $first => $snippets[$first] );
1034 // calc by how much to extend existing snippets
1035 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1038 foreach ( $snippets as $index => $line ) {
1039 $extended[$index] = $line;
1040 $len = strlen( $line );
1041 if ( $len < $targetchars - 20 ) {
1042 // complete this line
1043 if ( $len < strlen( $all[$index] ) ) {
1044 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1045 $len = strlen( $extended[$index] );
1050 while ( $len < $targetchars - 20
1051 && array_key_exists( $add, $all )
1052 && !array_key_exists( $add, $snippets ) ) {
1054 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1055 $extended[$add] = $tt;
1056 $len +
= strlen( $tt );
1062 // $snippets = array_map('htmlspecialchars', $extended);
1063 $snippets = $extended;
1066 foreach ( $snippets as $index => $line ) {
1068 $extract .= $line; // first line
1069 elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1070 $extract .= " " . $line; // continous lines
1072 $extract .= '<b> ... </b>' . $line;
1077 $extract .= '<b> ... </b>';
1079 $processed = array();
1080 foreach ( $terms as $term ) {
1081 if ( ! isset( $processed[$term] ) ) {
1082 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1083 $extract = preg_replace( $pat3,
1084 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1085 $processed[$term] = true;
1089 wfProfileOut( "$fname-extract" );
1095 * Split text into lines and add it to extracts array
1097 * @param $extracts Array: index -> $line
1098 * @param $count Integer
1099 * @param $text String
1101 function splitAndAdd( &$extracts, &$count, $text ) {
1102 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1103 foreach ( $split as $line ) {
1104 $tt = trim( $line );
1106 $extracts[$count++
] = $tt;
1111 * Do manual case conversion for non-ascii chars
1113 * @param $matches Array
1115 function caseCallback( $matches ) {
1117 if ( strlen( $matches[0] ) > 1 ) {
1118 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1124 * Extract part of the text from start to end, but by
1125 * not chopping up words
1126 * @param $text String
1127 * @param $start Integer
1128 * @param $end Integer
1129 * @param $posStart Integer: (out) actual start position
1130 * @param $posEnd Integer: (out) actual end position
1133 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1135 $start = $this->position( $text, $start, 1 );
1136 if ( $end >= strlen( $text ) )
1137 $end = strlen( $text );
1139 $end = $this->position( $text, $end );
1141 if ( !is_null( $posStart ) )
1143 if ( !is_null( $posEnd ) )
1146 if ( $end > $start )
1147 return substr( $text, $start, $end - $start );
1153 * Find a nonletter near a point (index) in the text
1155 * @param $text String
1156 * @param $point Integer
1157 * @param $offset Integer: offset to found index
1158 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1160 function position( $text, $point, $offset = 0 ) {
1162 $s = max( 0, $point - $tolerance );
1163 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1165 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1166 return $m[0][1] +
$s +
$offset;
1168 // check if point is on a valid first UTF8 char
1169 $char = ord( $text[$point] );
1170 while ( $char >= 0x80 && $char < 0xc0 ) {
1171 // skip trailing bytes
1173 if ( $point >= strlen( $text ) )
1174 return strlen( $text );
1175 $char = ord( $text[$point] );
1183 * Search extracts for a pattern, and return snippets
1185 * @param $pattern String: regexp for matching lines
1186 * @param $extracts Array: extracts to search
1187 * @param $linesleft Integer: number of extracts to make
1188 * @param $contextchars Integer: length of snippet
1189 * @param $out Array: map for highlighted snippets
1190 * @param $offsets Array: map of starting points of snippets
1193 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1194 if ( $linesleft == 0 )
1195 return; // nothing to do
1196 foreach ( $extracts as $index => $line ) {
1197 if ( array_key_exists( $index, $out ) )
1198 continue; // this line already highlighted
1201 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1205 $len = strlen( $m[0][0] );
1206 if ( $offset +
$len < $contextchars )
1208 elseif ( $len > $contextchars )
1211 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1213 $end = $begin +
$contextchars;
1216 // basic snippet from this line
1217 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1218 $offsets[$index] = $posBegin;
1220 if ( $linesleft == 0 )
1226 * Basic wikitext removal
1229 function removeWiki( $text ) {
1230 $fname = __METHOD__
;
1231 wfProfileIn( $fname );
1233 // $text = preg_replace("/'{2,5}/", "", $text);
1234 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1235 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1236 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1237 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1238 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1239 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1240 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1241 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1242 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1243 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1244 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1245 $text = preg_replace( "/'''''/", "", $text );
1246 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1247 $text = preg_replace( "/''/", "", $text );
1249 wfProfileOut( $fname );
1254 * callback to replace [[target|caption]] kind of links, if
1255 * the target is category or image, leave it
1257 * @param $matches Array
1259 function linkReplace( $matches ) {
1260 $colon = strpos( $matches[1], ':' );
1261 if ( $colon === false )
1262 return $matches[2]; // replace with caption
1264 $ns = substr( $matches[1], 0, $colon );
1265 $index = $wgContLang->getNsIndex( $ns );
1266 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) )
1267 return $matches[0]; // return the whole thing
1274 * Simple & fast snippet extraction, but gives completely unrelevant
1277 * @param $text String
1278 * @param $terms Array
1279 * @param $contextlines Integer
1280 * @param $contextchars Integer
1283 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1285 $fname = __METHOD__
;
1287 $lines = explode( "\n", $text );
1289 $terms = implode( '|', $terms );
1290 $max = intval( $contextchars ) +
1;
1291 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1296 wfProfileIn( "$fname-extract" );
1297 foreach ( $lines as $line ) {
1298 if ( 0 == $contextlines ) {
1303 if ( ! preg_match( $pat1, $line, $m ) ) {
1307 $pre = $wgContLang->truncate( $m[1], - $contextchars );
1309 if ( count( $m ) < 3 ) {
1312 $post = $wgContLang->truncate( $m[3], $contextchars );
1317 $line = htmlspecialchars( $pre . $found . $post );
1318 $pat2 = '/(' . $terms . ")/i";
1319 $line = preg_replace( $pat2,
1320 "<span class='searchmatch'>\\1</span>", $line );
1322 $extract .= "${line}\n";
1324 wfProfileOut( "$fname-extract" );
1332 * Dummy class to be used when non-supported Database engine is present.
1333 * @todo Fixme: dummy class should probably try something at least mildly useful,
1334 * such as a LIKE search through titles.
1337 class SearchEngineDummy
extends SearchEngine
{