Reverted r42528. Links with href="#" make firefox scroll to the top of the page,...
[mediawiki.git] / includes / SearchEngine.php
blob1856b9e57a314ecce676d23323f3f034e71aea06
1 <?php
2 /**
3 * @defgroup Search Search
5 * @file
6 * @ingroup Search
7 */
9 /**
10 * Contain a class for special pages
11 * @ingroup Search
13 class SearchEngine {
14 var $limit = 10;
15 var $offset = 0;
16 var $searchTerms = array();
17 var $namespaces = array( NS_MAIN );
18 var $showRedirects = false;
20 /**
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
26 * @access public
27 * @abstract
29 function searchText( $term ) {
30 return null;
33 /**
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
39 * @access public
40 * @abstract
42 function searchTitle( $term ) {
43 return null;
46 /**
47 * If an exact title match can be find, or a very slightly close match,
48 * return the title. If no match, returns NULL.
50 * @param string $term
51 * @return Title
53 public static function getNearMatch( $searchterm ) {
54 global $wgContLang;
56 $allSearchTerms = array($searchterm);
58 if($wgContLang->hasVariants()){
59 $allSearchTerms = array_merge($allSearchTerms,$wgContLang->convertLinkToAllVariants($searchterm));
62 foreach($allSearchTerms as $term){
64 # Exact match? No need to look further.
65 $title = Title::newFromText( $term );
66 if (is_null($title))
67 return NULL;
69 if ( $title->getNamespace() == NS_SPECIAL || $title->isExternal()
70 || $title->exists() ) {
71 return $title;
74 # Now try all lower case (i.e. first letter capitalized)
76 $title = Title::newFromText( $wgContLang->lc( $term ) );
77 if ( $title && $title->exists() ) {
78 return $title;
81 # Now try capitalized string
83 $title = Title::newFromText( $wgContLang->ucwords( $term ) );
84 if ( $title && $title->exists() ) {
85 return $title;
88 # Now try all upper case
90 $title = Title::newFromText( $wgContLang->uc( $term ) );
91 if ( $title && $title->exists() ) {
92 return $title;
95 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
96 $title = Title::newFromText( $wgContLang->ucwordbreaks($term) );
97 if ( $title && $title->exists() ) {
98 return $title;
101 // Give hooks a chance at better match variants
102 $title = null;
103 if( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
104 return $title;
108 $title = Title::newFromText( $searchterm );
110 # Entering an IP address goes to the contributions page
111 if ( ( $title->getNamespace() == NS_USER && User::isIP($title->getText() ) )
112 || User::isIP( trim( $searchterm ) ) ) {
113 return SpecialPage::getTitleFor( 'Contributions', $title->getDBkey() );
117 # Entering a user goes to the user page whether it's there or not
118 if ( $title->getNamespace() == NS_USER ) {
119 return $title;
122 # Go to images that exist even if there's no local page.
123 # There may have been a funny upload, or it may be on a shared
124 # file repository such as Wikimedia Commons.
125 if( $title->getNamespace() == NS_IMAGE ) {
126 $image = wfFindFile( $title );
127 if( $image ) {
128 return $title;
132 # MediaWiki namespace? Page may be "implied" if not customized.
133 # Just return it, with caps forced as the message system likes it.
134 if( $title->getNamespace() == NS_MEDIAWIKI ) {
135 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( $title->getText() ) );
138 # Quoted term? Try without the quotes...
139 $matches = array();
140 if( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
141 return SearchEngine::getNearMatch( $matches[1] );
144 return NULL;
147 public static function legalSearchChars() {
148 return "A-Za-z_'0-9\\x80-\\xFF\\-";
152 * Set the maximum number of results to return
153 * and how many to skip before returning the first.
155 * @param int $limit
156 * @param int $offset
157 * @access public
159 function setLimitOffset( $limit, $offset = 0 ) {
160 $this->limit = intval( $limit );
161 $this->offset = intval( $offset );
165 * Set which namespaces the search should include.
166 * Give an array of namespace index numbers.
168 * @param array $namespaces
169 * @access public
171 function setNamespaces( $namespaces ) {
172 $this->namespaces = $namespaces;
176 * Parse some common prefixes: all (search everything)
177 * or namespace names
179 * @param string $query
181 function replacePrefixes( $query ){
182 global $wgContLang;
184 if( strpos($query,':') === false )
185 return $query; // nothing to do
187 $parsed = $query;
188 $allkeyword = wfMsgForContent('searchall').":";
189 if( strncmp($query, $allkeyword, strlen($allkeyword)) == 0 ){
190 $this->namespaces = null;
191 $parsed = substr($query,strlen($allkeyword));
192 } else if( strpos($query,':') !== false ) {
193 $prefix = substr($query,0,strpos($query,':'));
194 $index = $wgContLang->getNsIndex($prefix);
195 if($index !== false){
196 $this->namespaces = array($index);
197 $parsed = substr($query,strlen($prefix)+1);
200 if(trim($parsed) == '')
201 return $query; // prefix was the whole query
203 return $parsed;
207 * Make a list of searchable namespaces and their canonical names.
208 * @return array
210 public static function searchableNamespaces() {
211 global $wgContLang;
212 $arr = array();
213 foreach( $wgContLang->getNamespaces() as $ns => $name ) {
214 if( $ns >= NS_MAIN ) {
215 $arr[$ns] = $name;
218 return $arr;
222 * Extract default namespaces to search from the given user's
223 * settings, returning a list of index numbers.
225 * @param User $user
226 * @return array
227 * @static
229 public static function userNamespaces( &$user ) {
230 $arr = array();
231 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
232 if( $user->getOption( 'searchNs' . $ns ) ) {
233 $arr[] = $ns;
236 return $arr;
240 * Find snippet highlight settings for a given user
242 * @param User $user
243 * @return array contextlines, contextchars
244 * @static
246 public static function userHighlightPrefs( &$user ){
247 //$contextlines = $user->getOption( 'contextlines', 5 );
248 //$contextchars = $user->getOption( 'contextchars', 50 );
249 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
250 $contextchars = 75; // same as above.... :P
251 return array($contextlines, $contextchars);
255 * An array of namespaces indexes to be searched by default
257 * @return array
258 * @static
260 public static function defaultNamespaces(){
261 global $wgNamespacesToBeSearchedDefault;
263 return array_keys($wgNamespacesToBeSearchedDefault, true);
267 * Return a 'cleaned up' search string
269 * @return string
270 * @access public
272 function filter( $text ) {
273 $lc = $this->legalSearchChars();
274 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
277 * Load up the appropriate search engine class for the currently
278 * active database backend, and return a configured instance.
280 * @return SearchEngine
282 public static function create() {
283 global $wgSearchType;
284 $dbr = wfGetDB( DB_SLAVE );
285 if( $wgSearchType ) {
286 $class = $wgSearchType;
287 } else {
288 $class = $dbr->getSearchEngine();
290 $search = new $class( $dbr );
291 $search->setLimitOffset(0,0);
292 return $search;
296 * Create or update the search index record for the given page.
297 * Title and text should be pre-processed.
299 * @param int $id
300 * @param string $title
301 * @param string $text
302 * @abstract
304 function update( $id, $title, $text ) {
305 // no-op
309 * Update a search index record's title only.
310 * Title should be pre-processed.
312 * @param int $id
313 * @param string $title
314 * @abstract
316 function updateTitle( $id, $title ) {
317 // no-op
321 * Get OpenSearch suggestion template
323 * @return string
324 * @static
326 public static function getOpenSearchTemplate() {
327 global $wgOpenSearchTemplate, $wgServer, $wgScriptPath;
328 if($wgOpenSearchTemplate)
329 return $wgOpenSearchTemplate;
330 else{
331 $ns = implode(',',SearchEngine::defaultNamespaces());
332 if(!$ns) $ns = "0";
333 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace='.$ns;
338 * Get internal MediaWiki Suggest template
340 * @return string
341 * @static
343 public static function getMWSuggestTemplate() {
344 global $wgMWSuggestTemplate, $wgServer, $wgScriptPath;
345 if($wgMWSuggestTemplate)
346 return $wgMWSuggestTemplate;
347 else
348 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace={namespaces}';
353 * @ingroup Search
355 class SearchResultSet {
357 * Fetch an array of regular expression fragments for matching
358 * the search terms as parsed by this engine in a text extract.
360 * @return array
361 * @access public
362 * @abstract
364 function termMatches() {
365 return array();
368 function numRows() {
369 return 0;
373 * Return true if results are included in this result set.
374 * @return bool
375 * @abstract
377 function hasResults() {
378 return false;
382 * Some search modes return a total hit count for the query
383 * in the entire article database. This may include pages
384 * in namespaces that would not be matched on the given
385 * settings.
387 * Return null if no total hits number is supported.
389 * @return int
390 * @access public
392 function getTotalHits() {
393 return null;
397 * Some search modes return a suggested alternate term if there are
398 * no exact hits. Returns true if there is one on this set.
400 * @return bool
401 * @access public
403 function hasSuggestion() {
404 return false;
408 * @return string suggested query, null if none
410 function getSuggestionQuery(){
411 return null;
415 * @return string highlighted suggested query, '' if none
417 function getSuggestionSnippet(){
418 return '';
422 * Return information about how and from where the results were fetched,
423 * should be useful for diagnostics and debugging
425 * @return string
427 function getInfo() {
428 return null;
432 * Return a result set of hits on other (multiple) wikis associated with this one
434 * @return SearchResultSet
436 function getInterwikiResults() {
437 return null;
441 * Check if there are results on other wikis
443 * @return boolean
445 function hasInterwikiResults() {
446 return $this->getInterwikiResults() != null;
451 * Fetches next search result, or false.
452 * @return SearchResult
453 * @access public
454 * @abstract
456 function next() {
457 return false;
461 * Frees the result set, if applicable.
462 * @ access public
464 function free() {
465 // ...
471 * @ingroup Search
473 class SearchResultTooMany {
474 ## Some search engines may bail out if too many matches are found
479 * @fixme This class is horribly factored. It would probably be better to have
480 * a useful base class to which you pass some standard information, then let
481 * the fancy self-highlighters extend that.
482 * @ingroup Search
484 class SearchResult {
485 var $mRevision = null;
487 function SearchResult( $row ) {
488 $this->mTitle = Title::makeTitle( $row->page_namespace, $row->page_title );
489 if( !is_null($this->mTitle) )
490 $this->mRevision = Revision::newFromTitle( $this->mTitle );
494 * Check if this is result points to an invalid title
496 * @return boolean
497 * @access public
499 function isBrokenTitle(){
500 if( is_null($this->mTitle) )
501 return true;
502 return false;
506 * Check if target page is missing, happens when index is out of date
508 * @return boolean
509 * @access public
511 function isMissingRevision(){
512 if( !$this->mRevision )
513 return true;
514 return false;
518 * @return Title
519 * @access public
521 function getTitle() {
522 return $this->mTitle;
526 * @return double or null if not supported
528 function getScore() {
529 return null;
533 * Lazy initialization of article text from DB
535 protected function initText(){
536 if( !isset($this->mText) ){
537 $this->mText = $this->mRevision->getText();
542 * @param array $terms terms to highlight
543 * @return string highlighted text snippet, null (and not '') if not supported
545 function getTextSnippet($terms){
546 global $wgUser, $wgAdvancedSearchHighlighting;
547 $this->initText();
548 list($contextlines,$contextchars) = SearchEngine::userHighlightPrefs($wgUser);
549 $h = new SearchHighlighter();
550 if( $wgAdvancedSearchHighlighting )
551 return $h->highlightText( $this->mText, $terms, $contextlines, $contextchars );
552 else
553 return $h->highlightSimple( $this->mText, $terms, $contextlines, $contextchars );
557 * @param array $terms terms to highlight
558 * @return string highlighted title, '' if not supported
560 function getTitleSnippet($terms){
561 return '';
565 * @param array $terms terms to highlight
566 * @return string highlighted redirect name (redirect to this page), '' if none or not supported
568 function getRedirectSnippet($terms){
569 return '';
573 * @return Title object for the redirect to this page, null if none or not supported
575 function getRedirectTitle(){
576 return null;
580 * @return string highlighted relevant section name, null if none or not supported
582 function getSectionSnippet(){
583 return '';
587 * @return Title object (pagename+fragment) for the section, null if none or not supported
589 function getSectionTitle(){
590 return null;
594 * @return string timestamp
596 function getTimestamp(){
597 return $this->mRevision->getTimestamp();
601 * @return int number of words
603 function getWordCount(){
604 $this->initText();
605 return str_word_count( $this->mText );
609 * @return int size in bytes
611 function getByteSize(){
612 $this->initText();
613 return strlen( $this->mText );
617 * @return boolean if hit has related articles
619 function hasRelated(){
620 return false;
624 * @return interwiki prefix of the title (return iw even if title is broken)
626 function getInterwikiPrefix(){
627 return '';
632 * Highlight bits of wikitext
634 * @ingroup Search
636 class SearchHighlighter {
637 var $mCleanWikitext = true;
639 function SearchHighlighter($cleanupWikitext = true){
640 $this->mCleanWikitext = $cleanupWikitext;
644 * Default implementation of wikitext highlighting
646 * @param string $text
647 * @param array $terms Terms to highlight (unescaped)
648 * @param int $contextlines
649 * @param int $contextchars
650 * @return string
652 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
653 global $wgLang, $wgContLang;
654 global $wgSearchHighlightBoundaries;
655 $fname = __METHOD__;
657 if($text == '')
658 return '';
660 // spli text into text + templates/links/tables
661 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
662 // first capture group is for detecting nested templates/links/tables/references
663 $endPatterns = array(
664 1 => '/(\{\{)|(\}\})/', // template
665 2 => '/(\[\[)|(\]\])/', // image
666 3 => "/(\n\\{\\|)|(\n\\|\\})/"); // table
668 // FIXME: this should prolly be a hook or something
669 if(function_exists('wfCite')){
670 $spat .= '|(<ref>)'; // references via cite extension
671 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
673 $spat .= '/';
674 $textExt = array(); // text extracts
675 $otherExt = array(); // other extracts
676 wfProfileIn( "$fname-split" );
677 $start = 0;
678 $textLen = strlen($text);
679 $count = 0; // sequence number to maintain ordering
680 while( $start < $textLen ){
681 // find start of template/image/table
682 if( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE, $start ) ){
683 $epat = '';
684 foreach($matches as $key => $val){
685 if($key > 0 && $val[1] != -1){
686 if($key == 2){
687 // see if this is an image link
688 $ns = substr($val[0],2,-1);
689 if( $wgContLang->getNsIndex($ns) != NS_IMAGE )
690 break;
693 $epat = $endPatterns[$key];
694 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
695 $start = $val[1];
696 break;
699 if( $epat ){
700 // find end (and detect any nested elements)
701 $level = 0;
702 $offset = $start + 1;
703 $found = false;
704 while( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE, $offset ) ){
705 if( array_key_exists(2,$endMatches) ){
706 // found end
707 if($level == 0){
708 $len = strlen($endMatches[2][0]);
709 $off = $endMatches[2][1];
710 $this->splitAndAdd( $otherExt, $count,
711 substr( $text, $start, $off + $len - $start ) );
712 $start = $off + $len;
713 $found = true;
714 break;
715 } else{
716 // end of nested element
717 $level -= 1;
719 } else{
720 // nested
721 $level += 1;
723 $offset = $endMatches[0][1] + strlen($endMatches[0][0]);
725 if( ! $found ){
726 // couldn't find appropriate closing tag, skip
727 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen($matches[0][0]) ) );
728 $start += strlen($matches[0][0]);
730 continue;
733 // else: add as text extract
734 $this->splitAndAdd( $textExt, $count, substr($text,$start) );
735 break;
738 $all = $textExt + $otherExt; // these have disjunct key sets
740 wfProfileOut( "$fname-split" );
742 // prepare regexps
743 foreach( $terms as $index => $term ) {
744 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
745 if(preg_match('/[\x80-\xff]/', $term) ){
746 $terms[$index] = preg_replace_callback('/./us',array($this,'caseCallback'),$terms[$index]);
747 } else {
748 $terms[$index] = $term;
751 $anyterm = implode( '|', $terms );
752 $phrase = implode("$wgSearchHighlightBoundaries+", $terms );
754 // FIXME: a hack to scale contextchars, a correct solution
755 // would be to have contextchars actually be char and not byte
756 // length, and do proper utf-8 substrings and lengths everywhere,
757 // but PHP is making that very hard and unclean to implement :(
758 $scale = strlen($anyterm) / mb_strlen($anyterm);
759 $contextchars = intval( $contextchars * $scale );
761 $patPre = "(^|$wgSearchHighlightBoundaries)";
762 $patPost = "($wgSearchHighlightBoundaries|$)";
764 $pat1 = "/(".$phrase.")/ui";
765 $pat2 = "/$patPre(".$anyterm.")$patPost/ui";
767 wfProfileIn( "$fname-extract" );
769 $left = $contextlines;
771 $snippets = array();
772 $offsets = array();
774 // show beginning only if it contains all words
775 $first = 0;
776 $firstText = '';
777 foreach($textExt as $index => $line){
778 if(strlen($line)>0 && $line[0] != ';' && $line[0] != ':'){
779 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
780 $first = $index;
781 break;
784 if( $firstText ){
785 $succ = true;
786 // check if first text contains all terms
787 foreach($terms as $term){
788 if( ! preg_match("/$patPre".$term."$patPost/ui", $firstText) ){
789 $succ = false;
790 break;
793 if( $succ ){
794 $snippets[$first] = $firstText;
795 $offsets[$first] = 0;
798 if( ! $snippets ) {
799 // match whole query on text
800 $this->process($pat1, $textExt, $left, $contextchars, $snippets, $offsets);
801 // match whole query on templates/tables/images
802 $this->process($pat1, $otherExt, $left, $contextchars, $snippets, $offsets);
803 // match any words on text
804 $this->process($pat2, $textExt, $left, $contextchars, $snippets, $offsets);
805 // match any words on templates/tables/images
806 $this->process($pat2, $otherExt, $left, $contextchars, $snippets, $offsets);
808 ksort($snippets);
811 // add extra chars to each snippet to make snippets constant size
812 $extended = array();
813 if( count( $snippets ) == 0){
814 // couldn't find the target words, just show beginning of article
815 $targetchars = $contextchars * $contextlines;
816 $snippets[$first] = '';
817 $offsets[$first] = 0;
818 } else{
819 // if begin of the article contains the whole phrase, show only that !!
820 if( array_key_exists($first,$snippets) && preg_match($pat1,$snippets[$first])
821 && $offsets[$first] < $contextchars * 2 ){
822 $snippets = array ($first => $snippets[$first]);
825 // calc by how much to extend existing snippets
826 $targetchars = intval( ($contextchars * $contextlines) / count ( $snippets ) );
829 foreach($snippets as $index => $line){
830 $extended[$index] = $line;
831 $len = strlen($line);
832 if( $len < $targetchars - 20 ){
833 // complete this line
834 if($len < strlen( $all[$index] )){
835 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index]+$targetchars, $offsets[$index]);
836 $len = strlen( $extended[$index] );
839 // add more lines
840 $add = $index + 1;
841 while( $len < $targetchars - 20
842 && array_key_exists($add,$all)
843 && !array_key_exists($add,$snippets) ){
844 $offsets[$add] = 0;
845 $tt = "\n".$this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
846 $extended[$add] = $tt;
847 $len += strlen( $tt );
848 $add++;
853 //$snippets = array_map('htmlspecialchars', $extended);
854 $snippets = $extended;
855 $last = -1;
856 $extract = '';
857 foreach($snippets as $index => $line){
858 if($last == -1)
859 $extract .= $line; // first line
860 elseif($last+1 == $index && $offsets[$last]+strlen($snippets[$last]) >= strlen($all[$last]))
861 $extract .= " ".$line; // continous lines
862 else
863 $extract .= '<b> ... </b>' . $line;
865 $last = $index;
867 if( $extract )
868 $extract .= '<b> ... </b>';
870 $processed = array();
871 foreach($terms as $term){
872 if( ! isset($processed[$term]) ){
873 $pat3 = "/$patPre(".$term.")$patPost/ui"; // highlight word
874 $extract = preg_replace( $pat3,
875 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
876 $processed[$term] = true;
880 wfProfileOut( "$fname-extract" );
882 return $extract;
886 * Split text into lines and add it to extracts array
888 * @param array $extracts index -> $line
889 * @param int $count
890 * @param string $text
892 function splitAndAdd(&$extracts, &$count, $text){
893 $split = explode( "\n", $this->mCleanWikitext? $this->removeWiki($text) : $text );
894 foreach($split as $line){
895 $tt = trim($line);
896 if( $tt )
897 $extracts[$count++] = $tt;
902 * Do manual case conversion for non-ascii chars
904 * @param unknown_type $matches
906 function caseCallback($matches){
907 global $wgContLang;
908 if( strlen($matches[0]) > 1 ){
909 return '['.$wgContLang->lc($matches[0]).$wgContLang->uc($matches[0]).']';
910 } else
911 return $matches[0];
915 * Extract part of the text from start to end, but by
916 * not chopping up words
917 * @param string $text
918 * @param int $start
919 * @param int $end
920 * @param int $posStart (out) actual start position
921 * @param int $posEnd (out) actual end position
922 * @return string
924 function extract($text, $start, $end, &$posStart = null, &$posEnd = null ){
925 global $wgContLang;
927 if( $start != 0)
928 $start = $this->position( $text, $start, 1 );
929 if( $end >= strlen($text) )
930 $end = strlen($text);
931 else
932 $end = $this->position( $text, $end );
934 if(!is_null($posStart))
935 $posStart = $start;
936 if(!is_null($posEnd))
937 $posEnd = $end;
939 if($end > $start)
940 return substr($text, $start, $end-$start);
941 else
942 return '';
946 * Find a nonletter near a point (index) in the text
948 * @param string $text
949 * @param int $point
950 * @param int $offset to found index
951 * @return int nearest nonletter index, or beginning of utf8 char if none
953 function position($text, $point, $offset=0 ){
954 $tolerance = 10;
955 $s = max( 0, $point - $tolerance );
956 $l = min( strlen($text), $point + $tolerance ) - $s;
957 $m = array();
958 if( preg_match('/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr($text,$s,$l), $m, PREG_OFFSET_CAPTURE ) ){
959 return $m[0][1] + $s + $offset;
960 } else{
961 // check if point is on a valid first UTF8 char
962 $char = ord( $text[$point] );
963 while( $char >= 0x80 && $char < 0xc0 ) {
964 // skip trailing bytes
965 $point++;
966 if($point >= strlen($text))
967 return strlen($text);
968 $char = ord( $text[$point] );
970 return $point;
976 * Search extracts for a pattern, and return snippets
978 * @param string $pattern regexp for matching lines
979 * @param array $extracts extracts to search
980 * @param int $linesleft number of extracts to make
981 * @param int $contextchars length of snippet
982 * @param array $out map for highlighted snippets
983 * @param array $offsets map of starting points of snippets
984 * @protected
986 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ){
987 if($linesleft == 0)
988 return; // nothing to do
989 foreach($extracts as $index => $line){
990 if( array_key_exists($index,$out) )
991 continue; // this line already highlighted
993 $m = array();
994 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) )
995 continue;
997 $offset = $m[0][1];
998 $len = strlen($m[0][0]);
999 if($offset + $len < $contextchars)
1000 $begin = 0;
1001 elseif( $len > $contextchars)
1002 $begin = $offset;
1003 else
1004 $begin = $offset + intval( ($len - $contextchars) / 2 );
1006 $end = $begin + $contextchars;
1008 $posBegin = $begin;
1009 // basic snippet from this line
1010 $out[$index] = $this->extract($line,$begin,$end,$posBegin);
1011 $offsets[$index] = $posBegin;
1012 $linesleft--;
1013 if($linesleft == 0)
1014 return;
1018 /**
1019 * Basic wikitext removal
1020 * @protected
1022 function removeWiki($text) {
1023 $fname = __METHOD__;
1024 wfProfileIn( $fname );
1026 //$text = preg_replace("/'{2,5}/", "", $text);
1027 //$text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1028 //$text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1029 //$text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1030 //$text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1031 //$text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1032 $text = preg_replace("/\\{\\{([^|]+?)\\}\\}/", "", $text);
1033 $text = preg_replace("/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text);
1034 $text = preg_replace("/\\[\\[([^|]+?)\\]\\]/", "\\1", $text);
1035 $text = preg_replace_callback("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array($this,'linkReplace'), $text);
1036 //$text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1037 $text = preg_replace("/<\/?[^>]+>/", "", $text);
1038 $text = preg_replace("/'''''/", "", $text);
1039 $text = preg_replace("/('''|<\/?[iIuUbB]>)/", "", $text);
1040 $text = preg_replace("/''/", "", $text);
1042 wfProfileOut( $fname );
1043 return $text;
1047 * callback to replace [[target|caption]] kind of links, if
1048 * the target is category or image, leave it
1050 * @param array $matches
1052 function linkReplace($matches){
1053 $colon = strpos( $matches[1], ':' );
1054 if( $colon === false )
1055 return $matches[2]; // replace with caption
1056 global $wgContLang;
1057 $ns = substr( $matches[1], 0, $colon );
1058 $index = $wgContLang->getNsIndex($ns);
1059 if( $index !== false && ($index == NS_IMAGE || $index == NS_CATEGORY) )
1060 return $matches[0]; // return the whole thing
1061 else
1062 return $matches[2];
1067 * Simple & fast snippet extraction, but gives completely unrelevant
1068 * snippets
1070 * @param string $text
1071 * @param array $terms
1072 * @param int $contextlines
1073 * @param int $contextchars
1074 * @return string
1076 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1077 global $wgLang, $wgContLang;
1078 $fname = __METHOD__;
1080 $lines = explode( "\n", $text );
1082 $terms = implode( '|', $terms );
1083 $max = intval( $contextchars ) + 1;
1084 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1086 $lineno = 0;
1088 $extract = "";
1089 wfProfileIn( "$fname-extract" );
1090 foreach ( $lines as $line ) {
1091 if ( 0 == $contextlines ) {
1092 break;
1094 ++$lineno;
1095 $m = array();
1096 if ( ! preg_match( $pat1, $line, $m ) ) {
1097 continue;
1099 --$contextlines;
1100 $pre = $wgContLang->truncate( $m[1], -$contextchars, ' ... ' );
1102 if ( count( $m ) < 3 ) {
1103 $post = '';
1104 } else {
1105 $post = $wgContLang->truncate( $m[3], $contextchars, ' ... ' );
1108 $found = $m[2];
1110 $line = htmlspecialchars( $pre . $found . $post );
1111 $pat2 = '/(' . $terms . ")/i";
1112 $line = preg_replace( $pat2,
1113 "<span class='searchmatch'>\\1</span>", $line );
1115 $extract .= "${line}\n";
1117 wfProfileOut( "$fname-extract" );
1119 return $extract;
1125 * Dummy class to be used when non-supported Database engine is present.
1126 * @fixme Dummy class should probably try something at least mildly useful,
1127 * such as a LIKE search through titles.
1128 * @ingroup Search
1130 class SearchEngineDummy extends SearchEngine {
1131 // no-op