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 ) {
66 global $wgContLang, $wgSecondaryGoNamespaces;
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 # If a match is not found in the main namespace look in secondary go namespaces.
92 if( $wgSecondaryGoNamespaces && $title->getNamespace() == NS_MAIN
) {
93 foreach( $wgSecondaryGoNamespaces as $ns ) {
94 $title = Title
::newFromText( $term, $ns );
95 if( $title && $title->exists() ) return $title;
99 # Now try all lower case (i.e. first letter capitalized)
101 $title = Title
::newFromText( $wgContLang->lc( $term ) );
102 if ( $title && $title->exists() ) {
106 # Now try capitalized string
108 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
109 if ( $title && $title->exists() ) {
113 # Now try all upper case
115 $title = Title
::newFromText( $wgContLang->uc( $term ) );
116 if ( $title && $title->exists() ) {
120 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
121 $title = Title
::newFromText( $wgContLang->ucwordbreaks($term) );
122 if ( $title && $title->exists() ) {
126 // Give hooks a chance at better match variants
128 if( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
133 $title = Title
::newFromText( $searchterm );
135 # Entering an IP address goes to the contributions page
136 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP($title->getText() ) )
137 || User
::isIP( trim( $searchterm ) ) ) {
138 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
142 # Entering a user goes to the user page whether it's there or not
143 if ( $title->getNamespace() == NS_USER
) {
147 # Go to images that exist even if there's no local page.
148 # There may have been a funny upload, or it may be on a shared
149 # file repository such as Wikimedia Commons.
150 if( $title->getNamespace() == NS_FILE
) {
151 $image = wfFindFile( $title );
157 # MediaWiki namespace? Page may be "implied" if not customized.
158 # Just return it, with caps forced as the message system likes it.
159 if( $title->getNamespace() == NS_MEDIAWIKI
) {
160 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
163 # Quoted term? Try without the quotes...
165 if( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
166 return SearchEngine
::getNearMatch( $matches[1] );
172 public static function legalSearchChars() {
173 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
177 * Set the maximum number of results to return
178 * and how many to skip before returning the first.
180 * @param $limit Integer
181 * @param $offset Integer
183 function setLimitOffset( $limit, $offset = 0 ) {
184 $this->limit
= intval( $limit );
185 $this->offset
= intval( $offset );
189 * Set which namespaces the search should include.
190 * Give an array of namespace index numbers.
192 * @param $namespaces Array
194 function setNamespaces( $namespaces ) {
195 $this->namespaces
= $namespaces;
199 * Parse some common prefixes: all (search everything)
202 * @param $query String
204 function replacePrefixes( $query ){
207 if( strpos($query,':') === false )
208 return $query; // nothing to do
211 $allkeyword = wfMsgForContent('searchall').":";
212 if( strncmp($query, $allkeyword, strlen($allkeyword)) == 0 ){
213 $this->namespaces
= null;
214 $parsed = substr($query,strlen($allkeyword));
215 } else if( strpos($query,':') !== false ) {
216 $prefix = substr($query,0,strpos($query,':'));
217 $index = $wgContLang->getNsIndex($prefix);
218 if($index !== false){
219 $this->namespaces
= array($index);
220 $parsed = substr($query,strlen($prefix)+
1);
223 if(trim($parsed) == '')
224 return $query; // prefix was the whole query
230 * Make a list of searchable namespaces and their canonical names.
233 public static function searchableNamespaces() {
236 foreach( $wgContLang->getNamespaces() as $ns => $name ) {
237 if( $ns >= NS_MAIN
) {
245 * Extract default namespaces to search from the given user's
246 * settings, returning a list of index numbers.
251 public static function userNamespaces( $user ) {
252 global $wgSearchEverythingOnlyLoggedIn;
254 // get search everything preference, that can be set to be read for logged-in users
255 $searcheverything = false;
256 if( ( $wgSearchEverythingOnlyLoggedIn && $user->isLoggedIn() )
257 ||
!$wgSearchEverythingOnlyLoggedIn )
258 $searcheverything = $user->getOption('searcheverything');
260 // searcheverything overrides other options
261 if( $searcheverything )
262 return array_keys(SearchEngine
::searchableNamespaces());
264 $arr = Preferences
::loadOldSearchNs( $user );
265 $searchableNamespaces = SearchEngine
::searchableNamespaces();
267 $arr = array_intersect( $arr, array_keys($searchableNamespaces) ); // Filter
273 * Find snippet highlight settings for a given user
276 * @return Array contextlines, contextchars
278 public static function userHighlightPrefs( &$user ){
279 //$contextlines = $user->getOption( 'contextlines', 5 );
280 //$contextchars = $user->getOption( 'contextchars', 50 );
281 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
282 $contextchars = 75; // same as above.... :P
283 return array($contextlines, $contextchars);
287 * An array of namespaces indexes to be searched by default
291 public static function defaultNamespaces(){
292 global $wgNamespacesToBeSearchedDefault;
294 return array_keys($wgNamespacesToBeSearchedDefault, true);
298 * Get a list of namespace names useful for showing in tooltips
301 * @param $namespaces Array
303 public static function namespacesAsText( $namespaces ){
306 $formatted = array_map( array($wgContLang,'getFormattedNsText'), $namespaces );
307 foreach( $formatted as $key => $ns ){
309 $formatted[$key] = wfMsg( 'blanknamespace' );
315 * Return the help namespaces to be shown on Special:Search
319 public static function helpNamespaces() {
320 global $wgNamespacesToBeSearchedHelp;
322 return array_keys( $wgNamespacesToBeSearchedHelp, true );
326 * Return a 'cleaned up' search string
328 * @param $text String
331 function filter( $text ) {
332 $lc = $this->legalSearchChars();
333 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
336 * Load up the appropriate search engine class for the currently
337 * active database backend, and return a configured instance.
339 * @return SearchEngine
341 public static function create() {
342 global $wgSearchType;
343 $dbr = wfGetDB( DB_SLAVE
);
344 if( $wgSearchType ) {
345 $class = $wgSearchType;
347 $class = $dbr->getSearchEngine();
349 $search = new $class( $dbr );
350 $search->setLimitOffset(0,0);
355 * Create or update the search index record for the given page.
356 * Title and text should be pre-processed.
360 * @param $title String
361 * @param $text String
363 function update( $id, $title, $text ) {
368 * Update a search index record's title only.
369 * Title should be pre-processed.
373 * @param $title String
375 function updateTitle( $id, $title ) {
380 * Get OpenSearch suggestion template
384 public static function getOpenSearchTemplate() {
385 global $wgOpenSearchTemplate, $wgServer, $wgScriptPath;
386 if( $wgOpenSearchTemplate ) {
387 return $wgOpenSearchTemplate;
389 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
390 if( !$ns ) $ns = "0";
391 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace='.$ns;
396 * Get internal MediaWiki Suggest template
400 public static function getMWSuggestTemplate() {
401 global $wgMWSuggestTemplate, $wgServer, $wgScriptPath;
402 if($wgMWSuggestTemplate)
403 return $wgMWSuggestTemplate;
405 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
412 class SearchResultSet
{
414 * Fetch an array of regular expression fragments for matching
415 * the search terms as parsed by this engine in a text extract.
420 function termMatches() {
429 * Return true if results are included in this result set.
434 function hasResults() {
439 * Some search modes return a total hit count for the query
440 * in the entire article database. This may include pages
441 * in namespaces that would not be matched on the given
444 * Return null if no total hits number is supported.
448 function getTotalHits() {
453 * Some search modes return a suggested alternate term if there are
454 * no exact hits. Returns true if there is one on this set.
458 function hasSuggestion() {
463 * @return String: suggested query, null if none
465 function getSuggestionQuery(){
470 * @return String: HTML highlighted suggested query, '' if none
472 function getSuggestionSnippet(){
477 * Return information about how and from where the results were fetched,
478 * should be useful for diagnostics and debugging
487 * Return a result set of hits on other (multiple) wikis associated with this one
489 * @return SearchResultSet
491 function getInterwikiResults() {
496 * Check if there are results on other wikis
500 function hasInterwikiResults() {
501 return $this->getInterwikiResults() != null;
506 * Fetches next search result, or false.
509 * @return SearchResult
516 * Frees the result set, if applicable.
527 class SearchResultTooMany
{
528 ## Some search engines may bail out if too many matches are found
533 * @todo Fixme: This class is horribly factored. It would probably be better to
534 * have a useful base class to which you pass some standard information, then
535 * let the fancy self-highlighters extend that.
539 var $mRevision = null;
542 function __construct( $row ) {
543 $this->mTitle
= Title
::makeTitle( $row->page_namespace
, $row->page_title
);
544 if( !is_null($this->mTitle
) ){
545 $this->mRevision
= Revision
::newFromTitle( $this->mTitle
);
546 if( $this->mTitle
->getNamespace() === NS_FILE
)
547 $this->mImage
= wfFindFile( $this->mTitle
);
552 * Check if this is result points to an invalid title
556 function isBrokenTitle(){
557 if( is_null($this->mTitle
) )
563 * Check if target page is missing, happens when index is out of date
567 function isMissingRevision(){
568 return !$this->mRevision
&& !$this->mImage
;
574 function getTitle() {
575 return $this->mTitle
;
579 * @return Double or null if not supported
581 function getScore() {
586 * Lazy initialization of article text from DB
588 protected function initText(){
589 if( !isset($this->mText
) ){
590 if($this->mRevision
!= null)
591 $this->mText
= $this->mRevision
->getText();
592 else // TODO: can we fetch raw wikitext for commons images?
599 * @param $terms Array: terms to highlight
600 * @return String: highlighted text snippet, null (and not '') if not supported
602 function getTextSnippet($terms){
603 global $wgUser, $wgAdvancedSearchHighlighting;
605 list($contextlines,$contextchars) = SearchEngine
::userHighlightPrefs($wgUser);
606 $h = new SearchHighlighter();
607 if( $wgAdvancedSearchHighlighting )
608 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
610 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
614 * @param $terms Array: terms to highlight
615 * @return String: highlighted title, '' if not supported
617 function getTitleSnippet($terms){
622 * @param $terms Array: terms to highlight
623 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
625 function getRedirectSnippet($terms){
630 * @return Title object for the redirect to this page, null if none or not supported
632 function getRedirectTitle(){
637 * @return string highlighted relevant section name, null if none or not supported
639 function getSectionSnippet(){
644 * @return Title object (pagename+fragment) for the section, null if none or not supported
646 function getSectionTitle(){
651 * @return String: timestamp
653 function getTimestamp(){
654 if( $this->mRevision
)
655 return $this->mRevision
->getTimestamp();
656 else if( $this->mImage
)
657 return $this->mImage
->getTimestamp();
662 * @return Integer: number of words
664 function getWordCount(){
666 return str_word_count( $this->mText
);
670 * @return Integer: size in bytes
672 function getByteSize(){
674 return strlen( $this->mText
);
678 * @return Boolean if hit has related articles
680 function hasRelated(){
685 * @return String: interwiki prefix of the title (return iw even if title is broken)
687 function getInterwikiPrefix(){
693 * Highlight bits of wikitext
697 class SearchHighlighter
{
698 var $mCleanWikitext = true;
700 function SearchHighlighter($cleanupWikitext = true){
701 $this->mCleanWikitext
= $cleanupWikitext;
705 * Default implementation of wikitext highlighting
707 * @param $text String
708 * @param $terms Array: terms to highlight (unescaped)
709 * @param $contextlines Integer
710 * @param $contextchars Integer
713 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
714 global $wgLang, $wgContLang;
715 global $wgSearchHighlightBoundaries;
721 // spli text into text + templates/links/tables
722 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
723 // first capture group is for detecting nested templates/links/tables/references
724 $endPatterns = array(
725 1 => '/(\{\{)|(\}\})/', // template
726 2 => '/(\[\[)|(\]\])/', // image
727 3 => "/(\n\\{\\|)|(\n\\|\\})/"); // table
729 // FIXME: this should prolly be a hook or something
730 if(function_exists('wfCite')){
731 $spat .= '|(<ref>)'; // references via cite extension
732 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
735 $textExt = array(); // text extracts
736 $otherExt = array(); // other extracts
737 wfProfileIn( "$fname-split" );
739 $textLen = strlen($text);
740 $count = 0; // sequence number to maintain ordering
741 while( $start < $textLen ){
742 // find start of template/image/table
743 if( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ){
745 foreach($matches as $key => $val){
746 if($key > 0 && $val[1] != -1){
748 // see if this is an image link
749 $ns = substr($val[0],2,-1);
750 if( $wgContLang->getNsIndex($ns) != NS_FILE
)
754 $epat = $endPatterns[$key];
755 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
761 // find end (and detect any nested elements)
763 $offset = $start +
1;
765 while( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ){
766 if( array_key_exists(2,$endMatches) ){
769 $len = strlen($endMatches[2][0]);
770 $off = $endMatches[2][1];
771 $this->splitAndAdd( $otherExt, $count,
772 substr( $text, $start, $off +
$len - $start ) );
773 $start = $off +
$len;
777 // end of nested element
784 $offset = $endMatches[0][1] +
strlen($endMatches[0][0]);
787 // couldn't find appropriate closing tag, skip
788 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen($matches[0][0]) ) );
789 $start +
= strlen($matches[0][0]);
794 // else: add as text extract
795 $this->splitAndAdd( $textExt, $count, substr($text,$start) );
799 $all = $textExt +
$otherExt; // these have disjunct key sets
801 wfProfileOut( "$fname-split" );
804 foreach( $terms as $index => $term ) {
805 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
806 if(preg_match('/[\x80-\xff]/', $term) ){
807 $terms[$index] = preg_replace_callback('/./us',array($this,'caseCallback'),$terms[$index]);
809 $terms[$index] = $term;
812 $anyterm = implode( '|', $terms );
813 $phrase = implode("$wgSearchHighlightBoundaries+", $terms );
815 // FIXME: a hack to scale contextchars, a correct solution
816 // would be to have contextchars actually be char and not byte
817 // length, and do proper utf-8 substrings and lengths everywhere,
818 // but PHP is making that very hard and unclean to implement :(
819 $scale = strlen($anyterm) / mb_strlen($anyterm);
820 $contextchars = intval( $contextchars * $scale );
822 $patPre = "(^|$wgSearchHighlightBoundaries)";
823 $patPost = "($wgSearchHighlightBoundaries|$)";
825 $pat1 = "/(".$phrase.")/ui";
826 $pat2 = "/$patPre(".$anyterm.")$patPost/ui";
828 wfProfileIn( "$fname-extract" );
830 $left = $contextlines;
835 // show beginning only if it contains all words
838 foreach($textExt as $index => $line){
839 if(strlen($line)>0 && $line[0] != ';' && $line[0] != ':'){
840 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
847 // check if first text contains all terms
848 foreach($terms as $term){
849 if( ! preg_match("/$patPre".$term."$patPost/ui", $firstText) ){
855 $snippets[$first] = $firstText;
856 $offsets[$first] = 0;
860 // match whole query on text
861 $this->process($pat1, $textExt, $left, $contextchars, $snippets, $offsets);
862 // match whole query on templates/tables/images
863 $this->process($pat1, $otherExt, $left, $contextchars, $snippets, $offsets);
864 // match any words on text
865 $this->process($pat2, $textExt, $left, $contextchars, $snippets, $offsets);
866 // match any words on templates/tables/images
867 $this->process($pat2, $otherExt, $left, $contextchars, $snippets, $offsets);
872 // add extra chars to each snippet to make snippets constant size
874 if( count( $snippets ) == 0){
875 // couldn't find the target words, just show beginning of article
876 $targetchars = $contextchars * $contextlines;
877 $snippets[$first] = '';
878 $offsets[$first] = 0;
880 // if begin of the article contains the whole phrase, show only that !!
881 if( array_key_exists($first,$snippets) && preg_match($pat1,$snippets[$first])
882 && $offsets[$first] < $contextchars * 2 ){
883 $snippets = array ($first => $snippets[$first]);
886 // calc by how much to extend existing snippets
887 $targetchars = intval( ($contextchars * $contextlines) / count ( $snippets ) );
890 foreach($snippets as $index => $line){
891 $extended[$index] = $line;
892 $len = strlen($line);
893 if( $len < $targetchars - 20 ){
894 // complete this line
895 if($len < strlen( $all[$index] )){
896 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index]+
$targetchars, $offsets[$index]);
897 $len = strlen( $extended[$index] );
902 while( $len < $targetchars - 20
903 && array_key_exists($add,$all)
904 && !array_key_exists($add,$snippets) ){
906 $tt = "\n".$this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
907 $extended[$add] = $tt;
908 $len +
= strlen( $tt );
914 //$snippets = array_map('htmlspecialchars', $extended);
915 $snippets = $extended;
918 foreach($snippets as $index => $line){
920 $extract .= $line; // first line
921 elseif($last+
1 == $index && $offsets[$last]+
strlen($snippets[$last]) >= strlen($all[$last]))
922 $extract .= " ".$line; // continous lines
924 $extract .= '<b> ... </b>' . $line;
929 $extract .= '<b> ... </b>';
931 $processed = array();
932 foreach($terms as $term){
933 if( ! isset($processed[$term]) ){
934 $pat3 = "/$patPre(".$term.")$patPost/ui"; // highlight word
935 $extract = preg_replace( $pat3,
936 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
937 $processed[$term] = true;
941 wfProfileOut( "$fname-extract" );
947 * Split text into lines and add it to extracts array
949 * @param $extracts Array: index -> $line
950 * @param $count Integer
951 * @param $text String
953 function splitAndAdd(&$extracts, &$count, $text){
954 $split = explode( "\n", $this->mCleanWikitext?
$this->removeWiki($text) : $text );
955 foreach($split as $line){
958 $extracts[$count++
] = $tt;
963 * Do manual case conversion for non-ascii chars
965 * @param $matches Array
967 function caseCallback($matches){
969 if( strlen($matches[0]) > 1 ){
970 return '['.$wgContLang->lc($matches[0]).$wgContLang->uc($matches[0]).']';
976 * Extract part of the text from start to end, but by
977 * not chopping up words
978 * @param $text String
979 * @param $start Integer
980 * @param $end Integer
981 * @param $posStart Integer: (out) actual start position
982 * @param $posEnd Integer: (out) actual end position
985 function extract($text, $start, $end, &$posStart = null, &$posEnd = null ){
989 $start = $this->position( $text, $start, 1 );
990 if( $end >= strlen($text) )
991 $end = strlen($text);
993 $end = $this->position( $text, $end );
995 if(!is_null($posStart))
997 if(!is_null($posEnd))
1001 return substr($text, $start, $end-$start);
1007 * Find a nonletter near a point (index) in the text
1009 * @param $text String
1010 * @param $point Integer
1011 * @param $offset Integer: offset to found index
1012 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1014 function position($text, $point, $offset=0 ){
1016 $s = max( 0, $point - $tolerance );
1017 $l = min( strlen($text), $point +
$tolerance ) - $s;
1019 if( preg_match('/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr($text,$s,$l), $m, PREG_OFFSET_CAPTURE
) ){
1020 return $m[0][1] +
$s +
$offset;
1022 // check if point is on a valid first UTF8 char
1023 $char = ord( $text[$point] );
1024 while( $char >= 0x80 && $char < 0xc0 ) {
1025 // skip trailing bytes
1027 if($point >= strlen($text))
1028 return strlen($text);
1029 $char = ord( $text[$point] );
1037 * Search extracts for a pattern, and return snippets
1039 * @param $pattern String: regexp for matching lines
1040 * @param $extracts Array: extracts to search
1041 * @param $linesleft Integer: number of extracts to make
1042 * @param $contextchars Integer: length of snippet
1043 * @param $out Array: map for highlighted snippets
1044 * @param $offsets Array: map of starting points of snippets
1047 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ){
1049 return; // nothing to do
1050 foreach($extracts as $index => $line){
1051 if( array_key_exists($index,$out) )
1052 continue; // this line already highlighted
1055 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1059 $len = strlen($m[0][0]);
1060 if($offset +
$len < $contextchars)
1062 elseif( $len > $contextchars)
1065 $begin = $offset +
intval( ($len - $contextchars) / 2 );
1067 $end = $begin +
$contextchars;
1070 // basic snippet from this line
1071 $out[$index] = $this->extract($line,$begin,$end,$posBegin);
1072 $offsets[$index] = $posBegin;
1080 * Basic wikitext removal
1083 function removeWiki($text) {
1084 $fname = __METHOD__
;
1085 wfProfileIn( $fname );
1087 //$text = preg_replace("/'{2,5}/", "", $text);
1088 //$text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1089 //$text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1090 //$text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1091 //$text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1092 //$text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1093 $text = preg_replace("/\\{\\{([^|]+?)\\}\\}/", "", $text);
1094 $text = preg_replace("/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text);
1095 $text = preg_replace("/\\[\\[([^|]+?)\\]\\]/", "\\1", $text);
1096 $text = preg_replace_callback("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array($this,'linkReplace'), $text);
1097 //$text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1098 $text = preg_replace("/<\/?[^>]+>/", "", $text);
1099 $text = preg_replace("/'''''/", "", $text);
1100 $text = preg_replace("/('''|<\/?[iIuUbB]>)/", "", $text);
1101 $text = preg_replace("/''/", "", $text);
1103 wfProfileOut( $fname );
1108 * callback to replace [[target|caption]] kind of links, if
1109 * the target is category or image, leave it
1111 * @param $matches Array
1113 function linkReplace($matches){
1114 $colon = strpos( $matches[1], ':' );
1115 if( $colon === false )
1116 return $matches[2]; // replace with caption
1118 $ns = substr( $matches[1], 0, $colon );
1119 $index = $wgContLang->getNsIndex($ns);
1120 if( $index !== false && ($index == NS_FILE ||
$index == NS_CATEGORY
) )
1121 return $matches[0]; // return the whole thing
1128 * Simple & fast snippet extraction, but gives completely unrelevant
1131 * @param $text String
1132 * @param $terms Array
1133 * @param $contextlines Integer
1134 * @param $contextchars Integer
1137 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1138 global $wgLang, $wgContLang;
1139 $fname = __METHOD__
;
1141 $lines = explode( "\n", $text );
1143 $terms = implode( '|', $terms );
1144 $max = intval( $contextchars ) +
1;
1145 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1150 wfProfileIn( "$fname-extract" );
1151 foreach ( $lines as $line ) {
1152 if ( 0 == $contextlines ) {
1157 if ( ! preg_match( $pat1, $line, $m ) ) {
1161 $pre = $wgContLang->truncate( $m[1], -$contextchars );
1163 if ( count( $m ) < 3 ) {
1166 $post = $wgContLang->truncate( $m[3], $contextchars );
1171 $line = htmlspecialchars( $pre . $found . $post );
1172 $pat2 = '/(' . $terms . ")/i";
1173 $line = preg_replace( $pat2,
1174 "<span class='searchmatch'>\\1</span>", $line );
1176 $extract .= "${line}\n";
1178 wfProfileOut( "$fname-extract" );
1186 * Dummy class to be used when non-supported Database engine is present.
1187 * @todo Fixme: dummy class should probably try something at least mildly useful,
1188 * such as a LIKE search through titles.
1191 class SearchEngineDummy
extends SearchEngine
{