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;
26 * Perform a full text search query and return a result set.
27 * If title searches are not supported or disabled, return null.
30 * @param $term String: raw search term
31 * @return SearchResultSet
33 function searchText( $term ) {
38 * Perform a title-only search query and return a result set.
39 * If title searches are not supported or disabled, return null.
42 * @param $term String: raw search term
43 * @return SearchResultSet
45 function searchTitle( $term ) {
49 /** If this search backend can list/unlist redirects */
50 function acceptListRedirects() {
55 * When overridden in derived class, performs database-specific conversions
56 * on text to be used for searching or updating search index.
57 * Default implementation does nothing (simply returns $string).
59 * @param $string string: String to process
62 public function normalizeText( $string ) {
65 // Some languages such as Chinese require word segmentation
66 return $wgContLang->segmentByWord( $string );
70 * Transform search term in cases when parts of the query came as different GET params (when supported)
71 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
73 function transformSearchTerm( $term ) {
78 * If an exact title match can be found, or a very slightly close match,
79 * return the title. If no match, returns NULL.
81 * @param $searchterm String
84 public static function getNearMatch( $searchterm ) {
85 $title = self
::getNearMatchInternal( $searchterm );
87 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
92 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
95 * @param $searchterm string
96 * @return SearchResultSet
98 public static function getNearMatchResultSet( $searchterm ) {
99 return new SearchNearMatchResultSet( self
::getNearMatch( $searchterm ) );
103 * Really find the title match.
105 private static function getNearMatchInternal( $searchterm ) {
108 $allSearchTerms = array( $searchterm );
110 if ( $wgContLang->hasVariants() ) {
111 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
115 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
119 foreach ( $allSearchTerms as $term ) {
121 # Exact match? No need to look further.
122 $title = Title
::newFromText( $term );
123 if ( is_null( $title ) )
126 if ( $title->getNamespace() == NS_SPECIAL ||
$title->isExternal() ||
$title->exists() ) {
130 # See if it still otherwise has content is some sane sense
131 $article = MediaWiki
::articleFromTitle( $title );
132 if ( $article->hasViewableContent() ) {
136 # Now try all lower case (i.e. first letter capitalized)
138 $title = Title
::newFromText( $wgContLang->lc( $term ) );
139 if ( $title && $title->exists() ) {
143 # Now try capitalized string
145 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
146 if ( $title && $title->exists() ) {
150 # Now try all upper case
152 $title = Title
::newFromText( $wgContLang->uc( $term ) );
153 if ( $title && $title->exists() ) {
157 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
158 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
159 if ( $title && $title->exists() ) {
163 // Give hooks a chance at better match variants
165 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
170 $title = Title
::newFromText( $searchterm );
172 # Entering an IP address goes to the contributions page
173 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
174 || User
::isIP( trim( $searchterm ) ) ) {
175 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
179 # Entering a user goes to the user page whether it's there or not
180 if ( $title->getNamespace() == NS_USER
) {
184 # Go to images that exist even if there's no local page.
185 # There may have been a funny upload, or it may be on a shared
186 # file repository such as Wikimedia Commons.
187 if ( $title->getNamespace() == NS_FILE
) {
188 $image = wfFindFile( $title );
194 # MediaWiki namespace? Page may be "implied" if not customized.
195 # Just return it, with caps forced as the message system likes it.
196 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
197 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
200 # Quoted term? Try without the quotes...
202 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
203 return SearchEngine
::getNearMatch( $matches[1] );
209 public static function legalSearchChars() {
210 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
214 * Set the maximum number of results to return
215 * and how many to skip before returning the first.
217 * @param $limit Integer
218 * @param $offset Integer
220 function setLimitOffset( $limit, $offset = 0 ) {
221 $this->limit
= intval( $limit );
222 $this->offset
= intval( $offset );
226 * Set which namespaces the search should include.
227 * Give an array of namespace index numbers.
229 * @param $namespaces Array
231 function setNamespaces( $namespaces ) {
232 $this->namespaces
= $namespaces;
236 * Parse some common prefixes: all (search everything)
239 * @param $query String
241 function replacePrefixes( $query ) {
245 if ( strpos( $query, ':' ) === false ) { // nothing to do
246 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
250 $allkeyword = wfMsgForContent( 'searchall' ) . ":";
251 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
252 $this->namespaces
= null;
253 $parsed = substr( $query, strlen( $allkeyword ) );
254 } else if ( strpos( $query, ':' ) !== false ) {
255 $prefix = substr( $query, 0, strpos( $query, ':' ) );
256 $index = $wgContLang->getNsIndex( $prefix );
257 if ( $index !== false ) {
258 $this->namespaces
= array( $index );
259 $parsed = substr( $query, strlen( $prefix ) +
1 );
262 if ( trim( $parsed ) == '' )
263 $parsed = $query; // prefix was the whole query
265 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
271 * Make a list of searchable namespaces and their canonical names.
274 public static function searchableNamespaces() {
277 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
278 if ( $ns >= NS_MAIN
) {
283 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
288 * Extract default namespaces to search from the given user's
289 * settings, returning a list of index numbers.
294 public static function userNamespaces( $user ) {
295 global $wgSearchEverythingOnlyLoggedIn;
297 // get search everything preference, that can be set to be read for logged-in users
298 $searcheverything = false;
299 if ( ( $wgSearchEverythingOnlyLoggedIn && $user->isLoggedIn() )
300 ||
!$wgSearchEverythingOnlyLoggedIn )
301 $searcheverything = $user->getOption( 'searcheverything' );
303 // searcheverything overrides other options
304 if ( $searcheverything )
305 return array_keys( SearchEngine
::searchableNamespaces() );
307 $arr = Preferences
::loadOldSearchNs( $user );
308 $searchableNamespaces = SearchEngine
::searchableNamespaces();
310 $arr = array_intersect( $arr, array_keys( $searchableNamespaces ) ); // Filter
316 * Find snippet highlight settings for a given user
319 * @return Array contextlines, contextchars
321 public static function userHighlightPrefs( &$user ) {
322 // $contextlines = $user->getOption( 'contextlines', 5 );
323 // $contextchars = $user->getOption( 'contextchars', 50 );
324 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
325 $contextchars = 75; // same as above.... :P
326 return array( $contextlines, $contextchars );
330 * An array of namespaces indexes to be searched by default
334 public static function defaultNamespaces() {
335 global $wgNamespacesToBeSearchedDefault;
337 return array_keys( $wgNamespacesToBeSearchedDefault, true );
341 * Get a list of namespace names useful for showing in tooltips
344 * @param $namespaces Array
346 public static function namespacesAsText( $namespaces ) {
349 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
350 foreach ( $formatted as $key => $ns ) {
352 $formatted[$key] = wfMsg( 'blanknamespace' );
358 * Return the help namespaces to be shown on Special:Search
362 public static function helpNamespaces() {
363 global $wgNamespacesToBeSearchedHelp;
365 return array_keys( $wgNamespacesToBeSearchedHelp, true );
369 * Return a 'cleaned up' search string
371 * @param $text String
374 function filter( $text ) {
375 $lc = $this->legalSearchChars();
376 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
379 * Load up the appropriate search engine class for the currently
380 * active database backend, and return a configured instance.
382 * @return SearchEngine
384 public static function create() {
385 global $wgSearchType;
386 $dbr = wfGetDB( DB_SLAVE
);
387 if ( $wgSearchType ) {
388 $class = $wgSearchType;
390 $class = $dbr->getSearchEngine();
392 $search = new $class( $dbr );
393 $search->setLimitOffset( 0, 0 );
398 * Create or update the search index record for the given page.
399 * Title and text should be pre-processed.
403 * @param $title String
404 * @param $text String
406 function update( $id, $title, $text ) {
411 * Update a search index record's title only.
412 * Title should be pre-processed.
416 * @param $title String
418 function updateTitle( $id, $title ) {
423 * Get OpenSearch suggestion template
427 public static function getOpenSearchTemplate() {
428 global $wgOpenSearchTemplate, $wgServer, $wgScriptPath;
429 if ( $wgOpenSearchTemplate ) {
430 return $wgOpenSearchTemplate;
432 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
433 if ( !$ns ) $ns = "0";
434 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace=' . $ns;
439 * Get internal MediaWiki Suggest template
443 public static function getMWSuggestTemplate() {
444 global $wgMWSuggestTemplate, $wgServer, $wgScriptPath;
445 if ( $wgMWSuggestTemplate )
446 return $wgMWSuggestTemplate;
448 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
455 class SearchResultSet
{
457 * Fetch an array of regular expression fragments for matching
458 * the search terms as parsed by this engine in a text extract.
463 function termMatches() {
472 * Return true if results are included in this result set.
477 function hasResults() {
482 * Some search modes return a total hit count for the query
483 * in the entire article database. This may include pages
484 * in namespaces that would not be matched on the given
487 * Return null if no total hits number is supported.
491 function getTotalHits() {
496 * Some search modes return a suggested alternate term if there are
497 * no exact hits. Returns true if there is one on this set.
501 function hasSuggestion() {
506 * @return String: suggested query, null if none
508 function getSuggestionQuery() {
513 * @return String: HTML highlighted suggested query, '' if none
515 function getSuggestionSnippet() {
520 * Return information about how and from where the results were fetched,
521 * should be useful for diagnostics and debugging
530 * Return a result set of hits on other (multiple) wikis associated with this one
532 * @return SearchResultSet
534 function getInterwikiResults() {
539 * Check if there are results on other wikis
543 function hasInterwikiResults() {
544 return $this->getInterwikiResults() != null;
548 * Fetches next search result, or false.
551 * @return SearchResult
558 * Frees the result set, if applicable.
566 * This class is used for different SQL-based search engines shipped with MediaWiki
568 class SqlSearchResultSet
extends SearchResultSet
{
569 function __construct( $resultSet, $terms ) {
570 $this->mResultSet
= $resultSet;
571 $this->mTerms
= $terms;
574 function termMatches() {
575 return $this->mTerms
;
579 if ( $this->mResultSet
=== false )
582 return $this->mResultSet
->numRows();
586 if ( $this->mResultSet
=== false )
589 $row = $this->mResultSet
->fetchObject();
590 if ( $row === false )
593 return SearchResult
::newFromRow( $row );
597 if ( $this->mResultSet
=== false )
600 $this->mResultSet
->free();
607 class SearchResultTooMany
{
608 # # Some search engines may bail out if too many matches are found
613 * @todo Fixme: This class is horribly factored. It would probably be better to
614 * have a useful base class to which you pass some standard information, then
615 * let the fancy self-highlighters extend that.
619 var $mRevision = null;
623 * Return a new SearchResult and initializes it with a title.
625 * @param $title Title
626 * @return SearchResult
628 public static function newFromTitle( $title ) {
629 $result = new self();
630 $result->initFromTitle( $title );
634 * Return a new SearchResult and initializes it with a row.
637 * @return SearchResult
639 public static function newFromRow( $row ) {
640 $result = new self();
641 $result->initFromRow( $row );
645 public function __construct( $row = null ) {
646 if ( !is_null( $row ) ) {
647 // Backwards compatibility with pre-1.17 callers
648 $this->initFromRow( $row );
653 * Initialize from a database row. Makes a Title and passes that to
658 protected function initFromRow( $row ) {
659 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
663 * Initialize from a Title and if possible initializes a corresponding
666 * @param $title Title
668 protected function initFromTitle( $title ) {
669 $this->mTitle
= $title;
670 if ( !is_null( $this->mTitle
) ) {
671 $this->mRevision
= Revision
::newFromTitle( $this->mTitle
);
672 if ( $this->mTitle
->getNamespace() === NS_FILE
)
673 $this->mImage
= wfFindFile( $this->mTitle
);
678 * Check if this is result points to an invalid title
682 function isBrokenTitle() {
683 if ( is_null( $this->mTitle
) )
689 * Check if target page is missing, happens when index is out of date
693 function isMissingRevision() {
694 return !$this->mRevision
&& !$this->mImage
;
700 function getTitle() {
701 return $this->mTitle
;
705 * @return Double or null if not supported
707 function getScore() {
712 * Lazy initialization of article text from DB
714 protected function initText() {
715 if ( !isset( $this->mText
) ) {
716 if ( $this->mRevision
!= null )
717 $this->mText
= $this->mRevision
->getText();
718 else // TODO: can we fetch raw wikitext for commons images?
725 * @param $terms Array: terms to highlight
726 * @return String: highlighted text snippet, null (and not '') if not supported
728 function getTextSnippet( $terms ) {
729 global $wgUser, $wgAdvancedSearchHighlighting;
731 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
732 $h = new SearchHighlighter();
733 if ( $wgAdvancedSearchHighlighting )
734 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
736 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
740 * @param $terms Array: terms to highlight
741 * @return String: highlighted title, '' if not supported
743 function getTitleSnippet( $terms ) {
748 * @param $terms Array: terms to highlight
749 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
751 function getRedirectSnippet( $terms ) {
756 * @return Title object for the redirect to this page, null if none or not supported
758 function getRedirectTitle() {
763 * @return string highlighted relevant section name, null if none or not supported
765 function getSectionSnippet() {
770 * @return Title object (pagename+fragment) for the section, null if none or not supported
772 function getSectionTitle() {
777 * @return String: timestamp
779 function getTimestamp() {
780 if ( $this->mRevision
)
781 return $this->mRevision
->getTimestamp();
782 else if ( $this->mImage
)
783 return $this->mImage
->getTimestamp();
788 * @return Integer: number of words
790 function getWordCount() {
792 return str_word_count( $this->mText
);
796 * @return Integer: size in bytes
798 function getByteSize() {
800 return strlen( $this->mText
);
804 * @return Boolean if hit has related articles
806 function hasRelated() {
811 * @return String: interwiki prefix of the title (return iw even if title is broken)
813 function getInterwikiPrefix() {
818 * A SearchResultSet wrapper for SearchEngine::getNearMatch
820 class SearchNearMatchResultSet
extends SearchResultSet
{
821 private $fetched = false;
823 * @param $match mixed Title if matched, else null
825 public function __construct( $match ) {
826 $this->result
= $match;
828 public function hasResult() {
829 return (bool)$this->result
;
831 public function numRows() {
832 return $this->hasResults() ?
1 : 0;
834 public function next() {
835 if ( $this->fetched ||
!$this->result
) {
838 $this->fetched
= true;
839 return SearchResult
::newFromTitle( $this->result
);
844 * Highlight bits of wikitext
848 class SearchHighlighter
{
849 var $mCleanWikitext = true;
851 function __construct( $cleanupWikitext = true ) {
852 $this->mCleanWikitext
= $cleanupWikitext;
856 * Default implementation of wikitext highlighting
858 * @param $text String
859 * @param $terms Array: terms to highlight (unescaped)
860 * @param $contextlines Integer
861 * @param $contextchars Integer
864 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
866 global $wgSearchHighlightBoundaries;
872 // spli text into text + templates/links/tables
873 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
874 // first capture group is for detecting nested templates/links/tables/references
875 $endPatterns = array(
876 1 => '/(\{\{)|(\}\})/', // template
877 2 => '/(\[\[)|(\]\])/', // image
878 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
880 // FIXME: this should prolly be a hook or something
881 if ( function_exists( 'wfCite' ) ) {
882 $spat .= '|(<ref>)'; // references via cite extension
883 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
886 $textExt = array(); // text extracts
887 $otherExt = array(); // other extracts
888 wfProfileIn( "$fname-split" );
890 $textLen = strlen( $text );
891 $count = 0; // sequence number to maintain ordering
892 while ( $start < $textLen ) {
893 // find start of template/image/table
894 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
896 foreach ( $matches as $key => $val ) {
897 if ( $key > 0 && $val[1] != - 1 ) {
899 // see if this is an image link
900 $ns = substr( $val[0], 2, - 1 );
901 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
)
905 $epat = $endPatterns[$key];
906 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
912 // find end (and detect any nested elements)
914 $offset = $start +
1;
916 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
917 if ( array_key_exists( 2, $endMatches ) ) {
920 $len = strlen( $endMatches[2][0] );
921 $off = $endMatches[2][1];
922 $this->splitAndAdd( $otherExt, $count,
923 substr( $text, $start, $off +
$len - $start ) );
924 $start = $off +
$len;
928 // end of nested element
935 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
938 // couldn't find appropriate closing tag, skip
939 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
940 $start +
= strlen( $matches[0][0] );
945 // else: add as text extract
946 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
950 $all = $textExt +
$otherExt; // these have disjunct key sets
952 wfProfileOut( "$fname-split" );
955 foreach ( $terms as $index => $term ) {
956 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
957 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
958 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
960 $terms[$index] = $term;
963 $anyterm = implode( '|', $terms );
964 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
966 // FIXME: a hack to scale contextchars, a correct solution
967 // would be to have contextchars actually be char and not byte
968 // length, and do proper utf-8 substrings and lengths everywhere,
969 // but PHP is making that very hard and unclean to implement :(
970 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
971 $contextchars = intval( $contextchars * $scale );
973 $patPre = "(^|$wgSearchHighlightBoundaries)";
974 $patPost = "($wgSearchHighlightBoundaries|$)";
976 $pat1 = "/(" . $phrase . ")/ui";
977 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
979 wfProfileIn( "$fname-extract" );
981 $left = $contextlines;
986 // show beginning only if it contains all words
989 foreach ( $textExt as $index => $line ) {
990 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
991 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
998 // check if first text contains all terms
999 foreach ( $terms as $term ) {
1000 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1006 $snippets[$first] = $firstText;
1007 $offsets[$first] = 0;
1010 if ( ! $snippets ) {
1011 // match whole query on text
1012 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1013 // match whole query on templates/tables/images
1014 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1015 // match any words on text
1016 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1017 // match any words on templates/tables/images
1018 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1023 // add extra chars to each snippet to make snippets constant size
1024 $extended = array();
1025 if ( count( $snippets ) == 0 ) {
1026 // couldn't find the target words, just show beginning of article
1027 if ( array_key_exists( $first, $all ) ) {
1028 $targetchars = $contextchars * $contextlines;
1029 $snippets[$first] = '';
1030 $offsets[$first] = 0;
1033 // if begin of the article contains the whole phrase, show only that !!
1034 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1035 && $offsets[$first] < $contextchars * 2 ) {
1036 $snippets = array ( $first => $snippets[$first] );
1039 // calc by how much to extend existing snippets
1040 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1043 foreach ( $snippets as $index => $line ) {
1044 $extended[$index] = $line;
1045 $len = strlen( $line );
1046 if ( $len < $targetchars - 20 ) {
1047 // complete this line
1048 if ( $len < strlen( $all[$index] ) ) {
1049 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1050 $len = strlen( $extended[$index] );
1055 while ( $len < $targetchars - 20
1056 && array_key_exists( $add, $all )
1057 && !array_key_exists( $add, $snippets ) ) {
1059 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1060 $extended[$add] = $tt;
1061 $len +
= strlen( $tt );
1067 // $snippets = array_map('htmlspecialchars', $extended);
1068 $snippets = $extended;
1071 foreach ( $snippets as $index => $line ) {
1073 $extract .= $line; // first line
1074 elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1075 $extract .= " " . $line; // continous lines
1077 $extract .= '<b> ... </b>' . $line;
1082 $extract .= '<b> ... </b>';
1084 $processed = array();
1085 foreach ( $terms as $term ) {
1086 if ( ! isset( $processed[$term] ) ) {
1087 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1088 $extract = preg_replace( $pat3,
1089 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1090 $processed[$term] = true;
1094 wfProfileOut( "$fname-extract" );
1100 * Split text into lines and add it to extracts array
1102 * @param $extracts Array: index -> $line
1103 * @param $count Integer
1104 * @param $text String
1106 function splitAndAdd( &$extracts, &$count, $text ) {
1107 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1108 foreach ( $split as $line ) {
1109 $tt = trim( $line );
1111 $extracts[$count++
] = $tt;
1116 * Do manual case conversion for non-ascii chars
1118 * @param $matches Array
1120 function caseCallback( $matches ) {
1122 if ( strlen( $matches[0] ) > 1 ) {
1123 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1129 * Extract part of the text from start to end, but by
1130 * not chopping up words
1131 * @param $text String
1132 * @param $start Integer
1133 * @param $end Integer
1134 * @param $posStart Integer: (out) actual start position
1135 * @param $posEnd Integer: (out) actual end position
1138 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1140 $start = $this->position( $text, $start, 1 );
1141 if ( $end >= strlen( $text ) )
1142 $end = strlen( $text );
1144 $end = $this->position( $text, $end );
1146 if ( !is_null( $posStart ) )
1148 if ( !is_null( $posEnd ) )
1151 if ( $end > $start )
1152 return substr( $text, $start, $end - $start );
1158 * Find a nonletter near a point (index) in the text
1160 * @param $text String
1161 * @param $point Integer
1162 * @param $offset Integer: offset to found index
1163 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1165 function position( $text, $point, $offset = 0 ) {
1167 $s = max( 0, $point - $tolerance );
1168 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1170 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1171 return $m[0][1] +
$s +
$offset;
1173 // check if point is on a valid first UTF8 char
1174 $char = ord( $text[$point] );
1175 while ( $char >= 0x80 && $char < 0xc0 ) {
1176 // skip trailing bytes
1178 if ( $point >= strlen( $text ) )
1179 return strlen( $text );
1180 $char = ord( $text[$point] );
1188 * Search extracts for a pattern, and return snippets
1190 * @param $pattern String: regexp for matching lines
1191 * @param $extracts Array: extracts to search
1192 * @param $linesleft Integer: number of extracts to make
1193 * @param $contextchars Integer: length of snippet
1194 * @param $out Array: map for highlighted snippets
1195 * @param $offsets Array: map of starting points of snippets
1198 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1199 if ( $linesleft == 0 )
1200 return; // nothing to do
1201 foreach ( $extracts as $index => $line ) {
1202 if ( array_key_exists( $index, $out ) )
1203 continue; // this line already highlighted
1206 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1210 $len = strlen( $m[0][0] );
1211 if ( $offset +
$len < $contextchars )
1213 elseif ( $len > $contextchars )
1216 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1218 $end = $begin +
$contextchars;
1221 // basic snippet from this line
1222 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1223 $offsets[$index] = $posBegin;
1225 if ( $linesleft == 0 )
1231 * Basic wikitext removal
1234 function removeWiki( $text ) {
1235 $fname = __METHOD__
;
1236 wfProfileIn( $fname );
1238 // $text = preg_replace("/'{2,5}/", "", $text);
1239 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1240 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1241 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1242 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1243 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1244 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1245 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1246 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1247 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1248 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1249 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1250 $text = preg_replace( "/'''''/", "", $text );
1251 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1252 $text = preg_replace( "/''/", "", $text );
1254 wfProfileOut( $fname );
1259 * callback to replace [[target|caption]] kind of links, if
1260 * the target is category or image, leave it
1262 * @param $matches Array
1264 function linkReplace( $matches ) {
1265 $colon = strpos( $matches[1], ':' );
1266 if ( $colon === false )
1267 return $matches[2]; // replace with caption
1269 $ns = substr( $matches[1], 0, $colon );
1270 $index = $wgContLang->getNsIndex( $ns );
1271 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) )
1272 return $matches[0]; // return the whole thing
1279 * Simple & fast snippet extraction, but gives completely unrelevant
1282 * @param $text String
1283 * @param $terms Array
1284 * @param $contextlines Integer
1285 * @param $contextchars Integer
1288 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1290 $fname = __METHOD__
;
1292 $lines = explode( "\n", $text );
1294 $terms = implode( '|', $terms );
1295 $max = intval( $contextchars ) +
1;
1296 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1301 wfProfileIn( "$fname-extract" );
1302 foreach ( $lines as $line ) {
1303 if ( 0 == $contextlines ) {
1308 if ( ! preg_match( $pat1, $line, $m ) ) {
1312 $pre = $wgContLang->truncate( $m[1], - $contextchars );
1314 if ( count( $m ) < 3 ) {
1317 $post = $wgContLang->truncate( $m[3], $contextchars );
1322 $line = htmlspecialchars( $pre . $found . $post );
1323 $pat2 = '/(' . $terms . ")/i";
1324 $line = preg_replace( $pat2,
1325 "<span class='searchmatch'>\\1</span>", $line );
1327 $extract .= "${line}\n";
1329 wfProfileOut( "$fname-extract" );
1337 * Dummy class to be used when non-supported Database engine is present.
1338 * @todo Fixme: dummy class should probably try something at least mildly useful,
1339 * such as a LIKE search through titles.
1342 class SearchEngineDummy
extends SearchEngine
{