0a4b7c56d143c4b45d269466dea01e09abf75e33
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;
25 function __construct($db = null) {
29 $this->db
= wfGetDB( DB_SLAVE
);
34 * Perform a full text 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 searchText( $term ) {
46 * Perform a title-only search query and return a result set.
47 * If title searches are not supported or disabled, return null.
50 * @param $term String: raw search term
51 * @return SearchResultSet
53 function searchTitle( $term ) {
57 /** If this search backend can list/unlist redirects */
58 function acceptListRedirects() {
63 * When overridden in derived class, performs database-specific conversions
64 * on text to be used for searching or updating search index.
65 * Default implementation does nothing (simply returns $string).
67 * @param $string string: String to process
70 public function normalizeText( $string ) {
73 // Some languages such as Chinese require word segmentation
74 return $wgContLang->segmentByWord( $string );
78 * Transform search term in cases when parts of the query came as different GET params (when supported)
79 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
81 function transformSearchTerm( $term ) {
86 * If an exact title match can be found, or a very slightly close match,
87 * return the title. If no match, returns NULL.
89 * @param $searchterm String
92 public static function getNearMatch( $searchterm ) {
93 $title = self
::getNearMatchInternal( $searchterm );
95 wfRunHooks( 'SpecialSearchGomatch', array( &$title ) );
97 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
102 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
105 * @param $searchterm string
106 * @return SearchResultSet
108 public static function getNearMatchResultSet( $searchterm ) {
109 return new SearchNearMatchResultSet( self
::getNearMatch( $searchterm ) );
113 * Really find the title match.
115 private static function getNearMatchInternal( $searchterm ) {
118 $allSearchTerms = array( $searchterm );
120 if ( $wgContLang->hasVariants() ) {
121 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
125 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
129 foreach ( $allSearchTerms as $term ) {
131 # Exact match? No need to look further.
132 $title = Title
::newFromText( $term );
133 if ( is_null( $title ) )
136 if ( $title->getNamespace() == NS_SPECIAL ||
$title->isExternal() ||
$title->exists() ) {
140 # See if it still otherwise has content is some sane sense
141 $article = MediaWiki
::articleFromTitle( $title );
142 if ( $article->hasViewableContent() ) {
146 # Now try all lower case (i.e. first letter capitalized)
148 $title = Title
::newFromText( $wgContLang->lc( $term ) );
149 if ( $title && $title->exists() ) {
153 # Now try capitalized string
155 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
156 if ( $title && $title->exists() ) {
160 # Now try all upper case
162 $title = Title
::newFromText( $wgContLang->uc( $term ) );
163 if ( $title && $title->exists() ) {
167 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
168 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
169 if ( $title && $title->exists() ) {
173 // Give hooks a chance at better match variants
175 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
180 $title = Title
::newFromText( $searchterm );
182 # Entering an IP address goes to the contributions page
183 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
184 || User
::isIP( trim( $searchterm ) ) ) {
185 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
189 # Entering a user goes to the user page whether it's there or not
190 if ( $title->getNamespace() == NS_USER
) {
194 # Go to images that exist even if there's no local page.
195 # There may have been a funny upload, or it may be on a shared
196 # file repository such as Wikimedia Commons.
197 if ( $title->getNamespace() == NS_FILE
) {
198 $image = wfFindFile( $title );
204 # MediaWiki namespace? Page may be "implied" if not customized.
205 # Just return it, with caps forced as the message system likes it.
206 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
207 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
210 # Quoted term? Try without the quotes...
212 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
213 return SearchEngine
::getNearMatch( $matches[1] );
219 public static function legalSearchChars() {
220 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
224 * Set the maximum number of results to return
225 * and how many to skip before returning the first.
227 * @param $limit Integer
228 * @param $offset Integer
230 function setLimitOffset( $limit, $offset = 0 ) {
231 $this->limit
= intval( $limit );
232 $this->offset
= intval( $offset );
236 * Set which namespaces the search should include.
237 * Give an array of namespace index numbers.
239 * @param $namespaces Array
241 function setNamespaces( $namespaces ) {
242 $this->namespaces
= $namespaces;
246 * Parse some common prefixes: all (search everything)
249 * @param $query String
251 function replacePrefixes( $query ) {
255 if ( strpos( $query, ':' ) === false ) { // nothing to do
256 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
260 $allkeyword = wfMsgForContent( 'searchall' ) . ":";
261 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
262 $this->namespaces
= null;
263 $parsed = substr( $query, strlen( $allkeyword ) );
264 } else if ( strpos( $query, ':' ) !== false ) {
265 $prefix = substr( $query, 0, strpos( $query, ':' ) );
266 $index = $wgContLang->getNsIndex( $prefix );
267 if ( $index !== false ) {
268 $this->namespaces
= array( $index );
269 $parsed = substr( $query, strlen( $prefix ) +
1 );
272 if ( trim( $parsed ) == '' )
273 $parsed = $query; // prefix was the whole query
275 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
281 * Make a list of searchable namespaces and their canonical names.
284 public static function searchableNamespaces() {
287 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
288 if ( $ns >= NS_MAIN
) {
293 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
298 * Extract default namespaces to search from the given user's
299 * settings, returning a list of index numbers.
304 public static function userNamespaces( $user ) {
305 global $wgSearchEverythingOnlyLoggedIn;
307 // get search everything preference, that can be set to be read for logged-in users
308 $searcheverything = false;
309 if ( ( $wgSearchEverythingOnlyLoggedIn && $user->isLoggedIn() )
310 ||
!$wgSearchEverythingOnlyLoggedIn )
311 $searcheverything = $user->getOption( 'searcheverything' );
313 // searcheverything overrides other options
314 if ( $searcheverything )
315 return array_keys( SearchEngine
::searchableNamespaces() );
317 $arr = Preferences
::loadOldSearchNs( $user );
318 $searchableNamespaces = SearchEngine
::searchableNamespaces();
320 $arr = array_intersect( $arr, array_keys( $searchableNamespaces ) ); // Filter
326 * Find snippet highlight settings for a given user
329 * @return Array contextlines, contextchars
331 public static function userHighlightPrefs( &$user ) {
332 // $contextlines = $user->getOption( 'contextlines', 5 );
333 // $contextchars = $user->getOption( 'contextchars', 50 );
334 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
335 $contextchars = 75; // same as above.... :P
336 return array( $contextlines, $contextchars );
340 * An array of namespaces indexes to be searched by default
344 public static function defaultNamespaces() {
345 global $wgNamespacesToBeSearchedDefault;
347 return array_keys( $wgNamespacesToBeSearchedDefault, true );
351 * Get a list of namespace names useful for showing in tooltips
354 * @param $namespaces Array
356 public static function namespacesAsText( $namespaces ) {
359 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
360 foreach ( $formatted as $key => $ns ) {
362 $formatted[$key] = wfMsg( 'blanknamespace' );
368 * Return the help namespaces to be shown on Special:Search
372 public static function helpNamespaces() {
373 global $wgNamespacesToBeSearchedHelp;
375 return array_keys( $wgNamespacesToBeSearchedHelp, true );
379 * Return a 'cleaned up' search string
381 * @param $text String
384 function filter( $text ) {
385 $lc = $this->legalSearchChars();
386 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
389 * Load up the appropriate search engine class for the currently
390 * active database backend, and return a configured instance.
392 * @return SearchEngine
394 public static function create() {
395 global $wgSearchType;
397 if ( $wgSearchType ) {
398 $class = $wgSearchType;
400 $dbr = wfGetDB( DB_SLAVE
);
401 $class = $dbr->getSearchEngine();
403 $search = new $class( $dbr );
404 $search->setLimitOffset( 0, 0 );
409 * Create or update the search index record for the given page.
410 * Title and text should be pre-processed.
414 * @param $title String
415 * @param $text String
417 function update( $id, $title, $text ) {
422 * Update a search index record's title only.
423 * Title should be pre-processed.
427 * @param $title String
429 function updateTitle( $id, $title ) {
434 * Get OpenSearch suggestion template
438 public static function getOpenSearchTemplate() {
439 global $wgOpenSearchTemplate, $wgServer, $wgScriptPath;
440 if ( $wgOpenSearchTemplate ) {
441 return $wgOpenSearchTemplate;
443 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
444 if ( !$ns ) $ns = "0";
445 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace=' . $ns;
450 * Get internal MediaWiki Suggest template
454 public static function getMWSuggestTemplate() {
455 global $wgMWSuggestTemplate, $wgServer, $wgScriptPath;
456 if ( $wgMWSuggestTemplate )
457 return $wgMWSuggestTemplate;
459 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
466 class SearchResultSet
{
468 * Fetch an array of regular expression fragments for matching
469 * the search terms as parsed by this engine in a text extract.
474 function termMatches() {
483 * Return true if results are included in this result set.
488 function hasResults() {
493 * Some search modes return a total hit count for the query
494 * in the entire article database. This may include pages
495 * in namespaces that would not be matched on the given
498 * Return null if no total hits number is supported.
502 function getTotalHits() {
507 * Some search modes return a suggested alternate term if there are
508 * no exact hits. Returns true if there is one on this set.
512 function hasSuggestion() {
517 * @return String: suggested query, null if none
519 function getSuggestionQuery() {
524 * @return String: HTML highlighted suggested query, '' if none
526 function getSuggestionSnippet() {
531 * Return information about how and from where the results were fetched,
532 * should be useful for diagnostics and debugging
541 * Return a result set of hits on other (multiple) wikis associated with this one
543 * @return SearchResultSet
545 function getInterwikiResults() {
550 * Check if there are results on other wikis
554 function hasInterwikiResults() {
555 return $this->getInterwikiResults() != null;
559 * Fetches next search result, or false.
562 * @return SearchResult
569 * Frees the result set, if applicable.
577 * This class is used for different SQL-based search engines shipped with MediaWiki
579 class SqlSearchResultSet
extends SearchResultSet
{
580 function __construct( $resultSet, $terms ) {
581 $this->mResultSet
= $resultSet;
582 $this->mTerms
= $terms;
585 function termMatches() {
586 return $this->mTerms
;
590 if ( $this->mResultSet
=== false )
593 return $this->mResultSet
->numRows();
597 if ( $this->mResultSet
=== false )
600 $row = $this->mResultSet
->fetchObject();
601 if ( $row === false )
604 return SearchResult
::newFromRow( $row );
608 if ( $this->mResultSet
=== false )
611 $this->mResultSet
->free();
618 class SearchResultTooMany
{
619 # # Some search engines may bail out if too many matches are found
624 * @todo Fixme: This class is horribly factored. It would probably be better to
625 * have a useful base class to which you pass some standard information, then
626 * let the fancy self-highlighters extend that.
630 var $mRevision = null;
634 * Return a new SearchResult and initializes it with a title.
636 * @param $title Title
637 * @return SearchResult
639 public static function newFromTitle( $title ) {
640 $result = new self();
641 $result->initFromTitle( $title );
645 * Return a new SearchResult and initializes it with a row.
648 * @return SearchResult
650 public static function newFromRow( $row ) {
651 $result = new self();
652 $result->initFromRow( $row );
656 public function __construct( $row = null ) {
657 if ( !is_null( $row ) ) {
658 // Backwards compatibility with pre-1.17 callers
659 $this->initFromRow( $row );
664 * Initialize from a database row. Makes a Title and passes that to
669 protected function initFromRow( $row ) {
670 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
674 * Initialize from a Title and if possible initializes a corresponding
677 * @param $title Title
679 protected function initFromTitle( $title ) {
680 $this->mTitle
= $title;
681 if ( !is_null( $this->mTitle
) ) {
682 $this->mRevision
= Revision
::newFromTitle( $this->mTitle
);
683 if ( $this->mTitle
->getNamespace() === NS_FILE
)
684 $this->mImage
= wfFindFile( $this->mTitle
);
689 * Check if this is result points to an invalid title
693 function isBrokenTitle() {
694 if ( is_null( $this->mTitle
) )
700 * Check if target page is missing, happens when index is out of date
704 function isMissingRevision() {
705 return !$this->mRevision
&& !$this->mImage
;
711 function getTitle() {
712 return $this->mTitle
;
716 * @return Double or null if not supported
718 function getScore() {
723 * Lazy initialization of article text from DB
725 protected function initText() {
726 if ( !isset( $this->mText
) ) {
727 if ( $this->mRevision
!= null )
728 $this->mText
= $this->mRevision
->getText();
729 else // TODO: can we fetch raw wikitext for commons images?
736 * @param $terms Array: terms to highlight
737 * @return String: highlighted text snippet, null (and not '') if not supported
739 function getTextSnippet( $terms ) {
740 global $wgUser, $wgAdvancedSearchHighlighting;
742 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
743 $h = new SearchHighlighter();
744 if ( $wgAdvancedSearchHighlighting )
745 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
747 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
751 * @param $terms Array: terms to highlight
752 * @return String: highlighted title, '' if not supported
754 function getTitleSnippet( $terms ) {
759 * @param $terms Array: terms to highlight
760 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
762 function getRedirectSnippet( $terms ) {
767 * @return Title object for the redirect to this page, null if none or not supported
769 function getRedirectTitle() {
774 * @return string highlighted relevant section name, null if none or not supported
776 function getSectionSnippet() {
781 * @return Title object (pagename+fragment) for the section, null if none or not supported
783 function getSectionTitle() {
788 * @return String: timestamp
790 function getTimestamp() {
791 if ( $this->mRevision
)
792 return $this->mRevision
->getTimestamp();
793 else if ( $this->mImage
)
794 return $this->mImage
->getTimestamp();
799 * @return Integer: number of words
801 function getWordCount() {
803 return str_word_count( $this->mText
);
807 * @return Integer: size in bytes
809 function getByteSize() {
811 return strlen( $this->mText
);
815 * @return Boolean if hit has related articles
817 function hasRelated() {
822 * @return String: interwiki prefix of the title (return iw even if title is broken)
824 function getInterwikiPrefix() {
829 * A SearchResultSet wrapper for SearchEngine::getNearMatch
831 class SearchNearMatchResultSet
extends SearchResultSet
{
832 private $fetched = false;
834 * @param $match mixed Title if matched, else null
836 public function __construct( $match ) {
837 $this->result
= $match;
839 public function hasResult() {
840 return (bool)$this->result
;
842 public function numRows() {
843 return $this->hasResults() ?
1 : 0;
845 public function next() {
846 if ( $this->fetched ||
!$this->result
) {
849 $this->fetched
= true;
850 return SearchResult
::newFromTitle( $this->result
);
855 * Highlight bits of wikitext
859 class SearchHighlighter
{
860 var $mCleanWikitext = true;
862 function __construct( $cleanupWikitext = true ) {
863 $this->mCleanWikitext
= $cleanupWikitext;
867 * Default implementation of wikitext highlighting
869 * @param $text String
870 * @param $terms Array: terms to highlight (unescaped)
871 * @param $contextlines Integer
872 * @param $contextchars Integer
875 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
877 global $wgSearchHighlightBoundaries;
883 // spli text into text + templates/links/tables
884 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
885 // first capture group is for detecting nested templates/links/tables/references
886 $endPatterns = array(
887 1 => '/(\{\{)|(\}\})/', // template
888 2 => '/(\[\[)|(\]\])/', // image
889 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
891 // FIXME: this should prolly be a hook or something
892 if ( function_exists( 'wfCite' ) ) {
893 $spat .= '|(<ref>)'; // references via cite extension
894 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
897 $textExt = array(); // text extracts
898 $otherExt = array(); // other extracts
899 wfProfileIn( "$fname-split" );
901 $textLen = strlen( $text );
902 $count = 0; // sequence number to maintain ordering
903 while ( $start < $textLen ) {
904 // find start of template/image/table
905 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
907 foreach ( $matches as $key => $val ) {
908 if ( $key > 0 && $val[1] != - 1 ) {
910 // see if this is an image link
911 $ns = substr( $val[0], 2, - 1 );
912 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
)
916 $epat = $endPatterns[$key];
917 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
923 // find end (and detect any nested elements)
925 $offset = $start +
1;
927 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
928 if ( array_key_exists( 2, $endMatches ) ) {
931 $len = strlen( $endMatches[2][0] );
932 $off = $endMatches[2][1];
933 $this->splitAndAdd( $otherExt, $count,
934 substr( $text, $start, $off +
$len - $start ) );
935 $start = $off +
$len;
939 // end of nested element
946 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
949 // couldn't find appropriate closing tag, skip
950 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
951 $start +
= strlen( $matches[0][0] );
956 // else: add as text extract
957 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
961 $all = $textExt +
$otherExt; // these have disjunct key sets
963 wfProfileOut( "$fname-split" );
966 foreach ( $terms as $index => $term ) {
967 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
968 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
969 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
971 $terms[$index] = $term;
974 $anyterm = implode( '|', $terms );
975 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
977 // FIXME: a hack to scale contextchars, a correct solution
978 // would be to have contextchars actually be char and not byte
979 // length, and do proper utf-8 substrings and lengths everywhere,
980 // but PHP is making that very hard and unclean to implement :(
981 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
982 $contextchars = intval( $contextchars * $scale );
984 $patPre = "(^|$wgSearchHighlightBoundaries)";
985 $patPost = "($wgSearchHighlightBoundaries|$)";
987 $pat1 = "/(" . $phrase . ")/ui";
988 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
990 wfProfileIn( "$fname-extract" );
992 $left = $contextlines;
997 // show beginning only if it contains all words
1000 foreach ( $textExt as $index => $line ) {
1001 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1002 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1009 // check if first text contains all terms
1010 foreach ( $terms as $term ) {
1011 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1017 $snippets[$first] = $firstText;
1018 $offsets[$first] = 0;
1021 if ( ! $snippets ) {
1022 // match whole query on text
1023 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1024 // match whole query on templates/tables/images
1025 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1026 // match any words on text
1027 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1028 // match any words on templates/tables/images
1029 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1034 // add extra chars to each snippet to make snippets constant size
1035 $extended = array();
1036 if ( count( $snippets ) == 0 ) {
1037 // couldn't find the target words, just show beginning of article
1038 if ( array_key_exists( $first, $all ) ) {
1039 $targetchars = $contextchars * $contextlines;
1040 $snippets[$first] = '';
1041 $offsets[$first] = 0;
1044 // if begin of the article contains the whole phrase, show only that !!
1045 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1046 && $offsets[$first] < $contextchars * 2 ) {
1047 $snippets = array ( $first => $snippets[$first] );
1050 // calc by how much to extend existing snippets
1051 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1054 foreach ( $snippets as $index => $line ) {
1055 $extended[$index] = $line;
1056 $len = strlen( $line );
1057 if ( $len < $targetchars - 20 ) {
1058 // complete this line
1059 if ( $len < strlen( $all[$index] ) ) {
1060 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1061 $len = strlen( $extended[$index] );
1066 while ( $len < $targetchars - 20
1067 && array_key_exists( $add, $all )
1068 && !array_key_exists( $add, $snippets ) ) {
1070 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1071 $extended[$add] = $tt;
1072 $len +
= strlen( $tt );
1078 // $snippets = array_map('htmlspecialchars', $extended);
1079 $snippets = $extended;
1082 foreach ( $snippets as $index => $line ) {
1084 $extract .= $line; // first line
1085 elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1086 $extract .= " " . $line; // continous lines
1088 $extract .= '<b> ... </b>' . $line;
1093 $extract .= '<b> ... </b>';
1095 $processed = array();
1096 foreach ( $terms as $term ) {
1097 if ( ! isset( $processed[$term] ) ) {
1098 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1099 $extract = preg_replace( $pat3,
1100 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1101 $processed[$term] = true;
1105 wfProfileOut( "$fname-extract" );
1111 * Split text into lines and add it to extracts array
1113 * @param $extracts Array: index -> $line
1114 * @param $count Integer
1115 * @param $text String
1117 function splitAndAdd( &$extracts, &$count, $text ) {
1118 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1119 foreach ( $split as $line ) {
1120 $tt = trim( $line );
1122 $extracts[$count++
] = $tt;
1127 * Do manual case conversion for non-ascii chars
1129 * @param $matches Array
1131 function caseCallback( $matches ) {
1133 if ( strlen( $matches[0] ) > 1 ) {
1134 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1140 * Extract part of the text from start to end, but by
1141 * not chopping up words
1142 * @param $text String
1143 * @param $start Integer
1144 * @param $end Integer
1145 * @param $posStart Integer: (out) actual start position
1146 * @param $posEnd Integer: (out) actual end position
1149 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1151 $start = $this->position( $text, $start, 1 );
1152 if ( $end >= strlen( $text ) )
1153 $end = strlen( $text );
1155 $end = $this->position( $text, $end );
1157 if ( !is_null( $posStart ) )
1159 if ( !is_null( $posEnd ) )
1162 if ( $end > $start )
1163 return substr( $text, $start, $end - $start );
1169 * Find a nonletter near a point (index) in the text
1171 * @param $text String
1172 * @param $point Integer
1173 * @param $offset Integer: offset to found index
1174 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1176 function position( $text, $point, $offset = 0 ) {
1178 $s = max( 0, $point - $tolerance );
1179 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1181 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1182 return $m[0][1] +
$s +
$offset;
1184 // check if point is on a valid first UTF8 char
1185 $char = ord( $text[$point] );
1186 while ( $char >= 0x80 && $char < 0xc0 ) {
1187 // skip trailing bytes
1189 if ( $point >= strlen( $text ) )
1190 return strlen( $text );
1191 $char = ord( $text[$point] );
1199 * Search extracts for a pattern, and return snippets
1201 * @param $pattern String: regexp for matching lines
1202 * @param $extracts Array: extracts to search
1203 * @param $linesleft Integer: number of extracts to make
1204 * @param $contextchars Integer: length of snippet
1205 * @param $out Array: map for highlighted snippets
1206 * @param $offsets Array: map of starting points of snippets
1209 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1210 if ( $linesleft == 0 )
1211 return; // nothing to do
1212 foreach ( $extracts as $index => $line ) {
1213 if ( array_key_exists( $index, $out ) )
1214 continue; // this line already highlighted
1217 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1221 $len = strlen( $m[0][0] );
1222 if ( $offset +
$len < $contextchars )
1224 elseif ( $len > $contextchars )
1227 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1229 $end = $begin +
$contextchars;
1232 // basic snippet from this line
1233 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1234 $offsets[$index] = $posBegin;
1236 if ( $linesleft == 0 )
1242 * Basic wikitext removal
1245 function removeWiki( $text ) {
1246 $fname = __METHOD__
;
1247 wfProfileIn( $fname );
1249 // $text = preg_replace("/'{2,5}/", "", $text);
1250 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1251 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1252 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1253 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1254 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1255 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1256 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1257 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1258 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1259 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1260 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1261 $text = preg_replace( "/'''''/", "", $text );
1262 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1263 $text = preg_replace( "/''/", "", $text );
1265 wfProfileOut( $fname );
1270 * callback to replace [[target|caption]] kind of links, if
1271 * the target is category or image, leave it
1273 * @param $matches Array
1275 function linkReplace( $matches ) {
1276 $colon = strpos( $matches[1], ':' );
1277 if ( $colon === false )
1278 return $matches[2]; // replace with caption
1280 $ns = substr( $matches[1], 0, $colon );
1281 $index = $wgContLang->getNsIndex( $ns );
1282 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) )
1283 return $matches[0]; // return the whole thing
1290 * Simple & fast snippet extraction, but gives completely unrelevant
1293 * @param $text String
1294 * @param $terms Array
1295 * @param $contextlines Integer
1296 * @param $contextchars Integer
1299 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1301 $fname = __METHOD__
;
1303 $lines = explode( "\n", $text );
1305 $terms = implode( '|', $terms );
1306 $max = intval( $contextchars ) +
1;
1307 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1312 wfProfileIn( "$fname-extract" );
1313 foreach ( $lines as $line ) {
1314 if ( 0 == $contextlines ) {
1319 if ( ! preg_match( $pat1, $line, $m ) ) {
1323 $pre = $wgContLang->truncate( $m[1], - $contextchars );
1325 if ( count( $m ) < 3 ) {
1328 $post = $wgContLang->truncate( $m[3], $contextchars );
1333 $line = htmlspecialchars( $pre . $found . $post );
1334 $pat2 = '/(' . $terms . ")/i";
1335 $line = preg_replace( $pat2,
1336 "<span class='searchmatch'>\\1</span>", $line );
1338 $extract .= "${line}\n";
1340 wfProfileOut( "$fname-extract" );
1348 * Dummy class to be used when non-supported Database engine is present.
1349 * @todo Fixme: dummy class should probably try something at least mildly useful,
1350 * such as a LIKE search through titles.
1353 class SearchEngineDummy
extends SearchEngine
{