6b77bb01038337e093afd6f27f041216797e76fd
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_IMAGE
) {
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 // for logged-in users use predefined defaults
237 if( $user->isLoggedIn() && $user->getOption( 'defaultusersearch', true ) )
238 return SearchEngine
::projectNamespaces();
240 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
241 if( $user->getOption( 'searchNs' . $ns ) ) {
249 * Find snippet highlight settings for a given user
252 * @return array contextlines, contextchars
255 public static function userHighlightPrefs( &$user ){
256 //$contextlines = $user->getOption( 'contextlines', 5 );
257 //$contextchars = $user->getOption( 'contextchars', 50 );
258 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
259 $contextchars = 75; // same as above.... :P
260 return array($contextlines, $contextchars);
264 * An array of namespaces indexes to be searched by default
269 public static function defaultNamespaces(){
270 global $wgNamespacesToBeSearchedDefault;
272 return array_keys($wgNamespacesToBeSearchedDefault, true);
276 * Get a list of namespace names useful for showing in tooltips
279 * @param unknown_type $namespaces
281 public static function namespacesAsText( $namespaces ){
284 $formatted = array_map( array($wgContLang,'getFormattedNsText'), $namespaces );
285 foreach( $formatted as $key => $ns ){
287 $formatted[$key] = wfMsg( 'blanknamespace' );
293 * An array of "project" namespaces indexes typically searched
299 public static function projectNamespaces(){
300 global $wgNamespacesToBeSearchedDefault, $wgNamespacesToBeSearchedProject;
302 return array_keys( $wgNamespacesToBeSearchedDefault +
303 $wgNamespacesToBeSearchedProject, true);
307 * Return a 'cleaned up' search string
312 function filter( $text ) {
313 $lc = $this->legalSearchChars();
314 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
317 * Load up the appropriate search engine class for the currently
318 * active database backend, and return a configured instance.
320 * @return SearchEngine
322 public static function create() {
323 global $wgSearchType;
324 $dbr = wfGetDB( DB_SLAVE
);
325 if( $wgSearchType ) {
326 $class = $wgSearchType;
328 $class = $dbr->getSearchEngine();
330 $search = new $class( $dbr );
331 $search->setLimitOffset(0,0);
336 * Create or update the search index record for the given page.
337 * Title and text should be pre-processed.
340 * @param string $title
341 * @param string $text
344 function update( $id, $title, $text ) {
349 * Update a search index record's title only.
350 * Title should be pre-processed.
353 * @param string $title
356 function updateTitle( $id, $title ) {
361 * Get OpenSearch suggestion template
366 public static function getOpenSearchTemplate() {
367 global $wgOpenSearchTemplate, $wgServer, $wgScriptPath;
368 if($wgOpenSearchTemplate)
369 return $wgOpenSearchTemplate;
371 $ns = implode(',',SearchEngine
::defaultNamespaces());
373 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace='.$ns;
378 * Get internal MediaWiki Suggest template
383 public static function getMWSuggestTemplate() {
384 global $wgMWSuggestTemplate, $wgServer, $wgScriptPath;
385 if($wgMWSuggestTemplate)
386 return $wgMWSuggestTemplate;
388 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace={namespaces}';
396 class SearchResultSet
{
398 * Fetch an array of regular expression fragments for matching
399 * the search terms as parsed by this engine in a text extract.
405 function termMatches() {
414 * Return true if results are included in this result set.
418 function hasResults() {
423 * Some search modes return a total hit count for the query
424 * in the entire article database. This may include pages
425 * in namespaces that would not be matched on the given
428 * Return null if no total hits number is supported.
433 function getTotalHits() {
438 * Some search modes return a suggested alternate term if there are
439 * no exact hits. Returns true if there is one on this set.
444 function hasSuggestion() {
449 * @return string suggested query, null if none
451 function getSuggestionQuery(){
456 * @return string highlighted suggested query, '' if none
458 function getSuggestionSnippet(){
463 * Return information about how and from where the results were fetched,
464 * should be useful for diagnostics and debugging
473 * Return a result set of hits on other (multiple) wikis associated with this one
475 * @return SearchResultSet
477 function getInterwikiResults() {
482 * Check if there are results on other wikis
486 function hasInterwikiResults() {
487 return $this->getInterwikiResults() != null;
492 * Fetches next search result, or false.
493 * @return SearchResult
502 * Frees the result set, if applicable.
514 class SearchResultTooMany
{
515 ## Some search engines may bail out if too many matches are found
520 * @fixme This class is horribly factored. It would probably be better to have
521 * a useful base class to which you pass some standard information, then let
522 * the fancy self-highlighters extend that.
526 var $mRevision = null;
529 function SearchResult( $row ) {
530 $this->mTitle
= Title
::makeTitle( $row->page_namespace
, $row->page_title
);
531 if( !is_null($this->mTitle
) ){
532 $this->mRevision
= Revision
::newFromTitle( $this->mTitle
);
533 if($this->mTitle
->getNamespace() == NS_IMAGE
)
534 $this->mImage
= wfFindFile( $this->mTitle
);
541 * Check if this is result points to an invalid title
546 function isBrokenTitle(){
547 if( is_null($this->mTitle
) )
553 * Check if target page is missing, happens when index is out of date
558 function isMissingRevision(){
559 if( !$this->mRevision
&& !$this->mImage
)
568 function getTitle() {
569 return $this->mTitle
;
573 * @return double or null if not supported
575 function getScore() {
580 * Lazy initialization of article text from DB
582 protected function initText(){
583 if( !isset($this->mText
) ){
584 if($this->mRevision
!= null)
585 $this->mText
= $this->mRevision
->getText();
592 * @param array $terms terms to highlight
593 * @return string highlighted text snippet, null (and not '') if not supported
595 function getTextSnippet($terms){
596 global $wgUser, $wgAdvancedSearchHighlighting;
598 list($contextlines,$contextchars) = SearchEngine
::userHighlightPrefs($wgUser);
599 $h = new SearchHighlighter();
600 if( $wgAdvancedSearchHighlighting )
601 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
603 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
607 * @param array $terms terms to highlight
608 * @return string highlighted title, '' if not supported
610 function getTitleSnippet($terms){
615 * @param array $terms terms to highlight
616 * @return string highlighted redirect name (redirect to this page), '' if none or not supported
618 function getRedirectSnippet($terms){
623 * @return Title object for the redirect to this page, null if none or not supported
625 function getRedirectTitle(){
630 * @return string highlighted relevant section name, null if none or not supported
632 function getSectionSnippet(){
637 * @return Title object (pagename+fragment) for the section, null if none or not supported
639 function getSectionTitle(){
644 * @return string timestamp
646 function getTimestamp(){
647 if($this->mRevision
!= null)
648 return $this->mRevision
->getTimestamp();
654 * @return int number of words
656 function getWordCount(){
658 return str_word_count( $this->mText
);
662 * @return int size in bytes
664 function getByteSize(){
666 return strlen( $this->mText
);
670 * @return boolean if hit has related articles
672 function hasRelated(){
677 * @return interwiki prefix of the title (return iw even if title is broken)
679 function getInterwikiPrefix(){
685 * Highlight bits of wikitext
689 class SearchHighlighter
{
690 var $mCleanWikitext = true;
692 function SearchHighlighter($cleanupWikitext = true){
693 $this->mCleanWikitext
= $cleanupWikitext;
697 * Default implementation of wikitext highlighting
699 * @param string $text
700 * @param array $terms Terms to highlight (unescaped)
701 * @param int $contextlines
702 * @param int $contextchars
705 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
706 global $wgLang, $wgContLang;
707 global $wgSearchHighlightBoundaries;
713 // spli text into text + templates/links/tables
714 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
715 // first capture group is for detecting nested templates/links/tables/references
716 $endPatterns = array(
717 1 => '/(\{\{)|(\}\})/', // template
718 2 => '/(\[\[)|(\]\])/', // image
719 3 => "/(\n\\{\\|)|(\n\\|\\})/"); // table
721 // FIXME: this should prolly be a hook or something
722 if(function_exists('wfCite')){
723 $spat .= '|(<ref>)'; // references via cite extension
724 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
727 $textExt = array(); // text extracts
728 $otherExt = array(); // other extracts
729 wfProfileIn( "$fname-split" );
731 $textLen = strlen($text);
732 $count = 0; // sequence number to maintain ordering
733 while( $start < $textLen ){
734 // find start of template/image/table
735 if( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ){
737 foreach($matches as $key => $val){
738 if($key > 0 && $val[1] != -1){
740 // see if this is an image link
741 $ns = substr($val[0],2,-1);
742 if( $wgContLang->getNsIndex($ns) != NS_IMAGE
)
746 $epat = $endPatterns[$key];
747 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
753 // find end (and detect any nested elements)
755 $offset = $start +
1;
757 while( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ){
758 if( array_key_exists(2,$endMatches) ){
761 $len = strlen($endMatches[2][0]);
762 $off = $endMatches[2][1];
763 $this->splitAndAdd( $otherExt, $count,
764 substr( $text, $start, $off +
$len - $start ) );
765 $start = $off +
$len;
769 // end of nested element
776 $offset = $endMatches[0][1] +
strlen($endMatches[0][0]);
779 // couldn't find appropriate closing tag, skip
780 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen($matches[0][0]) ) );
781 $start +
= strlen($matches[0][0]);
786 // else: add as text extract
787 $this->splitAndAdd( $textExt, $count, substr($text,$start) );
791 $all = $textExt +
$otherExt; // these have disjunct key sets
793 wfProfileOut( "$fname-split" );
796 foreach( $terms as $index => $term ) {
797 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
798 if(preg_match('/[\x80-\xff]/', $term) ){
799 $terms[$index] = preg_replace_callback('/./us',array($this,'caseCallback'),$terms[$index]);
801 $terms[$index] = $term;
804 $anyterm = implode( '|', $terms );
805 $phrase = implode("$wgSearchHighlightBoundaries+", $terms );
807 // FIXME: a hack to scale contextchars, a correct solution
808 // would be to have contextchars actually be char and not byte
809 // length, and do proper utf-8 substrings and lengths everywhere,
810 // but PHP is making that very hard and unclean to implement :(
811 $scale = strlen($anyterm) / mb_strlen($anyterm);
812 $contextchars = intval( $contextchars * $scale );
814 $patPre = "(^|$wgSearchHighlightBoundaries)";
815 $patPost = "($wgSearchHighlightBoundaries|$)";
817 $pat1 = "/(".$phrase.")/ui";
818 $pat2 = "/$patPre(".$anyterm.")$patPost/ui";
820 wfProfileIn( "$fname-extract" );
822 $left = $contextlines;
827 // show beginning only if it contains all words
830 foreach($textExt as $index => $line){
831 if(strlen($line)>0 && $line[0] != ';' && $line[0] != ':'){
832 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
839 // check if first text contains all terms
840 foreach($terms as $term){
841 if( ! preg_match("/$patPre".$term."$patPost/ui", $firstText) ){
847 $snippets[$first] = $firstText;
848 $offsets[$first] = 0;
852 // match whole query on text
853 $this->process($pat1, $textExt, $left, $contextchars, $snippets, $offsets);
854 // match whole query on templates/tables/images
855 $this->process($pat1, $otherExt, $left, $contextchars, $snippets, $offsets);
856 // match any words on text
857 $this->process($pat2, $textExt, $left, $contextchars, $snippets, $offsets);
858 // match any words on templates/tables/images
859 $this->process($pat2, $otherExt, $left, $contextchars, $snippets, $offsets);
864 // add extra chars to each snippet to make snippets constant size
866 if( count( $snippets ) == 0){
867 // couldn't find the target words, just show beginning of article
868 $targetchars = $contextchars * $contextlines;
869 $snippets[$first] = '';
870 $offsets[$first] = 0;
872 // if begin of the article contains the whole phrase, show only that !!
873 if( array_key_exists($first,$snippets) && preg_match($pat1,$snippets[$first])
874 && $offsets[$first] < $contextchars * 2 ){
875 $snippets = array ($first => $snippets[$first]);
878 // calc by how much to extend existing snippets
879 $targetchars = intval( ($contextchars * $contextlines) / count ( $snippets ) );
882 foreach($snippets as $index => $line){
883 $extended[$index] = $line;
884 $len = strlen($line);
885 if( $len < $targetchars - 20 ){
886 // complete this line
887 if($len < strlen( $all[$index] )){
888 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index]+
$targetchars, $offsets[$index]);
889 $len = strlen( $extended[$index] );
894 while( $len < $targetchars - 20
895 && array_key_exists($add,$all)
896 && !array_key_exists($add,$snippets) ){
898 $tt = "\n".$this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
899 $extended[$add] = $tt;
900 $len +
= strlen( $tt );
906 //$snippets = array_map('htmlspecialchars', $extended);
907 $snippets = $extended;
910 foreach($snippets as $index => $line){
912 $extract .= $line; // first line
913 elseif($last+
1 == $index && $offsets[$last]+
strlen($snippets[$last]) >= strlen($all[$last]))
914 $extract .= " ".$line; // continous lines
916 $extract .= '<b> ... </b>' . $line;
921 $extract .= '<b> ... </b>';
923 $processed = array();
924 foreach($terms as $term){
925 if( ! isset($processed[$term]) ){
926 $pat3 = "/$patPre(".$term.")$patPost/ui"; // highlight word
927 $extract = preg_replace( $pat3,
928 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
929 $processed[$term] = true;
933 wfProfileOut( "$fname-extract" );
939 * Split text into lines and add it to extracts array
941 * @param array $extracts index -> $line
943 * @param string $text
945 function splitAndAdd(&$extracts, &$count, $text){
946 $split = explode( "\n", $this->mCleanWikitext?
$this->removeWiki($text) : $text );
947 foreach($split as $line){
950 $extracts[$count++
] = $tt;
955 * Do manual case conversion for non-ascii chars
957 * @param unknown_type $matches
959 function caseCallback($matches){
961 if( strlen($matches[0]) > 1 ){
962 return '['.$wgContLang->lc($matches[0]).$wgContLang->uc($matches[0]).']';
968 * Extract part of the text from start to end, but by
969 * not chopping up words
970 * @param string $text
973 * @param int $posStart (out) actual start position
974 * @param int $posEnd (out) actual end position
977 function extract($text, $start, $end, &$posStart = null, &$posEnd = null ){
981 $start = $this->position( $text, $start, 1 );
982 if( $end >= strlen($text) )
983 $end = strlen($text);
985 $end = $this->position( $text, $end );
987 if(!is_null($posStart))
989 if(!is_null($posEnd))
993 return substr($text, $start, $end-$start);
999 * Find a nonletter near a point (index) in the text
1001 * @param string $text
1003 * @param int $offset to found index
1004 * @return int nearest nonletter index, or beginning of utf8 char if none
1006 function position($text, $point, $offset=0 ){
1008 $s = max( 0, $point - $tolerance );
1009 $l = min( strlen($text), $point +
$tolerance ) - $s;
1011 if( preg_match('/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr($text,$s,$l), $m, PREG_OFFSET_CAPTURE
) ){
1012 return $m[0][1] +
$s +
$offset;
1014 // check if point is on a valid first UTF8 char
1015 $char = ord( $text[$point] );
1016 while( $char >= 0x80 && $char < 0xc0 ) {
1017 // skip trailing bytes
1019 if($point >= strlen($text))
1020 return strlen($text);
1021 $char = ord( $text[$point] );
1029 * Search extracts for a pattern, and return snippets
1031 * @param string $pattern regexp for matching lines
1032 * @param array $extracts extracts to search
1033 * @param int $linesleft number of extracts to make
1034 * @param int $contextchars length of snippet
1035 * @param array $out map for highlighted snippets
1036 * @param array $offsets map of starting points of snippets
1039 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ){
1041 return; // nothing to do
1042 foreach($extracts as $index => $line){
1043 if( array_key_exists($index,$out) )
1044 continue; // this line already highlighted
1047 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1051 $len = strlen($m[0][0]);
1052 if($offset +
$len < $contextchars)
1054 elseif( $len > $contextchars)
1057 $begin = $offset +
intval( ($len - $contextchars) / 2 );
1059 $end = $begin +
$contextchars;
1062 // basic snippet from this line
1063 $out[$index] = $this->extract($line,$begin,$end,$posBegin);
1064 $offsets[$index] = $posBegin;
1072 * Basic wikitext removal
1075 function removeWiki($text) {
1076 $fname = __METHOD__
;
1077 wfProfileIn( $fname );
1079 //$text = preg_replace("/'{2,5}/", "", $text);
1080 //$text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1081 //$text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1082 //$text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1083 //$text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1084 //$text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1085 $text = preg_replace("/\\{\\{([^|]+?)\\}\\}/", "", $text);
1086 $text = preg_replace("/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text);
1087 $text = preg_replace("/\\[\\[([^|]+?)\\]\\]/", "\\1", $text);
1088 $text = preg_replace_callback("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array($this,'linkReplace'), $text);
1089 //$text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1090 $text = preg_replace("/<\/?[^>]+>/", "", $text);
1091 $text = preg_replace("/'''''/", "", $text);
1092 $text = preg_replace("/('''|<\/?[iIuUbB]>)/", "", $text);
1093 $text = preg_replace("/''/", "", $text);
1095 wfProfileOut( $fname );
1100 * callback to replace [[target|caption]] kind of links, if
1101 * the target is category or image, leave it
1103 * @param array $matches
1105 function linkReplace($matches){
1106 $colon = strpos( $matches[1], ':' );
1107 if( $colon === false )
1108 return $matches[2]; // replace with caption
1110 $ns = substr( $matches[1], 0, $colon );
1111 $index = $wgContLang->getNsIndex($ns);
1112 if( $index !== false && ($index == NS_IMAGE ||
$index == NS_CATEGORY
) )
1113 return $matches[0]; // return the whole thing
1120 * Simple & fast snippet extraction, but gives completely unrelevant
1123 * @param string $text
1124 * @param array $terms
1125 * @param int $contextlines
1126 * @param int $contextchars
1129 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1130 global $wgLang, $wgContLang;
1131 $fname = __METHOD__
;
1133 $lines = explode( "\n", $text );
1135 $terms = implode( '|', $terms );
1136 $max = intval( $contextchars ) +
1;
1137 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1142 wfProfileIn( "$fname-extract" );
1143 foreach ( $lines as $line ) {
1144 if ( 0 == $contextlines ) {
1149 if ( ! preg_match( $pat1, $line, $m ) ) {
1153 $pre = $wgContLang->truncate( $m[1], -$contextchars, ' ... ' );
1155 if ( count( $m ) < 3 ) {
1158 $post = $wgContLang->truncate( $m[3], $contextchars, ' ... ' );
1163 $line = htmlspecialchars( $pre . $found . $post );
1164 $pat2 = '/(' . $terms . ")/i";
1165 $line = preg_replace( $pat2,
1166 "<span class='searchmatch'>\\1</span>", $line );
1168 $extract .= "${line}\n";
1170 wfProfileOut( "$fname-extract" );
1178 * Dummy class to be used when non-supported Database engine is present.
1179 * @fixme Dummy class should probably try something at least mildly useful,
1180 * such as a LIKE search through titles.
1183 class SearchEngineDummy
extends SearchEngine
{