3 * @defgroup Search Search
10 * Contain a class for special pages
16 var $searchTerms = array();
17 var $namespaces = array( NS_MAIN
);
18 var $showRedirects = false;
21 * Perform a full text search query and return a result set.
22 * If title searches are not supported or disabled, return null.
24 * @param string $term - Raw search term
25 * @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.
37 * @param string $term - Raw search term
38 * @return SearchResultSet
42 function searchTitle( $term ) {
46 /** If this search backend can list/unlist redirects */
47 function acceptListRedirects() {
52 * If an exact title match can be find, or a very slightly close match,
53 * return the title. If no match, returns NULL.
58 public static function getNearMatch( $searchterm ) {
61 $allSearchTerms = array($searchterm);
63 if($wgContLang->hasVariants()){
64 $allSearchTerms = array_merge($allSearchTerms,$wgContLang->convertLinkToAllVariants($searchterm));
67 foreach($allSearchTerms as $term){
69 # Exact match? No need to look further.
70 $title = Title
::newFromText( $term );
74 if ( $title->getNamespace() == NS_SPECIAL ||
$title->isExternal()
75 ||
$title->exists() ) {
79 # Now try all lower case (i.e. first letter capitalized)
81 $title = Title
::newFromText( $wgContLang->lc( $term ) );
82 if ( $title && $title->exists() ) {
86 # Now try capitalized string
88 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
89 if ( $title && $title->exists() ) {
93 # Now try all upper case
95 $title = Title
::newFromText( $wgContLang->uc( $term ) );
96 if ( $title && $title->exists() ) {
100 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
101 $title = Title
::newFromText( $wgContLang->ucwordbreaks($term) );
102 if ( $title && $title->exists() ) {
106 // Give hooks a chance at better match variants
108 if( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
113 $title = Title
::newFromText( $searchterm );
115 # Entering an IP address goes to the contributions page
116 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP($title->getText() ) )
117 || User
::isIP( trim( $searchterm ) ) ) {
118 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
122 # Entering a user goes to the user page whether it's there or not
123 if ( $title->getNamespace() == NS_USER
) {
127 # Go to images that exist even if there's no local page.
128 # There may have been a funny upload, or it may be on a shared
129 # file repository such as Wikimedia Commons.
130 if( $title->getNamespace() == NS_FILE
) {
131 $image = wfFindFile( $title );
137 # MediaWiki namespace? Page may be "implied" if not customized.
138 # Just return it, with caps forced as the message system likes it.
139 if( $title->getNamespace() == NS_MEDIAWIKI
) {
140 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
143 # Quoted term? Try without the quotes...
145 if( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
146 return SearchEngine
::getNearMatch( $matches[1] );
152 public static function legalSearchChars() {
153 return "A-Za-z_'0-9\\x80-\\xFF\\-";
157 * Set the maximum number of results to return
158 * and how many to skip before returning the first.
164 function setLimitOffset( $limit, $offset = 0 ) {
165 $this->limit
= intval( $limit );
166 $this->offset
= intval( $offset );
170 * Set which namespaces the search should include.
171 * Give an array of namespace index numbers.
173 * @param array $namespaces
176 function setNamespaces( $namespaces ) {
177 $this->namespaces
= $namespaces;
181 * Parse some common prefixes: all (search everything)
184 * @param string $query
186 function replacePrefixes( $query ){
189 if( strpos($query,':') === false )
190 return $query; // nothing to do
193 $allkeyword = wfMsgForContent('searchall').":";
194 if( strncmp($query, $allkeyword, strlen($allkeyword)) == 0 ){
195 $this->namespaces
= null;
196 $parsed = substr($query,strlen($allkeyword));
197 } else if( strpos($query,':') !== false ) {
198 $prefix = substr($query,0,strpos($query,':'));
199 $index = $wgContLang->getNsIndex($prefix);
200 if($index !== false){
201 $this->namespaces
= array($index);
202 $parsed = substr($query,strlen($prefix)+
1);
205 if(trim($parsed) == '')
206 return $query; // prefix was the whole query
212 * Make a list of searchable namespaces and their canonical names.
215 public static function searchableNamespaces() {
218 foreach( $wgContLang->getNamespaces() as $ns => $name ) {
219 if( $ns >= NS_MAIN
) {
227 * Extract default namespaces to search from the given user's
228 * settings, returning a list of index numbers.
234 public static function userNamespaces( &$user ) {
236 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
237 if( $user->getOption( 'searchNs' . $ns ) ) {
245 * Find snippet highlight settings for a given user
248 * @return array contextlines, contextchars
251 public static function userHighlightPrefs( &$user ){
252 //$contextlines = $user->getOption( 'contextlines', 5 );
253 //$contextchars = $user->getOption( 'contextchars', 50 );
254 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
255 $contextchars = 75; // same as above.... :P
256 return array($contextlines, $contextchars);
260 * An array of namespaces indexes to be searched by default
265 public static function defaultNamespaces(){
266 global $wgNamespacesToBeSearchedDefault;
268 return array_keys($wgNamespacesToBeSearchedDefault, true);
272 * Get a list of namespace names useful for showing in tooltips
275 * @param unknown_type $namespaces
277 public static function namespacesAsText( $namespaces ){
280 $formatted = array_map( array($wgContLang,'getFormattedNsText'), $namespaces );
281 foreach( $formatted as $key => $ns ){
283 $formatted[$key] = wfMsg( 'blanknamespace' );
289 * An array of "project" namespaces indexes typically searched
295 public static function projectNamespaces() {
296 global $wgNamespacesToBeSearchedDefault, $wgNamespacesToBeSearchedProject;
298 return array_keys( $wgNamespacesToBeSearchedProject, true );
302 * An array of "project" namespaces indexes typically searched
303 * by logged-in users in addition to the default namespaces
308 public static function defaultAndProjectNamespaces() {
309 global $wgNamespacesToBeSearchedDefault, $wgNamespacesToBeSearchedProject;
311 return array_keys( $wgNamespacesToBeSearchedDefault +
312 $wgNamespacesToBeSearchedProject, true);
316 * Return a 'cleaned up' search string
321 function filter( $text ) {
322 $lc = $this->legalSearchChars();
323 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
326 * Load up the appropriate search engine class for the currently
327 * active database backend, and return a configured instance.
329 * @return SearchEngine
331 public static function create() {
332 global $wgSearchType;
333 $dbr = wfGetDB( DB_SLAVE
);
334 if( $wgSearchType ) {
335 $class = $wgSearchType;
337 $class = $dbr->getSearchEngine();
339 $search = new $class( $dbr );
340 $search->setLimitOffset(0,0);
345 * Create or update the search index record for the given page.
346 * Title and text should be pre-processed.
349 * @param string $title
350 * @param string $text
353 function update( $id, $title, $text ) {
358 * Update a search index record's title only.
359 * Title should be pre-processed.
362 * @param string $title
365 function updateTitle( $id, $title ) {
370 * Get OpenSearch suggestion template
375 public static function getOpenSearchTemplate() {
376 global $wgOpenSearchTemplate, $wgServer, $wgScriptPath;
377 if( $wgOpenSearchTemplate ) {
378 return $wgOpenSearchTemplate;
380 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
381 if( !$ns ) $ns = "0";
382 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace='.$ns;
387 * Get internal MediaWiki Suggest template
392 public static function getMWSuggestTemplate() {
393 global $wgMWSuggestTemplate, $wgServer, $wgScriptPath;
394 if($wgMWSuggestTemplate)
395 return $wgMWSuggestTemplate;
397 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace={namespaces}';
404 class SearchResultSet
{
406 * Fetch an array of regular expression fragments for matching
407 * the search terms as parsed by this engine in a text extract.
413 function termMatches() {
422 * Return true if results are included in this result set.
426 function hasResults() {
431 * Some search modes return a total hit count for the query
432 * in the entire article database. This may include pages
433 * in namespaces that would not be matched on the given
436 * Return null if no total hits number is supported.
441 function getTotalHits() {
446 * Some search modes return a suggested alternate term if there are
447 * no exact hits. Returns true if there is one on this set.
452 function hasSuggestion() {
457 * @return string suggested query, null if none
459 function getSuggestionQuery(){
464 * @return string highlighted suggested query, '' if none
466 function getSuggestionSnippet(){
471 * Return information about how and from where the results were fetched,
472 * should be useful for diagnostics and debugging
481 * Return a result set of hits on other (multiple) wikis associated with this one
483 * @return SearchResultSet
485 function getInterwikiResults() {
490 * Check if there are results on other wikis
494 function hasInterwikiResults() {
495 return $this->getInterwikiResults() != null;
500 * Fetches next search result, or false.
501 * @return SearchResult
510 * Frees the result set, if applicable.
522 class SearchResultTooMany
{
523 ## Some search engines may bail out if too many matches are found
528 * @fixme This class is horribly factored. It would probably be better to have
529 * a useful base class to which you pass some standard information, then let
530 * the fancy self-highlighters extend that.
534 var $mRevision = null;
537 function __construct( $row ) {
538 $this->mTitle
= Title
::makeTitle( $row->page_namespace
, $row->page_title
);
539 if( !is_null($this->mTitle
) ){
540 $this->mRevision
= Revision
::newFromTitle( $this->mTitle
);
541 if( $this->mTitle
->getNamespace() === NS_FILE
)
542 $this->mImage
= wfFindFile( $this->mTitle
);
547 * Check if this is result points to an invalid title
552 function isBrokenTitle(){
553 if( is_null($this->mTitle
) )
559 * Check if target page is missing, happens when index is out of date
564 function isMissingRevision(){
565 return !$this->mRevision
&& !$this->mImage
;
572 function getTitle() {
573 return $this->mTitle
;
577 * @return double or null if not supported
579 function getScore() {
584 * Lazy initialization of article text from DB
586 protected function initText(){
587 if( !isset($this->mText
) ){
588 if($this->mRevision
!= null)
589 $this->mText
= $this->mRevision
->getText();
590 else // TODO: can we fetch raw wikitext for commons images?
597 * @param array $terms terms to highlight
598 * @return string highlighted text snippet, null (and not '') if not supported
600 function getTextSnippet($terms){
601 global $wgUser, $wgAdvancedSearchHighlighting;
603 list($contextlines,$contextchars) = SearchEngine
::userHighlightPrefs($wgUser);
604 $h = new SearchHighlighter();
605 if( $wgAdvancedSearchHighlighting )
606 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
608 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
612 * @param array $terms terms to highlight
613 * @return string highlighted title, '' if not supported
615 function getTitleSnippet($terms){
620 * @param array $terms terms to highlight
621 * @return string highlighted redirect name (redirect to this page), '' if none or not supported
623 function getRedirectSnippet($terms){
628 * @return Title object for the redirect to this page, null if none or not supported
630 function getRedirectTitle(){
635 * @return string highlighted relevant section name, null if none or not supported
637 function getSectionSnippet(){
642 * @return Title object (pagename+fragment) for the section, null if none or not supported
644 function getSectionTitle(){
649 * @return string timestamp
651 function getTimestamp(){
652 if( $this->mRevision
)
653 return $this->mRevision
->getTimestamp();
654 else if( $this->mImage
)
655 return $this->mImage
->getTimestamp();
660 * @return int number of words
662 function getWordCount(){
664 return str_word_count( $this->mText
);
668 * @return int size in bytes
670 function getByteSize(){
672 return strlen( $this->mText
);
676 * @return boolean if hit has related articles
678 function hasRelated(){
683 * @return interwiki prefix of the title (return iw even if title is broken)
685 function getInterwikiPrefix(){
691 * Highlight bits of wikitext
695 class SearchHighlighter
{
696 var $mCleanWikitext = true;
698 function SearchHighlighter($cleanupWikitext = true){
699 $this->mCleanWikitext
= $cleanupWikitext;
703 * Default implementation of wikitext highlighting
705 * @param string $text
706 * @param array $terms Terms to highlight (unescaped)
707 * @param int $contextlines
708 * @param int $contextchars
711 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
712 global $wgLang, $wgContLang;
713 global $wgSearchHighlightBoundaries;
719 // spli text into text + templates/links/tables
720 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
721 // first capture group is for detecting nested templates/links/tables/references
722 $endPatterns = array(
723 1 => '/(\{\{)|(\}\})/', // template
724 2 => '/(\[\[)|(\]\])/', // image
725 3 => "/(\n\\{\\|)|(\n\\|\\})/"); // table
727 // FIXME: this should prolly be a hook or something
728 if(function_exists('wfCite')){
729 $spat .= '|(<ref>)'; // references via cite extension
730 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
733 $textExt = array(); // text extracts
734 $otherExt = array(); // other extracts
735 wfProfileIn( "$fname-split" );
737 $textLen = strlen($text);
738 $count = 0; // sequence number to maintain ordering
739 while( $start < $textLen ){
740 // find start of template/image/table
741 if( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ){
743 foreach($matches as $key => $val){
744 if($key > 0 && $val[1] != -1){
746 // see if this is an image link
747 $ns = substr($val[0],2,-1);
748 if( $wgContLang->getNsIndex($ns) != NS_FILE
)
752 $epat = $endPatterns[$key];
753 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
759 // find end (and detect any nested elements)
761 $offset = $start +
1;
763 while( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ){
764 if( array_key_exists(2,$endMatches) ){
767 $len = strlen($endMatches[2][0]);
768 $off = $endMatches[2][1];
769 $this->splitAndAdd( $otherExt, $count,
770 substr( $text, $start, $off +
$len - $start ) );
771 $start = $off +
$len;
775 // end of nested element
782 $offset = $endMatches[0][1] +
strlen($endMatches[0][0]);
785 // couldn't find appropriate closing tag, skip
786 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen($matches[0][0]) ) );
787 $start +
= strlen($matches[0][0]);
792 // else: add as text extract
793 $this->splitAndAdd( $textExt, $count, substr($text,$start) );
797 $all = $textExt +
$otherExt; // these have disjunct key sets
799 wfProfileOut( "$fname-split" );
802 foreach( $terms as $index => $term ) {
803 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
804 if(preg_match('/[\x80-\xff]/', $term) ){
805 $terms[$index] = preg_replace_callback('/./us',array($this,'caseCallback'),$terms[$index]);
807 $terms[$index] = $term;
810 $anyterm = implode( '|', $terms );
811 $phrase = implode("$wgSearchHighlightBoundaries+", $terms );
813 // FIXME: a hack to scale contextchars, a correct solution
814 // would be to have contextchars actually be char and not byte
815 // length, and do proper utf-8 substrings and lengths everywhere,
816 // but PHP is making that very hard and unclean to implement :(
817 $scale = strlen($anyterm) / mb_strlen($anyterm);
818 $contextchars = intval( $contextchars * $scale );
820 $patPre = "(^|$wgSearchHighlightBoundaries)";
821 $patPost = "($wgSearchHighlightBoundaries|$)";
823 $pat1 = "/(".$phrase.")/ui";
824 $pat2 = "/$patPre(".$anyterm.")$patPost/ui";
826 wfProfileIn( "$fname-extract" );
828 $left = $contextlines;
833 // show beginning only if it contains all words
836 foreach($textExt as $index => $line){
837 if(strlen($line)>0 && $line[0] != ';' && $line[0] != ':'){
838 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
845 // check if first text contains all terms
846 foreach($terms as $term){
847 if( ! preg_match("/$patPre".$term."$patPost/ui", $firstText) ){
853 $snippets[$first] = $firstText;
854 $offsets[$first] = 0;
858 // match whole query on text
859 $this->process($pat1, $textExt, $left, $contextchars, $snippets, $offsets);
860 // match whole query on templates/tables/images
861 $this->process($pat1, $otherExt, $left, $contextchars, $snippets, $offsets);
862 // match any words on text
863 $this->process($pat2, $textExt, $left, $contextchars, $snippets, $offsets);
864 // match any words on templates/tables/images
865 $this->process($pat2, $otherExt, $left, $contextchars, $snippets, $offsets);
870 // add extra chars to each snippet to make snippets constant size
872 if( count( $snippets ) == 0){
873 // couldn't find the target words, just show beginning of article
874 $targetchars = $contextchars * $contextlines;
875 $snippets[$first] = '';
876 $offsets[$first] = 0;
878 // if begin of the article contains the whole phrase, show only that !!
879 if( array_key_exists($first,$snippets) && preg_match($pat1,$snippets[$first])
880 && $offsets[$first] < $contextchars * 2 ){
881 $snippets = array ($first => $snippets[$first]);
884 // calc by how much to extend existing snippets
885 $targetchars = intval( ($contextchars * $contextlines) / count ( $snippets ) );
888 foreach($snippets as $index => $line){
889 $extended[$index] = $line;
890 $len = strlen($line);
891 if( $len < $targetchars - 20 ){
892 // complete this line
893 if($len < strlen( $all[$index] )){
894 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index]+
$targetchars, $offsets[$index]);
895 $len = strlen( $extended[$index] );
900 while( $len < $targetchars - 20
901 && array_key_exists($add,$all)
902 && !array_key_exists($add,$snippets) ){
904 $tt = "\n".$this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
905 $extended[$add] = $tt;
906 $len +
= strlen( $tt );
912 //$snippets = array_map('htmlspecialchars', $extended);
913 $snippets = $extended;
916 foreach($snippets as $index => $line){
918 $extract .= $line; // first line
919 elseif($last+
1 == $index && $offsets[$last]+
strlen($snippets[$last]) >= strlen($all[$last]))
920 $extract .= " ".$line; // continous lines
922 $extract .= '<b> ... </b>' . $line;
927 $extract .= '<b> ... </b>';
929 $processed = array();
930 foreach($terms as $term){
931 if( ! isset($processed[$term]) ){
932 $pat3 = "/$patPre(".$term.")$patPost/ui"; // highlight word
933 $extract = preg_replace( $pat3,
934 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
935 $processed[$term] = true;
939 wfProfileOut( "$fname-extract" );
945 * Split text into lines and add it to extracts array
947 * @param array $extracts index -> $line
949 * @param string $text
951 function splitAndAdd(&$extracts, &$count, $text){
952 $split = explode( "\n", $this->mCleanWikitext?
$this->removeWiki($text) : $text );
953 foreach($split as $line){
956 $extracts[$count++
] = $tt;
961 * Do manual case conversion for non-ascii chars
963 * @param unknown_type $matches
965 function caseCallback($matches){
967 if( strlen($matches[0]) > 1 ){
968 return '['.$wgContLang->lc($matches[0]).$wgContLang->uc($matches[0]).']';
974 * Extract part of the text from start to end, but by
975 * not chopping up words
976 * @param string $text
979 * @param int $posStart (out) actual start position
980 * @param int $posEnd (out) actual end position
983 function extract($text, $start, $end, &$posStart = null, &$posEnd = null ){
987 $start = $this->position( $text, $start, 1 );
988 if( $end >= strlen($text) )
989 $end = strlen($text);
991 $end = $this->position( $text, $end );
993 if(!is_null($posStart))
995 if(!is_null($posEnd))
999 return substr($text, $start, $end-$start);
1005 * Find a nonletter near a point (index) in the text
1007 * @param string $text
1009 * @param int $offset to found index
1010 * @return int nearest nonletter index, or beginning of utf8 char if none
1012 function position($text, $point, $offset=0 ){
1014 $s = max( 0, $point - $tolerance );
1015 $l = min( strlen($text), $point +
$tolerance ) - $s;
1017 if( preg_match('/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr($text,$s,$l), $m, PREG_OFFSET_CAPTURE
) ){
1018 return $m[0][1] +
$s +
$offset;
1020 // check if point is on a valid first UTF8 char
1021 $char = ord( $text[$point] );
1022 while( $char >= 0x80 && $char < 0xc0 ) {
1023 // skip trailing bytes
1025 if($point >= strlen($text))
1026 return strlen($text);
1027 $char = ord( $text[$point] );
1035 * Search extracts for a pattern, and return snippets
1037 * @param string $pattern regexp for matching lines
1038 * @param array $extracts extracts to search
1039 * @param int $linesleft number of extracts to make
1040 * @param int $contextchars length of snippet
1041 * @param array $out map for highlighted snippets
1042 * @param array $offsets map of starting points of snippets
1045 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ){
1047 return; // nothing to do
1048 foreach($extracts as $index => $line){
1049 if( array_key_exists($index,$out) )
1050 continue; // this line already highlighted
1053 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1057 $len = strlen($m[0][0]);
1058 if($offset +
$len < $contextchars)
1060 elseif( $len > $contextchars)
1063 $begin = $offset +
intval( ($len - $contextchars) / 2 );
1065 $end = $begin +
$contextchars;
1068 // basic snippet from this line
1069 $out[$index] = $this->extract($line,$begin,$end,$posBegin);
1070 $offsets[$index] = $posBegin;
1078 * Basic wikitext removal
1081 function removeWiki($text) {
1082 $fname = __METHOD__
;
1083 wfProfileIn( $fname );
1085 //$text = preg_replace("/'{2,5}/", "", $text);
1086 //$text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1087 //$text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1088 //$text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1089 //$text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1090 //$text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1091 $text = preg_replace("/\\{\\{([^|]+?)\\}\\}/", "", $text);
1092 $text = preg_replace("/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text);
1093 $text = preg_replace("/\\[\\[([^|]+?)\\]\\]/", "\\1", $text);
1094 $text = preg_replace_callback("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array($this,'linkReplace'), $text);
1095 //$text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1096 $text = preg_replace("/<\/?[^>]+>/", "", $text);
1097 $text = preg_replace("/'''''/", "", $text);
1098 $text = preg_replace("/('''|<\/?[iIuUbB]>)/", "", $text);
1099 $text = preg_replace("/''/", "", $text);
1101 wfProfileOut( $fname );
1106 * callback to replace [[target|caption]] kind of links, if
1107 * the target is category or image, leave it
1109 * @param array $matches
1111 function linkReplace($matches){
1112 $colon = strpos( $matches[1], ':' );
1113 if( $colon === false )
1114 return $matches[2]; // replace with caption
1116 $ns = substr( $matches[1], 0, $colon );
1117 $index = $wgContLang->getNsIndex($ns);
1118 if( $index !== false && ($index == NS_FILE ||
$index == NS_CATEGORY
) )
1119 return $matches[0]; // return the whole thing
1126 * Simple & fast snippet extraction, but gives completely unrelevant
1129 * @param string $text
1130 * @param array $terms
1131 * @param int $contextlines
1132 * @param int $contextchars
1135 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1136 global $wgLang, $wgContLang;
1137 $fname = __METHOD__
;
1139 $lines = explode( "\n", $text );
1141 $terms = implode( '|', $terms );
1142 $max = intval( $contextchars ) +
1;
1143 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1148 wfProfileIn( "$fname-extract" );
1149 foreach ( $lines as $line ) {
1150 if ( 0 == $contextlines ) {
1155 if ( ! preg_match( $pat1, $line, $m ) ) {
1159 $pre = $wgContLang->truncate( $m[1], -$contextchars, ' ... ' );
1161 if ( count( $m ) < 3 ) {
1164 $post = $wgContLang->truncate( $m[3], $contextchars, ' ... ' );
1169 $line = htmlspecialchars( $pre . $found . $post );
1170 $pat2 = '/(' . $terms . ")/i";
1171 $line = preg_replace( $pat2,
1172 "<span class='searchmatch'>\\1</span>", $line );
1174 $extract .= "${line}\n";
1176 wfProfileOut( "$fname-extract" );
1184 * Dummy class to be used when non-supported Database engine is present.
1185 * @fixme Dummy class should probably try something at least mildly useful,
1186 * such as a LIKE search through titles.
1189 class SearchEngineDummy
extends SearchEngine
{