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( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
100 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
103 * @param $searchterm string
104 * @return SearchResultSet
106 public static function getNearMatchResultSet( $searchterm ) {
107 return new SearchNearMatchResultSet( self
::getNearMatch( $searchterm ) );
111 * Really find the title match.
113 private static function getNearMatchInternal( $searchterm ) {
116 $allSearchTerms = array( $searchterm );
118 if ( $wgContLang->hasVariants() ) {
119 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
123 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
127 foreach ( $allSearchTerms as $term ) {
129 # Exact match? No need to look further.
130 $title = Title
::newFromText( $term );
131 if ( is_null( $title ) )
134 if ( $title->getNamespace() == NS_SPECIAL ||
$title->isExternal() ||
$title->exists() ) {
138 # See if it still otherwise has content is some sane sense
139 $article = MediaWiki
::articleFromTitle( $title );
140 if ( $article->hasViewableContent() ) {
144 # Now try all lower case (i.e. first letter capitalized)
146 $title = Title
::newFromText( $wgContLang->lc( $term ) );
147 if ( $title && $title->exists() ) {
151 # Now try capitalized string
153 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
154 if ( $title && $title->exists() ) {
158 # Now try all upper case
160 $title = Title
::newFromText( $wgContLang->uc( $term ) );
161 if ( $title && $title->exists() ) {
165 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
166 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
167 if ( $title && $title->exists() ) {
171 // Give hooks a chance at better match variants
173 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
178 $title = Title
::newFromText( $searchterm );
180 # Entering an IP address goes to the contributions page
181 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
182 || User
::isIP( trim( $searchterm ) ) ) {
183 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
187 # Entering a user goes to the user page whether it's there or not
188 if ( $title->getNamespace() == NS_USER
) {
192 # Go to images that exist even if there's no local page.
193 # There may have been a funny upload, or it may be on a shared
194 # file repository such as Wikimedia Commons.
195 if ( $title->getNamespace() == NS_FILE
) {
196 $image = wfFindFile( $title );
202 # MediaWiki namespace? Page may be "implied" if not customized.
203 # Just return it, with caps forced as the message system likes it.
204 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
205 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
208 # Quoted term? Try without the quotes...
210 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
211 return SearchEngine
::getNearMatch( $matches[1] );
217 public static function legalSearchChars() {
218 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
222 * Set the maximum number of results to return
223 * and how many to skip before returning the first.
225 * @param $limit Integer
226 * @param $offset Integer
228 function setLimitOffset( $limit, $offset = 0 ) {
229 $this->limit
= intval( $limit );
230 $this->offset
= intval( $offset );
234 * Set which namespaces the search should include.
235 * Give an array of namespace index numbers.
237 * @param $namespaces Array
239 function setNamespaces( $namespaces ) {
240 $this->namespaces
= $namespaces;
244 * Parse some common prefixes: all (search everything)
247 * @param $query String
249 function replacePrefixes( $query ) {
253 if ( strpos( $query, ':' ) === false ) { // nothing to do
254 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
258 $allkeyword = wfMsgForContent( 'searchall' ) . ":";
259 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
260 $this->namespaces
= null;
261 $parsed = substr( $query, strlen( $allkeyword ) );
262 } else if ( strpos( $query, ':' ) !== false ) {
263 $prefix = substr( $query, 0, strpos( $query, ':' ) );
264 $index = $wgContLang->getNsIndex( $prefix );
265 if ( $index !== false ) {
266 $this->namespaces
= array( $index );
267 $parsed = substr( $query, strlen( $prefix ) +
1 );
270 if ( trim( $parsed ) == '' )
271 $parsed = $query; // prefix was the whole query
273 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
279 * Make a list of searchable namespaces and their canonical names.
282 public static function searchableNamespaces() {
285 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
286 if ( $ns >= NS_MAIN
) {
291 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
296 * Extract default namespaces to search from the given user's
297 * settings, returning a list of index numbers.
302 public static function userNamespaces( $user ) {
303 global $wgSearchEverythingOnlyLoggedIn;
305 // get search everything preference, that can be set to be read for logged-in users
306 $searcheverything = false;
307 if ( ( $wgSearchEverythingOnlyLoggedIn && $user->isLoggedIn() )
308 ||
!$wgSearchEverythingOnlyLoggedIn )
309 $searcheverything = $user->getOption( 'searcheverything' );
311 // searcheverything overrides other options
312 if ( $searcheverything )
313 return array_keys( SearchEngine
::searchableNamespaces() );
315 $arr = Preferences
::loadOldSearchNs( $user );
316 $searchableNamespaces = SearchEngine
::searchableNamespaces();
318 $arr = array_intersect( $arr, array_keys( $searchableNamespaces ) ); // Filter
324 * Find snippet highlight settings for a given user
327 * @return Array contextlines, contextchars
329 public static function userHighlightPrefs( &$user ) {
330 // $contextlines = $user->getOption( 'contextlines', 5 );
331 // $contextchars = $user->getOption( 'contextchars', 50 );
332 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
333 $contextchars = 75; // same as above.... :P
334 return array( $contextlines, $contextchars );
338 * An array of namespaces indexes to be searched by default
342 public static function defaultNamespaces() {
343 global $wgNamespacesToBeSearchedDefault;
345 return array_keys( $wgNamespacesToBeSearchedDefault, true );
349 * Get a list of namespace names useful for showing in tooltips
352 * @param $namespaces Array
354 public static function namespacesAsText( $namespaces ) {
357 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
358 foreach ( $formatted as $key => $ns ) {
360 $formatted[$key] = wfMsg( 'blanknamespace' );
366 * Return the help namespaces to be shown on Special:Search
370 public static function helpNamespaces() {
371 global $wgNamespacesToBeSearchedHelp;
373 return array_keys( $wgNamespacesToBeSearchedHelp, true );
377 * Return a 'cleaned up' search string
379 * @param $text String
382 function filter( $text ) {
383 $lc = $this->legalSearchChars();
384 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
387 * Load up the appropriate search engine class for the currently
388 * active database backend, and return a configured instance.
390 * @return SearchEngine
392 public static function create() {
393 global $wgSearchType;
395 if ( $wgSearchType ) {
396 $class = $wgSearchType;
398 $dbr = wfGetDB( DB_SLAVE
);
399 $class = $dbr->getSearchEngine();
401 $search = new $class( $dbr );
402 $search->setLimitOffset( 0, 0 );
407 * Create or update the search index record for the given page.
408 * Title and text should be pre-processed.
412 * @param $title String
413 * @param $text String
415 function update( $id, $title, $text ) {
420 * Update a search index record's title only.
421 * Title should be pre-processed.
425 * @param $title String
427 function updateTitle( $id, $title ) {
432 * Get OpenSearch suggestion template
436 public static function getOpenSearchTemplate() {
437 global $wgOpenSearchTemplate, $wgServer, $wgScriptPath;
438 if ( $wgOpenSearchTemplate ) {
439 return $wgOpenSearchTemplate;
441 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
442 if ( !$ns ) $ns = "0";
443 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace=' . $ns;
448 * Get internal MediaWiki Suggest template
452 public static function getMWSuggestTemplate() {
453 global $wgMWSuggestTemplate, $wgServer, $wgScriptPath;
454 if ( $wgMWSuggestTemplate )
455 return $wgMWSuggestTemplate;
457 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
464 class SearchResultSet
{
466 * Fetch an array of regular expression fragments for matching
467 * the search terms as parsed by this engine in a text extract.
472 function termMatches() {
481 * Return true if results are included in this result set.
486 function hasResults() {
491 * Some search modes return a total hit count for the query
492 * in the entire article database. This may include pages
493 * in namespaces that would not be matched on the given
496 * Return null if no total hits number is supported.
500 function getTotalHits() {
505 * Some search modes return a suggested alternate term if there are
506 * no exact hits. Returns true if there is one on this set.
510 function hasSuggestion() {
515 * @return String: suggested query, null if none
517 function getSuggestionQuery() {
522 * @return String: HTML highlighted suggested query, '' if none
524 function getSuggestionSnippet() {
529 * Return information about how and from where the results were fetched,
530 * should be useful for diagnostics and debugging
539 * Return a result set of hits on other (multiple) wikis associated with this one
541 * @return SearchResultSet
543 function getInterwikiResults() {
548 * Check if there are results on other wikis
552 function hasInterwikiResults() {
553 return $this->getInterwikiResults() != null;
557 * Fetches next search result, or false.
560 * @return SearchResult
567 * Frees the result set, if applicable.
575 * This class is used for different SQL-based search engines shipped with MediaWiki
577 class SqlSearchResultSet
extends SearchResultSet
{
578 function __construct( $resultSet, $terms ) {
579 $this->mResultSet
= $resultSet;
580 $this->mTerms
= $terms;
583 function termMatches() {
584 return $this->mTerms
;
588 if ( $this->mResultSet
=== false )
591 return $this->mResultSet
->numRows();
595 if ( $this->mResultSet
=== false )
598 $row = $this->mResultSet
->fetchObject();
599 if ( $row === false )
602 return SearchResult
::newFromRow( $row );
606 if ( $this->mResultSet
=== false )
609 $this->mResultSet
->free();
616 class SearchResultTooMany
{
617 # # Some search engines may bail out if too many matches are found
622 * @todo Fixme: This class is horribly factored. It would probably be better to
623 * have a useful base class to which you pass some standard information, then
624 * let the fancy self-highlighters extend that.
628 var $mRevision = null;
632 * Return a new SearchResult and initializes it with a title.
634 * @param $title Title
635 * @return SearchResult
637 public static function newFromTitle( $title ) {
638 $result = new self();
639 $result->initFromTitle( $title );
643 * Return a new SearchResult and initializes it with a row.
646 * @return SearchResult
648 public static function newFromRow( $row ) {
649 $result = new self();
650 $result->initFromRow( $row );
654 public function __construct( $row = null ) {
655 if ( !is_null( $row ) ) {
656 // Backwards compatibility with pre-1.17 callers
657 $this->initFromRow( $row );
662 * Initialize from a database row. Makes a Title and passes that to
667 protected function initFromRow( $row ) {
668 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
672 * Initialize from a Title and if possible initializes a corresponding
675 * @param $title Title
677 protected function initFromTitle( $title ) {
678 $this->mTitle
= $title;
679 if ( !is_null( $this->mTitle
) ) {
680 $this->mRevision
= Revision
::newFromTitle( $this->mTitle
);
681 if ( $this->mTitle
->getNamespace() === NS_FILE
)
682 $this->mImage
= wfFindFile( $this->mTitle
);
687 * Check if this is result points to an invalid title
691 function isBrokenTitle() {
692 if ( is_null( $this->mTitle
) )
698 * Check if target page is missing, happens when index is out of date
702 function isMissingRevision() {
703 return !$this->mRevision
&& !$this->mImage
;
709 function getTitle() {
710 return $this->mTitle
;
714 * @return Double or null if not supported
716 function getScore() {
721 * Lazy initialization of article text from DB
723 protected function initText() {
724 if ( !isset( $this->mText
) ) {
725 if ( $this->mRevision
!= null )
726 $this->mText
= $this->mRevision
->getText();
727 else // TODO: can we fetch raw wikitext for commons images?
734 * @param $terms Array: terms to highlight
735 * @return String: highlighted text snippet, null (and not '') if not supported
737 function getTextSnippet( $terms ) {
738 global $wgUser, $wgAdvancedSearchHighlighting;
740 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
741 $h = new SearchHighlighter();
742 if ( $wgAdvancedSearchHighlighting )
743 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
745 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
749 * @param $terms Array: terms to highlight
750 * @return String: highlighted title, '' if not supported
752 function getTitleSnippet( $terms ) {
757 * @param $terms Array: terms to highlight
758 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
760 function getRedirectSnippet( $terms ) {
765 * @return Title object for the redirect to this page, null if none or not supported
767 function getRedirectTitle() {
772 * @return string highlighted relevant section name, null if none or not supported
774 function getSectionSnippet() {
779 * @return Title object (pagename+fragment) for the section, null if none or not supported
781 function getSectionTitle() {
786 * @return String: timestamp
788 function getTimestamp() {
789 if ( $this->mRevision
)
790 return $this->mRevision
->getTimestamp();
791 else if ( $this->mImage
)
792 return $this->mImage
->getTimestamp();
797 * @return Integer: number of words
799 function getWordCount() {
801 return str_word_count( $this->mText
);
805 * @return Integer: size in bytes
807 function getByteSize() {
809 return strlen( $this->mText
);
813 * @return Boolean if hit has related articles
815 function hasRelated() {
820 * @return String: interwiki prefix of the title (return iw even if title is broken)
822 function getInterwikiPrefix() {
827 * A SearchResultSet wrapper for SearchEngine::getNearMatch
829 class SearchNearMatchResultSet
extends SearchResultSet
{
830 private $fetched = false;
832 * @param $match mixed Title if matched, else null
834 public function __construct( $match ) {
835 $this->result
= $match;
837 public function hasResult() {
838 return (bool)$this->result
;
840 public function numRows() {
841 return $this->hasResults() ?
1 : 0;
843 public function next() {
844 if ( $this->fetched ||
!$this->result
) {
847 $this->fetched
= true;
848 return SearchResult
::newFromTitle( $this->result
);
853 * Highlight bits of wikitext
857 class SearchHighlighter
{
858 var $mCleanWikitext = true;
860 function __construct( $cleanupWikitext = true ) {
861 $this->mCleanWikitext
= $cleanupWikitext;
865 * Default implementation of wikitext highlighting
867 * @param $text String
868 * @param $terms Array: terms to highlight (unescaped)
869 * @param $contextlines Integer
870 * @param $contextchars Integer
873 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
875 global $wgSearchHighlightBoundaries;
881 // spli text into text + templates/links/tables
882 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
883 // first capture group is for detecting nested templates/links/tables/references
884 $endPatterns = array(
885 1 => '/(\{\{)|(\}\})/', // template
886 2 => '/(\[\[)|(\]\])/', // image
887 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
889 // FIXME: this should prolly be a hook or something
890 if ( function_exists( 'wfCite' ) ) {
891 $spat .= '|(<ref>)'; // references via cite extension
892 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
895 $textExt = array(); // text extracts
896 $otherExt = array(); // other extracts
897 wfProfileIn( "$fname-split" );
899 $textLen = strlen( $text );
900 $count = 0; // sequence number to maintain ordering
901 while ( $start < $textLen ) {
902 // find start of template/image/table
903 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
905 foreach ( $matches as $key => $val ) {
906 if ( $key > 0 && $val[1] != - 1 ) {
908 // see if this is an image link
909 $ns = substr( $val[0], 2, - 1 );
910 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
)
914 $epat = $endPatterns[$key];
915 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
921 // find end (and detect any nested elements)
923 $offset = $start +
1;
925 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
926 if ( array_key_exists( 2, $endMatches ) ) {
929 $len = strlen( $endMatches[2][0] );
930 $off = $endMatches[2][1];
931 $this->splitAndAdd( $otherExt, $count,
932 substr( $text, $start, $off +
$len - $start ) );
933 $start = $off +
$len;
937 // end of nested element
944 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
947 // couldn't find appropriate closing tag, skip
948 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
949 $start +
= strlen( $matches[0][0] );
954 // else: add as text extract
955 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
959 $all = $textExt +
$otherExt; // these have disjunct key sets
961 wfProfileOut( "$fname-split" );
964 foreach ( $terms as $index => $term ) {
965 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
966 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
967 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
969 $terms[$index] = $term;
972 $anyterm = implode( '|', $terms );
973 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
975 // FIXME: a hack to scale contextchars, a correct solution
976 // would be to have contextchars actually be char and not byte
977 // length, and do proper utf-8 substrings and lengths everywhere,
978 // but PHP is making that very hard and unclean to implement :(
979 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
980 $contextchars = intval( $contextchars * $scale );
982 $patPre = "(^|$wgSearchHighlightBoundaries)";
983 $patPost = "($wgSearchHighlightBoundaries|$)";
985 $pat1 = "/(" . $phrase . ")/ui";
986 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
988 wfProfileIn( "$fname-extract" );
990 $left = $contextlines;
995 // show beginning only if it contains all words
998 foreach ( $textExt as $index => $line ) {
999 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1000 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1007 // check if first text contains all terms
1008 foreach ( $terms as $term ) {
1009 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1015 $snippets[$first] = $firstText;
1016 $offsets[$first] = 0;
1019 if ( ! $snippets ) {
1020 // match whole query on text
1021 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1022 // match whole query on templates/tables/images
1023 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1024 // match any words on text
1025 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1026 // match any words on templates/tables/images
1027 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1032 // add extra chars to each snippet to make snippets constant size
1033 $extended = array();
1034 if ( count( $snippets ) == 0 ) {
1035 // couldn't find the target words, just show beginning of article
1036 if ( array_key_exists( $first, $all ) ) {
1037 $targetchars = $contextchars * $contextlines;
1038 $snippets[$first] = '';
1039 $offsets[$first] = 0;
1042 // if begin of the article contains the whole phrase, show only that !!
1043 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1044 && $offsets[$first] < $contextchars * 2 ) {
1045 $snippets = array ( $first => $snippets[$first] );
1048 // calc by how much to extend existing snippets
1049 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1052 foreach ( $snippets as $index => $line ) {
1053 $extended[$index] = $line;
1054 $len = strlen( $line );
1055 if ( $len < $targetchars - 20 ) {
1056 // complete this line
1057 if ( $len < strlen( $all[$index] ) ) {
1058 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1059 $len = strlen( $extended[$index] );
1064 while ( $len < $targetchars - 20
1065 && array_key_exists( $add, $all )
1066 && !array_key_exists( $add, $snippets ) ) {
1068 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1069 $extended[$add] = $tt;
1070 $len +
= strlen( $tt );
1076 // $snippets = array_map('htmlspecialchars', $extended);
1077 $snippets = $extended;
1080 foreach ( $snippets as $index => $line ) {
1082 $extract .= $line; // first line
1083 elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1084 $extract .= " " . $line; // continous lines
1086 $extract .= '<b> ... </b>' . $line;
1091 $extract .= '<b> ... </b>';
1093 $processed = array();
1094 foreach ( $terms as $term ) {
1095 if ( ! isset( $processed[$term] ) ) {
1096 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1097 $extract = preg_replace( $pat3,
1098 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1099 $processed[$term] = true;
1103 wfProfileOut( "$fname-extract" );
1109 * Split text into lines and add it to extracts array
1111 * @param $extracts Array: index -> $line
1112 * @param $count Integer
1113 * @param $text String
1115 function splitAndAdd( &$extracts, &$count, $text ) {
1116 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1117 foreach ( $split as $line ) {
1118 $tt = trim( $line );
1120 $extracts[$count++
] = $tt;
1125 * Do manual case conversion for non-ascii chars
1127 * @param $matches Array
1129 function caseCallback( $matches ) {
1131 if ( strlen( $matches[0] ) > 1 ) {
1132 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1138 * Extract part of the text from start to end, but by
1139 * not chopping up words
1140 * @param $text String
1141 * @param $start Integer
1142 * @param $end Integer
1143 * @param $posStart Integer: (out) actual start position
1144 * @param $posEnd Integer: (out) actual end position
1147 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1149 $start = $this->position( $text, $start, 1 );
1150 if ( $end >= strlen( $text ) )
1151 $end = strlen( $text );
1153 $end = $this->position( $text, $end );
1155 if ( !is_null( $posStart ) )
1157 if ( !is_null( $posEnd ) )
1160 if ( $end > $start )
1161 return substr( $text, $start, $end - $start );
1167 * Find a nonletter near a point (index) in the text
1169 * @param $text String
1170 * @param $point Integer
1171 * @param $offset Integer: offset to found index
1172 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1174 function position( $text, $point, $offset = 0 ) {
1176 $s = max( 0, $point - $tolerance );
1177 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1179 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1180 return $m[0][1] +
$s +
$offset;
1182 // check if point is on a valid first UTF8 char
1183 $char = ord( $text[$point] );
1184 while ( $char >= 0x80 && $char < 0xc0 ) {
1185 // skip trailing bytes
1187 if ( $point >= strlen( $text ) )
1188 return strlen( $text );
1189 $char = ord( $text[$point] );
1197 * Search extracts for a pattern, and return snippets
1199 * @param $pattern String: regexp for matching lines
1200 * @param $extracts Array: extracts to search
1201 * @param $linesleft Integer: number of extracts to make
1202 * @param $contextchars Integer: length of snippet
1203 * @param $out Array: map for highlighted snippets
1204 * @param $offsets Array: map of starting points of snippets
1207 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1208 if ( $linesleft == 0 )
1209 return; // nothing to do
1210 foreach ( $extracts as $index => $line ) {
1211 if ( array_key_exists( $index, $out ) )
1212 continue; // this line already highlighted
1215 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1219 $len = strlen( $m[0][0] );
1220 if ( $offset +
$len < $contextchars )
1222 elseif ( $len > $contextchars )
1225 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1227 $end = $begin +
$contextchars;
1230 // basic snippet from this line
1231 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1232 $offsets[$index] = $posBegin;
1234 if ( $linesleft == 0 )
1240 * Basic wikitext removal
1243 function removeWiki( $text ) {
1244 $fname = __METHOD__
;
1245 wfProfileIn( $fname );
1247 // $text = preg_replace("/'{2,5}/", "", $text);
1248 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1249 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1250 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1251 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1252 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1253 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1254 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1255 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1256 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1257 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1258 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1259 $text = preg_replace( "/'''''/", "", $text );
1260 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1261 $text = preg_replace( "/''/", "", $text );
1263 wfProfileOut( $fname );
1268 * callback to replace [[target|caption]] kind of links, if
1269 * the target is category or image, leave it
1271 * @param $matches Array
1273 function linkReplace( $matches ) {
1274 $colon = strpos( $matches[1], ':' );
1275 if ( $colon === false )
1276 return $matches[2]; // replace with caption
1278 $ns = substr( $matches[1], 0, $colon );
1279 $index = $wgContLang->getNsIndex( $ns );
1280 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) )
1281 return $matches[0]; // return the whole thing
1288 * Simple & fast snippet extraction, but gives completely unrelevant
1291 * @param $text String
1292 * @param $terms Array
1293 * @param $contextlines Integer
1294 * @param $contextchars Integer
1297 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1299 $fname = __METHOD__
;
1301 $lines = explode( "\n", $text );
1303 $terms = implode( '|', $terms );
1304 $max = intval( $contextchars ) +
1;
1305 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1310 wfProfileIn( "$fname-extract" );
1311 foreach ( $lines as $line ) {
1312 if ( 0 == $contextlines ) {
1317 if ( ! preg_match( $pat1, $line, $m ) ) {
1321 $pre = $wgContLang->truncate( $m[1], - $contextchars );
1323 if ( count( $m ) < 3 ) {
1326 $post = $wgContLang->truncate( $m[3], $contextchars );
1331 $line = htmlspecialchars( $pre . $found . $post );
1332 $pat2 = '/(' . $terms . ")/i";
1333 $line = preg_replace( $pat2,
1334 "<span class='searchmatch'>\\1</span>", $line );
1336 $extract .= "${line}\n";
1338 wfProfileOut( "$fname-extract" );
1346 * Dummy class to be used when non-supported Database engine is present.
1347 * @todo Fixme: dummy class should probably try something at least mildly useful,
1348 * such as a LIKE search through titles.
1351 class SearchEngineDummy
extends SearchEngine
{