3 * @defgroup Search Search
10 * Contain a class for special pages
17 var $searchTerms = array();
18 var $namespaces = array( NS_MAIN
);
19 var $showRedirects = false;
22 * Perform a full text search query and return a result set.
23 * If title searches are not supported or disabled, return null.
26 * @param $term String: raw search term
27 * @return SearchResultSet
29 function searchText( $term ) {
34 * Perform a title-only search query and return a result set.
35 * If title searches are not supported or disabled, return null.
38 * @param $term String: raw search term
39 * @return SearchResultSet
41 function searchTitle( $term ) {
45 /** If this search backend can list/unlist redirects */
46 function acceptListRedirects() {
51 * Transform search term in cases when parts of the query came as different GET params (when supported)
52 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
54 function transformSearchTerm( $term ) {
59 * If an exact title match can be find, or a very slightly close match,
60 * return the title. If no match, returns NULL.
62 * @param $searchterm String
65 public static function getNearMatch( $searchterm ) {
68 $allSearchTerms = array($searchterm);
70 if($wgContLang->hasVariants()){
71 $allSearchTerms = array_merge($allSearchTerms,$wgContLang->convertLinkToAllVariants($searchterm));
74 foreach($allSearchTerms as $term){
76 # Exact match? No need to look further.
77 $title = Title
::newFromText( $term );
81 if ( $title->getNamespace() == NS_SPECIAL ||
$title->isExternal() ||
$title->exists() ) {
85 # See if it still otherwise has content is some sane sense
86 $article = MediaWiki
::articleFromTitle( $title );
87 if( $article->hasViewableContent() ) {
91 # Now try all lower case (i.e. first letter capitalized)
93 $title = Title
::newFromText( $wgContLang->lc( $term ) );
94 if ( $title && $title->exists() ) {
98 # Now try capitalized string
100 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
101 if ( $title && $title->exists() ) {
105 # Now try all upper case
107 $title = Title
::newFromText( $wgContLang->uc( $term ) );
108 if ( $title && $title->exists() ) {
112 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
113 $title = Title
::newFromText( $wgContLang->ucwordbreaks($term) );
114 if ( $title && $title->exists() ) {
118 // Give hooks a chance at better match variants
120 if( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
125 $title = Title
::newFromText( $searchterm );
127 # Entering an IP address goes to the contributions page
128 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP($title->getText() ) )
129 || User
::isIP( trim( $searchterm ) ) ) {
130 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
134 # Entering a user goes to the user page whether it's there or not
135 if ( $title->getNamespace() == NS_USER
) {
139 # Go to images that exist even if there's no local page.
140 # There may have been a funny upload, or it may be on a shared
141 # file repository such as Wikimedia Commons.
142 if( $title->getNamespace() == NS_FILE
) {
143 $image = wfFindFile( $title );
149 # MediaWiki namespace? Page may be "implied" if not customized.
150 # Just return it, with caps forced as the message system likes it.
151 if( $title->getNamespace() == NS_MEDIAWIKI
) {
152 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
155 # Quoted term? Try without the quotes...
157 if( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
158 return SearchEngine
::getNearMatch( $matches[1] );
164 public static function legalSearchChars() {
165 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
169 * Set the maximum number of results to return
170 * and how many to skip before returning the first.
172 * @param $limit Integer
173 * @param $offset Integer
175 function setLimitOffset( $limit, $offset = 0 ) {
176 $this->limit
= intval( $limit );
177 $this->offset
= intval( $offset );
181 * Set which namespaces the search should include.
182 * Give an array of namespace index numbers.
184 * @param $namespaces Array
186 function setNamespaces( $namespaces ) {
187 $this->namespaces
= $namespaces;
191 * Parse some common prefixes: all (search everything)
194 * @param $query String
196 function replacePrefixes( $query ){
199 if( strpos($query,':') === false )
200 return $query; // nothing to do
203 $allkeyword = wfMsgForContent('searchall').":";
204 if( strncmp($query, $allkeyword, strlen($allkeyword)) == 0 ){
205 $this->namespaces
= null;
206 $parsed = substr($query,strlen($allkeyword));
207 } else if( strpos($query,':') !== false ) {
208 $prefix = substr($query,0,strpos($query,':'));
209 $index = $wgContLang->getNsIndex($prefix);
210 if($index !== false){
211 $this->namespaces
= array($index);
212 $parsed = substr($query,strlen($prefix)+
1);
215 if(trim($parsed) == '')
216 return $query; // prefix was the whole query
222 * Make a list of searchable namespaces and their canonical names.
225 public static function searchableNamespaces() {
228 foreach( $wgContLang->getNamespaces() as $ns => $name ) {
229 if( $ns >= NS_MAIN
) {
237 * Extract default namespaces to search from the given user's
238 * settings, returning a list of index numbers.
243 public static function userNamespaces( $user ) {
244 $arr = Preferences
::loadOldSearchNs( $user );
245 $searchableNamespaces = SearchEngine
::searchableNamespaces();
247 $arr = array_intersect( $arr, array_keys($searchableNamespaces) ); // Filter
253 * Find snippet highlight settings for a given user
256 * @return Array contextlines, contextchars
258 public static function userHighlightPrefs( &$user ){
259 //$contextlines = $user->getOption( 'contextlines', 5 );
260 //$contextchars = $user->getOption( 'contextchars', 50 );
261 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
262 $contextchars = 75; // same as above.... :P
263 return array($contextlines, $contextchars);
267 * An array of namespaces indexes to be searched by default
271 public static function defaultNamespaces(){
272 global $wgNamespacesToBeSearchedDefault;
274 return array_keys($wgNamespacesToBeSearchedDefault, true);
278 * Get a list of namespace names useful for showing in tooltips
281 * @param $namespaces Array
283 public static function namespacesAsText( $namespaces ){
286 $formatted = array_map( array($wgContLang,'getFormattedNsText'), $namespaces );
287 foreach( $formatted as $key => $ns ){
289 $formatted[$key] = wfMsg( 'blanknamespace' );
295 * Return the help namespaces to be shown on Special:Search
299 public static function helpNamespaces() {
300 global $wgNamespacesToBeSearchedHelp;
302 return array_keys( $wgNamespacesToBeSearchedHelp, true );
306 * Return a 'cleaned up' search string
308 * @param $text String
311 function filter( $text ) {
312 $lc = $this->legalSearchChars();
313 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
316 * Load up the appropriate search engine class for the currently
317 * active database backend, and return a configured instance.
319 * @return SearchEngine
321 public static function create() {
322 global $wgSearchType;
323 $dbr = wfGetDB( DB_SLAVE
);
324 if( $wgSearchType ) {
325 $class = $wgSearchType;
327 $class = $dbr->getSearchEngine();
329 $search = new $class( $dbr );
330 $search->setLimitOffset(0,0);
335 * Create or update the search index record for the given page.
336 * Title and text should be pre-processed.
340 * @param $title String
341 * @param $text String
343 function update( $id, $title, $text ) {
348 * Update a search index record's title only.
349 * Title should be pre-processed.
353 * @param $title String
355 function updateTitle( $id, $title ) {
360 * Get OpenSearch suggestion template
364 public static function getOpenSearchTemplate() {
365 global $wgOpenSearchTemplate, $wgServer, $wgScriptPath;
366 if( $wgOpenSearchTemplate ) {
367 return $wgOpenSearchTemplate;
369 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
370 if( !$ns ) $ns = "0";
371 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace='.$ns;
376 * Get internal MediaWiki Suggest template
380 public static function getMWSuggestTemplate() {
381 global $wgMWSuggestTemplate, $wgServer, $wgScriptPath;
382 if($wgMWSuggestTemplate)
383 return $wgMWSuggestTemplate;
385 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
392 class SearchResultSet
{
394 * Fetch an array of regular expression fragments for matching
395 * the search terms as parsed by this engine in a text extract.
400 function termMatches() {
409 * Return true if results are included in this result set.
414 function hasResults() {
419 * Some search modes return a total hit count for the query
420 * in the entire article database. This may include pages
421 * in namespaces that would not be matched on the given
424 * Return null if no total hits number is supported.
428 function getTotalHits() {
433 * Some search modes return a suggested alternate term if there are
434 * no exact hits. Returns true if there is one on this set.
438 function hasSuggestion() {
443 * @return String: suggested query, null if none
445 function getSuggestionQuery(){
450 * @return String: HTML highlighted suggested query, '' if none
452 function getSuggestionSnippet(){
457 * Return information about how and from where the results were fetched,
458 * should be useful for diagnostics and debugging
467 * Return a result set of hits on other (multiple) wikis associated with this one
469 * @return SearchResultSet
471 function getInterwikiResults() {
476 * Check if there are results on other wikis
480 function hasInterwikiResults() {
481 return $this->getInterwikiResults() != null;
486 * Fetches next search result, or false.
489 * @return SearchResult
496 * Frees the result set, if applicable.
507 class SearchResultTooMany
{
508 ## Some search engines may bail out if too many matches are found
513 * @todo Fixme: This class is horribly factored. It would probably be better to
514 * have a useful base class to which you pass some standard information, then
515 * let the fancy self-highlighters extend that.
519 var $mRevision = null;
522 function __construct( $row ) {
523 $this->mTitle
= Title
::makeTitle( $row->page_namespace
, $row->page_title
);
524 if( !is_null($this->mTitle
) ){
525 $this->mRevision
= Revision
::newFromTitle( $this->mTitle
);
526 if( $this->mTitle
->getNamespace() === NS_FILE
)
527 $this->mImage
= wfFindFile( $this->mTitle
);
532 * Check if this is result points to an invalid title
536 function isBrokenTitle(){
537 if( is_null($this->mTitle
) )
543 * Check if target page is missing, happens when index is out of date
547 function isMissingRevision(){
548 return !$this->mRevision
&& !$this->mImage
;
554 function getTitle() {
555 return $this->mTitle
;
559 * @return Double or null if not supported
561 function getScore() {
566 * Lazy initialization of article text from DB
568 protected function initText(){
569 if( !isset($this->mText
) ){
570 if($this->mRevision
!= null)
571 $this->mText
= $this->mRevision
->getText();
572 else // TODO: can we fetch raw wikitext for commons images?
579 * @param $terms Array: terms to highlight
580 * @return String: highlighted text snippet, null (and not '') if not supported
582 function getTextSnippet($terms){
583 global $wgUser, $wgAdvancedSearchHighlighting;
585 list($contextlines,$contextchars) = SearchEngine
::userHighlightPrefs($wgUser);
586 $h = new SearchHighlighter();
587 if( $wgAdvancedSearchHighlighting )
588 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
590 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
594 * @param $terms Array: terms to highlight
595 * @return String: highlighted title, '' if not supported
597 function getTitleSnippet($terms){
602 * @param $terms Array: terms to highlight
603 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
605 function getRedirectSnippet($terms){
610 * @return Title object for the redirect to this page, null if none or not supported
612 function getRedirectTitle(){
617 * @return string highlighted relevant section name, null if none or not supported
619 function getSectionSnippet(){
624 * @return Title object (pagename+fragment) for the section, null if none or not supported
626 function getSectionTitle(){
631 * @return String: timestamp
633 function getTimestamp(){
634 if( $this->mRevision
)
635 return $this->mRevision
->getTimestamp();
636 else if( $this->mImage
)
637 return $this->mImage
->getTimestamp();
642 * @return Integer: number of words
644 function getWordCount(){
646 return str_word_count( $this->mText
);
650 * @return Integer: size in bytes
652 function getByteSize(){
654 return strlen( $this->mText
);
658 * @return Boolean if hit has related articles
660 function hasRelated(){
665 * @return String: interwiki prefix of the title (return iw even if title is broken)
667 function getInterwikiPrefix(){
673 * Highlight bits of wikitext
677 class SearchHighlighter
{
678 var $mCleanWikitext = true;
680 function SearchHighlighter($cleanupWikitext = true){
681 $this->mCleanWikitext
= $cleanupWikitext;
685 * Default implementation of wikitext highlighting
687 * @param $text String
688 * @param $terms Array: terms to highlight (unescaped)
689 * @param $contextlines Integer
690 * @param $contextchars Integer
693 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
694 global $wgLang, $wgContLang;
695 global $wgSearchHighlightBoundaries;
701 // spli text into text + templates/links/tables
702 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
703 // first capture group is for detecting nested templates/links/tables/references
704 $endPatterns = array(
705 1 => '/(\{\{)|(\}\})/', // template
706 2 => '/(\[\[)|(\]\])/', // image
707 3 => "/(\n\\{\\|)|(\n\\|\\})/"); // table
709 // FIXME: this should prolly be a hook or something
710 if(function_exists('wfCite')){
711 $spat .= '|(<ref>)'; // references via cite extension
712 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
715 $textExt = array(); // text extracts
716 $otherExt = array(); // other extracts
717 wfProfileIn( "$fname-split" );
719 $textLen = strlen($text);
720 $count = 0; // sequence number to maintain ordering
721 while( $start < $textLen ){
722 // find start of template/image/table
723 if( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ){
725 foreach($matches as $key => $val){
726 if($key > 0 && $val[1] != -1){
728 // see if this is an image link
729 $ns = substr($val[0],2,-1);
730 if( $wgContLang->getNsIndex($ns) != NS_FILE
)
734 $epat = $endPatterns[$key];
735 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
741 // find end (and detect any nested elements)
743 $offset = $start +
1;
745 while( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ){
746 if( array_key_exists(2,$endMatches) ){
749 $len = strlen($endMatches[2][0]);
750 $off = $endMatches[2][1];
751 $this->splitAndAdd( $otherExt, $count,
752 substr( $text, $start, $off +
$len - $start ) );
753 $start = $off +
$len;
757 // end of nested element
764 $offset = $endMatches[0][1] +
strlen($endMatches[0][0]);
767 // couldn't find appropriate closing tag, skip
768 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen($matches[0][0]) ) );
769 $start +
= strlen($matches[0][0]);
774 // else: add as text extract
775 $this->splitAndAdd( $textExt, $count, substr($text,$start) );
779 $all = $textExt +
$otherExt; // these have disjunct key sets
781 wfProfileOut( "$fname-split" );
784 foreach( $terms as $index => $term ) {
785 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
786 if(preg_match('/[\x80-\xff]/', $term) ){
787 $terms[$index] = preg_replace_callback('/./us',array($this,'caseCallback'),$terms[$index]);
789 $terms[$index] = $term;
792 $anyterm = implode( '|', $terms );
793 $phrase = implode("$wgSearchHighlightBoundaries+", $terms );
795 // FIXME: a hack to scale contextchars, a correct solution
796 // would be to have contextchars actually be char and not byte
797 // length, and do proper utf-8 substrings and lengths everywhere,
798 // but PHP is making that very hard and unclean to implement :(
799 $scale = strlen($anyterm) / mb_strlen($anyterm);
800 $contextchars = intval( $contextchars * $scale );
802 $patPre = "(^|$wgSearchHighlightBoundaries)";
803 $patPost = "($wgSearchHighlightBoundaries|$)";
805 $pat1 = "/(".$phrase.")/ui";
806 $pat2 = "/$patPre(".$anyterm.")$patPost/ui";
808 wfProfileIn( "$fname-extract" );
810 $left = $contextlines;
815 // show beginning only if it contains all words
818 foreach($textExt as $index => $line){
819 if(strlen($line)>0 && $line[0] != ';' && $line[0] != ':'){
820 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
827 // check if first text contains all terms
828 foreach($terms as $term){
829 if( ! preg_match("/$patPre".$term."$patPost/ui", $firstText) ){
835 $snippets[$first] = $firstText;
836 $offsets[$first] = 0;
840 // match whole query on text
841 $this->process($pat1, $textExt, $left, $contextchars, $snippets, $offsets);
842 // match whole query on templates/tables/images
843 $this->process($pat1, $otherExt, $left, $contextchars, $snippets, $offsets);
844 // match any words on text
845 $this->process($pat2, $textExt, $left, $contextchars, $snippets, $offsets);
846 // match any words on templates/tables/images
847 $this->process($pat2, $otherExt, $left, $contextchars, $snippets, $offsets);
852 // add extra chars to each snippet to make snippets constant size
854 if( count( $snippets ) == 0){
855 // couldn't find the target words, just show beginning of article
856 $targetchars = $contextchars * $contextlines;
857 $snippets[$first] = '';
858 $offsets[$first] = 0;
860 // if begin of the article contains the whole phrase, show only that !!
861 if( array_key_exists($first,$snippets) && preg_match($pat1,$snippets[$first])
862 && $offsets[$first] < $contextchars * 2 ){
863 $snippets = array ($first => $snippets[$first]);
866 // calc by how much to extend existing snippets
867 $targetchars = intval( ($contextchars * $contextlines) / count ( $snippets ) );
870 foreach($snippets as $index => $line){
871 $extended[$index] = $line;
872 $len = strlen($line);
873 if( $len < $targetchars - 20 ){
874 // complete this line
875 if($len < strlen( $all[$index] )){
876 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index]+
$targetchars, $offsets[$index]);
877 $len = strlen( $extended[$index] );
882 while( $len < $targetchars - 20
883 && array_key_exists($add,$all)
884 && !array_key_exists($add,$snippets) ){
886 $tt = "\n".$this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
887 $extended[$add] = $tt;
888 $len +
= strlen( $tt );
894 //$snippets = array_map('htmlspecialchars', $extended);
895 $snippets = $extended;
898 foreach($snippets as $index => $line){
900 $extract .= $line; // first line
901 elseif($last+
1 == $index && $offsets[$last]+
strlen($snippets[$last]) >= strlen($all[$last]))
902 $extract .= " ".$line; // continous lines
904 $extract .= '<b> ... </b>' . $line;
909 $extract .= '<b> ... </b>';
911 $processed = array();
912 foreach($terms as $term){
913 if( ! isset($processed[$term]) ){
914 $pat3 = "/$patPre(".$term.")$patPost/ui"; // highlight word
915 $extract = preg_replace( $pat3,
916 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
917 $processed[$term] = true;
921 wfProfileOut( "$fname-extract" );
927 * Split text into lines and add it to extracts array
929 * @param $extracts Array: index -> $line
930 * @param $count Integer
931 * @param $text String
933 function splitAndAdd(&$extracts, &$count, $text){
934 $split = explode( "\n", $this->mCleanWikitext?
$this->removeWiki($text) : $text );
935 foreach($split as $line){
938 $extracts[$count++
] = $tt;
943 * Do manual case conversion for non-ascii chars
945 * @param $matches Array
947 function caseCallback($matches){
949 if( strlen($matches[0]) > 1 ){
950 return '['.$wgContLang->lc($matches[0]).$wgContLang->uc($matches[0]).']';
956 * Extract part of the text from start to end, but by
957 * not chopping up words
958 * @param $text String
959 * @param $start Integer
960 * @param $end Integer
961 * @param $posStart Integer: (out) actual start position
962 * @param $posEnd Integer: (out) actual end position
965 function extract($text, $start, $end, &$posStart = null, &$posEnd = null ){
969 $start = $this->position( $text, $start, 1 );
970 if( $end >= strlen($text) )
971 $end = strlen($text);
973 $end = $this->position( $text, $end );
975 if(!is_null($posStart))
977 if(!is_null($posEnd))
981 return substr($text, $start, $end-$start);
987 * Find a nonletter near a point (index) in the text
989 * @param $text String
990 * @param $point Integer
991 * @param $offset Integer: offset to found index
992 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
994 function position($text, $point, $offset=0 ){
996 $s = max( 0, $point - $tolerance );
997 $l = min( strlen($text), $point +
$tolerance ) - $s;
999 if( preg_match('/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr($text,$s,$l), $m, PREG_OFFSET_CAPTURE
) ){
1000 return $m[0][1] +
$s +
$offset;
1002 // check if point is on a valid first UTF8 char
1003 $char = ord( $text[$point] );
1004 while( $char >= 0x80 && $char < 0xc0 ) {
1005 // skip trailing bytes
1007 if($point >= strlen($text))
1008 return strlen($text);
1009 $char = ord( $text[$point] );
1017 * Search extracts for a pattern, and return snippets
1019 * @param $pattern String: regexp for matching lines
1020 * @param $extracts Array: extracts to search
1021 * @param $linesleft Integer: number of extracts to make
1022 * @param $contextchars Integer: length of snippet
1023 * @param $out Array: map for highlighted snippets
1024 * @param $offsets Array: map of starting points of snippets
1027 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ){
1029 return; // nothing to do
1030 foreach($extracts as $index => $line){
1031 if( array_key_exists($index,$out) )
1032 continue; // this line already highlighted
1035 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1039 $len = strlen($m[0][0]);
1040 if($offset +
$len < $contextchars)
1042 elseif( $len > $contextchars)
1045 $begin = $offset +
intval( ($len - $contextchars) / 2 );
1047 $end = $begin +
$contextchars;
1050 // basic snippet from this line
1051 $out[$index] = $this->extract($line,$begin,$end,$posBegin);
1052 $offsets[$index] = $posBegin;
1060 * Basic wikitext removal
1063 function removeWiki($text) {
1064 $fname = __METHOD__
;
1065 wfProfileIn( $fname );
1067 //$text = preg_replace("/'{2,5}/", "", $text);
1068 //$text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1069 //$text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1070 //$text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1071 //$text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1072 //$text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1073 $text = preg_replace("/\\{\\{([^|]+?)\\}\\}/", "", $text);
1074 $text = preg_replace("/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text);
1075 $text = preg_replace("/\\[\\[([^|]+?)\\]\\]/", "\\1", $text);
1076 $text = preg_replace_callback("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array($this,'linkReplace'), $text);
1077 //$text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1078 $text = preg_replace("/<\/?[^>]+>/", "", $text);
1079 $text = preg_replace("/'''''/", "", $text);
1080 $text = preg_replace("/('''|<\/?[iIuUbB]>)/", "", $text);
1081 $text = preg_replace("/''/", "", $text);
1083 wfProfileOut( $fname );
1088 * callback to replace [[target|caption]] kind of links, if
1089 * the target is category or image, leave it
1091 * @param $matches Array
1093 function linkReplace($matches){
1094 $colon = strpos( $matches[1], ':' );
1095 if( $colon === false )
1096 return $matches[2]; // replace with caption
1098 $ns = substr( $matches[1], 0, $colon );
1099 $index = $wgContLang->getNsIndex($ns);
1100 if( $index !== false && ($index == NS_FILE ||
$index == NS_CATEGORY
) )
1101 return $matches[0]; // return the whole thing
1108 * Simple & fast snippet extraction, but gives completely unrelevant
1111 * @param $text String
1112 * @param $terms Array
1113 * @param $contextlines Integer
1114 * @param $contextchars Integer
1117 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1118 global $wgLang, $wgContLang;
1119 $fname = __METHOD__
;
1121 $lines = explode( "\n", $text );
1123 $terms = implode( '|', $terms );
1124 $max = intval( $contextchars ) +
1;
1125 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1130 wfProfileIn( "$fname-extract" );
1131 foreach ( $lines as $line ) {
1132 if ( 0 == $contextlines ) {
1137 if ( ! preg_match( $pat1, $line, $m ) ) {
1141 $pre = $wgContLang->truncate( $m[1], -$contextchars );
1143 if ( count( $m ) < 3 ) {
1146 $post = $wgContLang->truncate( $m[3], $contextchars );
1151 $line = htmlspecialchars( $pre . $found . $post );
1152 $pat2 = '/(' . $terms . ")/i";
1153 $line = preg_replace( $pat2,
1154 "<span class='searchmatch'>\\1</span>", $line );
1156 $extract .= "${line}\n";
1158 wfProfileOut( "$fname-extract" );
1166 * Dummy class to be used when non-supported Database engine is present.
1167 * @todo Fixme: dummy class should probably try something at least mildly useful,
1168 * such as a LIKE search through titles.
1171 class SearchEngineDummy
extends SearchEngine
{