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.
637 var $mRevision = null;
651 * Return a new SearchResult and initializes it with a title.
653 * @param $title Title
654 * @return SearchResult
656 public static function newFromTitle( $title ) {
657 $result = new self();
658 $result->initFromTitle( $title );
662 * Return a new SearchResult and initializes it with a row.
665 * @return SearchResult
667 public static function newFromRow( $row ) {
668 $result = new self();
669 $result->initFromRow( $row );
673 public function __construct( $row = null ) {
674 if ( !is_null( $row ) ) {
675 // Backwards compatibility with pre-1.17 callers
676 $this->initFromRow( $row );
681 * Initialize from a database row. Makes a Title and passes that to
686 protected function initFromRow( $row ) {
687 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
691 * Initialize from a Title and if possible initializes a corresponding
694 * @param $title Title
696 protected function initFromTitle( $title ) {
697 $this->mTitle
= $title;
698 if ( !is_null( $this->mTitle
) ) {
699 $this->mRevision
= Revision
::newFromTitle( $this->mTitle
);
700 if ( $this->mTitle
->getNamespace() === NS_FILE
)
701 $this->mImage
= wfFindFile( $this->mTitle
);
706 * Check if this is result points to an invalid title
710 function isBrokenTitle() {
711 if ( is_null( $this->mTitle
) )
717 * Check if target page is missing, happens when index is out of date
721 function isMissingRevision() {
722 return !$this->mRevision
&& !$this->mImage
;
728 function getTitle() {
729 return $this->mTitle
;
733 * @return Double or null if not supported
735 function getScore() {
740 * Lazy initialization of article text from DB
742 protected function initText() {
743 if ( !isset( $this->mText
) ) {
744 if ( $this->mRevision
!= null )
745 $this->mText
= $this->mRevision
->getText();
746 else // TODO: can we fetch raw wikitext for commons images?
753 * @param $terms Array: terms to highlight
754 * @return String: highlighted text snippet, null (and not '') if not supported
756 function getTextSnippet( $terms ) {
757 global $wgUser, $wgAdvancedSearchHighlighting;
759 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
760 $h = new SearchHighlighter();
761 if ( $wgAdvancedSearchHighlighting )
762 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
764 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
768 * @param $terms Array: terms to highlight
769 * @return String: highlighted title, '' if not supported
771 function getTitleSnippet( $terms ) {
776 * @param $terms Array: terms to highlight
777 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
779 function getRedirectSnippet( $terms ) {
784 * @return Title object for the redirect to this page, null if none or not supported
786 function getRedirectTitle() {
791 * @return string highlighted relevant section name, null if none or not supported
793 function getSectionSnippet() {
798 * @return Title object (pagename+fragment) for the section, null if none or not supported
800 function getSectionTitle() {
805 * @return String: timestamp
807 function getTimestamp() {
808 if ( $this->mRevision
)
809 return $this->mRevision
->getTimestamp();
810 else if ( $this->mImage
)
811 return $this->mImage
->getTimestamp();
816 * @return Integer: number of words
818 function getWordCount() {
820 return str_word_count( $this->mText
);
824 * @return Integer: size in bytes
826 function getByteSize() {
828 return strlen( $this->mText
);
832 * @return Boolean if hit has related articles
834 function hasRelated() {
839 * @return String: interwiki prefix of the title (return iw even if title is broken)
841 function getInterwikiPrefix() {
846 * A SearchResultSet wrapper for SearchEngine::getNearMatch
848 class SearchNearMatchResultSet
extends SearchResultSet
{
849 private $fetched = false;
851 * @param $match mixed Title if matched, else null
853 public function __construct( $match ) {
854 $this->result
= $match;
856 public function hasResult() {
857 return (bool)$this->result
;
859 public function numRows() {
860 return $this->hasResults() ?
1 : 0;
862 public function next() {
863 if ( $this->fetched ||
!$this->result
) {
866 $this->fetched
= true;
867 return SearchResult
::newFromTitle( $this->result
);
872 * Highlight bits of wikitext
876 class SearchHighlighter
{
877 var $mCleanWikitext = true;
879 function __construct( $cleanupWikitext = true ) {
880 $this->mCleanWikitext
= $cleanupWikitext;
884 * Default implementation of wikitext highlighting
886 * @param $text String
887 * @param $terms Array: terms to highlight (unescaped)
888 * @param $contextlines Integer
889 * @param $contextchars Integer
892 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
894 global $wgSearchHighlightBoundaries;
900 // spli text into text + templates/links/tables
901 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
902 // first capture group is for detecting nested templates/links/tables/references
903 $endPatterns = array(
904 1 => '/(\{\{)|(\}\})/', // template
905 2 => '/(\[\[)|(\]\])/', // image
906 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
908 // FIXME: this should prolly be a hook or something
909 if ( function_exists( 'wfCite' ) ) {
910 $spat .= '|(<ref>)'; // references via cite extension
911 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
914 $textExt = array(); // text extracts
915 $otherExt = array(); // other extracts
916 wfProfileIn( "$fname-split" );
918 $textLen = strlen( $text );
919 $count = 0; // sequence number to maintain ordering
920 while ( $start < $textLen ) {
921 // find start of template/image/table
922 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
924 foreach ( $matches as $key => $val ) {
925 if ( $key > 0 && $val[1] != - 1 ) {
927 // see if this is an image link
928 $ns = substr( $val[0], 2, - 1 );
929 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
)
933 $epat = $endPatterns[$key];
934 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
940 // find end (and detect any nested elements)
942 $offset = $start +
1;
944 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
945 if ( array_key_exists( 2, $endMatches ) ) {
948 $len = strlen( $endMatches[2][0] );
949 $off = $endMatches[2][1];
950 $this->splitAndAdd( $otherExt, $count,
951 substr( $text, $start, $off +
$len - $start ) );
952 $start = $off +
$len;
956 // end of nested element
963 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
966 // couldn't find appropriate closing tag, skip
967 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
968 $start +
= strlen( $matches[0][0] );
973 // else: add as text extract
974 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
978 $all = $textExt +
$otherExt; // these have disjunct key sets
980 wfProfileOut( "$fname-split" );
983 foreach ( $terms as $index => $term ) {
984 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
985 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
986 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
988 $terms[$index] = $term;
991 $anyterm = implode( '|', $terms );
992 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
994 // FIXME: a hack to scale contextchars, a correct solution
995 // would be to have contextchars actually be char and not byte
996 // length, and do proper utf-8 substrings and lengths everywhere,
997 // but PHP is making that very hard and unclean to implement :(
998 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
999 $contextchars = intval( $contextchars * $scale );
1001 $patPre = "(^|$wgSearchHighlightBoundaries)";
1002 $patPost = "($wgSearchHighlightBoundaries|$)";
1004 $pat1 = "/(" . $phrase . ")/ui";
1005 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1007 wfProfileIn( "$fname-extract" );
1009 $left = $contextlines;
1011 $snippets = array();
1014 // show beginning only if it contains all words
1017 foreach ( $textExt as $index => $line ) {
1018 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1019 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1026 // check if first text contains all terms
1027 foreach ( $terms as $term ) {
1028 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1034 $snippets[$first] = $firstText;
1035 $offsets[$first] = 0;
1038 if ( ! $snippets ) {
1039 // match whole query on text
1040 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1041 // match whole query on templates/tables/images
1042 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1043 // match any words on text
1044 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1045 // match any words on templates/tables/images
1046 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1051 // add extra chars to each snippet to make snippets constant size
1052 $extended = array();
1053 if ( count( $snippets ) == 0 ) {
1054 // couldn't find the target words, just show beginning of article
1055 if ( array_key_exists( $first, $all ) ) {
1056 $targetchars = $contextchars * $contextlines;
1057 $snippets[$first] = '';
1058 $offsets[$first] = 0;
1061 // if begin of the article contains the whole phrase, show only that !!
1062 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1063 && $offsets[$first] < $contextchars * 2 ) {
1064 $snippets = array ( $first => $snippets[$first] );
1067 // calc by how much to extend existing snippets
1068 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1071 foreach ( $snippets as $index => $line ) {
1072 $extended[$index] = $line;
1073 $len = strlen( $line );
1074 if ( $len < $targetchars - 20 ) {
1075 // complete this line
1076 if ( $len < strlen( $all[$index] ) ) {
1077 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1078 $len = strlen( $extended[$index] );
1083 while ( $len < $targetchars - 20
1084 && array_key_exists( $add, $all )
1085 && !array_key_exists( $add, $snippets ) ) {
1087 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1088 $extended[$add] = $tt;
1089 $len +
= strlen( $tt );
1095 // $snippets = array_map('htmlspecialchars', $extended);
1096 $snippets = $extended;
1099 foreach ( $snippets as $index => $line ) {
1101 $extract .= $line; // first line
1102 elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1103 $extract .= " " . $line; // continous lines
1105 $extract .= '<b> ... </b>' . $line;
1110 $extract .= '<b> ... </b>';
1112 $processed = array();
1113 foreach ( $terms as $term ) {
1114 if ( ! isset( $processed[$term] ) ) {
1115 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1116 $extract = preg_replace( $pat3,
1117 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1118 $processed[$term] = true;
1122 wfProfileOut( "$fname-extract" );
1128 * Split text into lines and add it to extracts array
1130 * @param $extracts Array: index -> $line
1131 * @param $count Integer
1132 * @param $text String
1134 function splitAndAdd( &$extracts, &$count, $text ) {
1135 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1136 foreach ( $split as $line ) {
1137 $tt = trim( $line );
1139 $extracts[$count++
] = $tt;
1144 * Do manual case conversion for non-ascii chars
1146 * @param $matches Array
1148 function caseCallback( $matches ) {
1150 if ( strlen( $matches[0] ) > 1 ) {
1151 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1157 * Extract part of the text from start to end, but by
1158 * not chopping up words
1159 * @param $text String
1160 * @param $start Integer
1161 * @param $end Integer
1162 * @param $posStart Integer: (out) actual start position
1163 * @param $posEnd Integer: (out) actual end position
1166 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1168 $start = $this->position( $text, $start, 1 );
1169 if ( $end >= strlen( $text ) )
1170 $end = strlen( $text );
1172 $end = $this->position( $text, $end );
1174 if ( !is_null( $posStart ) )
1176 if ( !is_null( $posEnd ) )
1179 if ( $end > $start )
1180 return substr( $text, $start, $end - $start );
1186 * Find a nonletter near a point (index) in the text
1188 * @param $text String
1189 * @param $point Integer
1190 * @param $offset Integer: offset to found index
1191 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1193 function position( $text, $point, $offset = 0 ) {
1195 $s = max( 0, $point - $tolerance );
1196 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1198 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1199 return $m[0][1] +
$s +
$offset;
1201 // check if point is on a valid first UTF8 char
1202 $char = ord( $text[$point] );
1203 while ( $char >= 0x80 && $char < 0xc0 ) {
1204 // skip trailing bytes
1206 if ( $point >= strlen( $text ) )
1207 return strlen( $text );
1208 $char = ord( $text[$point] );
1216 * Search extracts for a pattern, and return snippets
1218 * @param $pattern String: regexp for matching lines
1219 * @param $extracts Array: extracts to search
1220 * @param $linesleft Integer: number of extracts to make
1221 * @param $contextchars Integer: length of snippet
1222 * @param $out Array: map for highlighted snippets
1223 * @param $offsets Array: map of starting points of snippets
1226 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1227 if ( $linesleft == 0 )
1228 return; // nothing to do
1229 foreach ( $extracts as $index => $line ) {
1230 if ( array_key_exists( $index, $out ) )
1231 continue; // this line already highlighted
1234 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1238 $len = strlen( $m[0][0] );
1239 if ( $offset +
$len < $contextchars )
1241 elseif ( $len > $contextchars )
1244 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1246 $end = $begin +
$contextchars;
1249 // basic snippet from this line
1250 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1251 $offsets[$index] = $posBegin;
1253 if ( $linesleft == 0 )
1259 * Basic wikitext removal
1262 function removeWiki( $text ) {
1263 $fname = __METHOD__
;
1264 wfProfileIn( $fname );
1266 // $text = preg_replace("/'{2,5}/", "", $text);
1267 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1268 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1269 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1270 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1271 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1272 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1273 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1274 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1275 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1276 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1277 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1278 $text = preg_replace( "/'''''/", "", $text );
1279 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1280 $text = preg_replace( "/''/", "", $text );
1282 wfProfileOut( $fname );
1287 * callback to replace [[target|caption]] kind of links, if
1288 * the target is category or image, leave it
1290 * @param $matches Array
1292 function linkReplace( $matches ) {
1293 $colon = strpos( $matches[1], ':' );
1294 if ( $colon === false )
1295 return $matches[2]; // replace with caption
1297 $ns = substr( $matches[1], 0, $colon );
1298 $index = $wgContLang->getNsIndex( $ns );
1299 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) )
1300 return $matches[0]; // return the whole thing
1307 * Simple & fast snippet extraction, but gives completely unrelevant
1310 * @param $text String
1311 * @param $terms Array
1312 * @param $contextlines Integer
1313 * @param $contextchars Integer
1316 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1318 $fname = __METHOD__
;
1320 $lines = explode( "\n", $text );
1322 $terms = implode( '|', $terms );
1323 $max = intval( $contextchars ) +
1;
1324 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1329 wfProfileIn( "$fname-extract" );
1330 foreach ( $lines as $line ) {
1331 if ( 0 == $contextlines ) {
1336 if ( ! preg_match( $pat1, $line, $m ) ) {
1340 // truncate function changes ... to relevant i18n message.
1341 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1343 if ( count( $m ) < 3 ) {
1346 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1351 $line = htmlspecialchars( $pre . $found . $post );
1352 $pat2 = '/(' . $terms . ")/i";
1353 $line = preg_replace( $pat2,
1354 "<span class='searchmatch'>\\1</span>", $line );
1356 $extract .= "${line}\n";
1358 wfProfileOut( "$fname-extract" );
1366 * Dummy class to be used when non-supported Database engine is present.
1367 * @todo Fixme: dummy class should probably try something at least mildly useful,
1368 * such as a LIKE search through titles.
1371 class SearchEngineDummy
extends SearchEngine
{