(bug 15543) fix for r38139: don't include $wgUser->mTouched and smaxage=0 in query...
[lhc/web/wiklou.git] / includes / SearchEngine.php
1 <?php
2 /**
3 * @defgroup Search Search
4 *
5 * @file
6 * @ingroup Search
7 */
8
9 /**
10 * Contain a class for special pages
11 * @ingroup Search
12 */
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;
19
20 /**
21 * Perform a full text search query and return a result set.
22 * If title searches are not supported or disabled, return null.
23 *
24 * @param string $term - Raw search term
25 * @return SearchResultSet
26 * @access public
27 * @abstract
28 */
29 function searchText( $term ) {
30 return null;
31 }
32
33 /**
34 * Perform a title-only search query and return a result set.
35 * If title searches are not supported or disabled, return null.
36 *
37 * @param string $term - Raw search term
38 * @return SearchResultSet
39 * @access public
40 * @abstract
41 */
42 function searchTitle( $term ) {
43 return null;
44 }
45
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.
49 *
50 * @param string $term
51 * @return Title
52 */
53 public static function getNearMatch( $searchterm ) {
54 global $wgContLang;
55
56 $allSearchTerms = array($searchterm);
57
58 if($wgContLang->hasVariants()){
59 $allSearchTerms = array_merge($allSearchTerms,$wgContLang->convertLinkToAllVariants($searchterm));
60 }
61
62 foreach($allSearchTerms as $term){
63
64 # Exact match? No need to look further.
65 $title = Title::newFromText( $term );
66 if (is_null($title))
67 return NULL;
68
69 if ( $title->getNamespace() == NS_SPECIAL || $title->isExternal()
70 || $title->exists() ) {
71 return $title;
72 }
73
74 # Now try all lower case (i.e. first letter capitalized)
75 #
76 $title = Title::newFromText( $wgContLang->lc( $term ) );
77 if ( $title && $title->exists() ) {
78 return $title;
79 }
80
81 # Now try capitalized string
82 #
83 $title = Title::newFromText( $wgContLang->ucwords( $term ) );
84 if ( $title && $title->exists() ) {
85 return $title;
86 }
87
88 # Now try all upper case
89 #
90 $title = Title::newFromText( $wgContLang->uc( $term ) );
91 if ( $title && $title->exists() ) {
92 return $title;
93 }
94
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;
99 }
100
101 // Give hooks a chance at better match variants
102 $title = null;
103 if( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
104 return $title;
105 }
106 }
107
108 $title = Title::newFromText( $searchterm );
109
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() );
114 }
115
116
117 # Entering a user goes to the user page whether it's there or not
118 if ( $title->getNamespace() == NS_USER ) {
119 return $title;
120 }
121
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;
129 }
130 }
131
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() ) );
136 }
137
138 # Quoted term? Try without the quotes...
139 $matches = array();
140 if( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
141 return SearchEngine::getNearMatch( $matches[1] );
142 }
143
144 return NULL;
145 }
146
147 public static function legalSearchChars() {
148 return "A-Za-z_'0-9\\x80-\\xFF\\-";
149 }
150
151 /**
152 * Set the maximum number of results to return
153 * and how many to skip before returning the first.
154 *
155 * @param int $limit
156 * @param int $offset
157 * @access public
158 */
159 function setLimitOffset( $limit, $offset = 0 ) {
160 $this->limit = intval( $limit );
161 $this->offset = intval( $offset );
162 }
163
164 /**
165 * Set which namespaces the search should include.
166 * Give an array of namespace index numbers.
167 *
168 * @param array $namespaces
169 * @access public
170 */
171 function setNamespaces( $namespaces ) {
172 $this->namespaces = $namespaces;
173 }
174
175 /**
176 * Parse some common prefixes: all (search everything)
177 * or namespace names
178 *
179 * @param string $query
180 */
181 function replacePrefixes( $query ){
182 global $wgContLang;
183
184 if( strpos($query,':') === false )
185 return $query; // nothing to do
186
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);
198 }
199 }
200 if(trim($parsed) == '')
201 return $query; // prefix was the whole query
202
203 return $parsed;
204 }
205
206 /**
207 * Make a list of searchable namespaces and their canonical names.
208 * @return array
209 */
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;
216 }
217 }
218 return $arr;
219 }
220
221 /**
222 * Extract default namespaces to search from the given user's
223 * settings, returning a list of index numbers.
224 *
225 * @param User $user
226 * @return array
227 * @static
228 */
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;
234 }
235 }
236 return $arr;
237 }
238
239 /**
240 * Find snippet highlight settings for a given user
241 *
242 * @param User $user
243 * @return array contextlines, contextchars
244 * @static
245 */
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);
252 }
253
254 /**
255 * An array of namespaces indexes to be searched by default
256 *
257 * @return array
258 * @static
259 */
260 public static function defaultNamespaces(){
261 global $wgNamespacesToBeSearchedDefault;
262
263 return array_keys($wgNamespacesToBeSearchedDefault, true);
264 }
265
266 /**
267 * Return a 'cleaned up' search string
268 *
269 * @return string
270 * @access public
271 */
272 function filter( $text ) {
273 $lc = $this->legalSearchChars();
274 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
275 }
276 /**
277 * Load up the appropriate search engine class for the currently
278 * active database backend, and return a configured instance.
279 *
280 * @return SearchEngine
281 */
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();
289 }
290 $search = new $class( $dbr );
291 $search->setLimitOffset(0,0);
292 return $search;
293 }
294
295 /**
296 * Create or update the search index record for the given page.
297 * Title and text should be pre-processed.
298 *
299 * @param int $id
300 * @param string $title
301 * @param string $text
302 * @abstract
303 */
304 function update( $id, $title, $text ) {
305 // no-op
306 }
307
308 /**
309 * Update a search index record's title only.
310 * Title should be pre-processed.
311 *
312 * @param int $id
313 * @param string $title
314 * @abstract
315 */
316 function updateTitle( $id, $title ) {
317 // no-op
318 }
319
320 /**
321 * Get OpenSearch suggestion template
322 *
323 * @return string
324 * @static
325 */
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;
334 }
335 }
336
337 /**
338 * Get internal MediaWiki Suggest template
339 *
340 * @return string
341 * @static
342 */
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}';
349 }
350 }
351
352 /**
353 * @ingroup Search
354 */
355 class SearchResultSet {
356 /**
357 * Fetch an array of regular expression fragments for matching
358 * the search terms as parsed by this engine in a text extract.
359 *
360 * @return array
361 * @access public
362 * @abstract
363 */
364 function termMatches() {
365 return array();
366 }
367
368 function numRows() {
369 return 0;
370 }
371
372 /**
373 * Return true if results are included in this result set.
374 * @return bool
375 * @abstract
376 */
377 function hasResults() {
378 return false;
379 }
380
381 /**
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.
386 *
387 * Return null if no total hits number is supported.
388 *
389 * @return int
390 * @access public
391 */
392 function getTotalHits() {
393 return null;
394 }
395
396 /**
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.
399 *
400 * @return bool
401 * @access public
402 */
403 function hasSuggestion() {
404 return false;
405 }
406
407 /**
408 * @return string suggested query, null if none
409 */
410 function getSuggestionQuery(){
411 return null;
412 }
413
414 /**
415 * @return string highlighted suggested query, '' if none
416 */
417 function getSuggestionSnippet(){
418 return '';
419 }
420
421 /**
422 * Return information about how and from where the results were fetched,
423 * should be useful for diagnostics and debugging
424 *
425 * @return string
426 */
427 function getInfo() {
428 return null;
429 }
430
431 /**
432 * Return a result set of hits on other (multiple) wikis associated with this one
433 *
434 * @return SearchResultSet
435 */
436 function getInterwikiResults() {
437 return null;
438 }
439
440 /**
441 * Check if there are results on other wikis
442 *
443 * @return boolean
444 */
445 function hasInterwikiResults() {
446 return $this->getInterwikiResults() != null;
447 }
448
449
450 /**
451 * Fetches next search result, or false.
452 * @return SearchResult
453 * @access public
454 * @abstract
455 */
456 function next() {
457 return false;
458 }
459
460 /**
461 * Frees the result set, if applicable.
462 * @ access public
463 */
464 function free() {
465 // ...
466 }
467 }
468
469
470 /**
471 * @ingroup Search
472 */
473 class SearchResultTooMany {
474 ## Some search engines may bail out if too many matches are found
475 }
476
477
478 /**
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
483 */
484 class SearchResult {
485 var $mRevision = null;
486
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 );
491 }
492
493 /**
494 * Check if this is result points to an invalid title
495 *
496 * @return boolean
497 * @access public
498 */
499 function isBrokenTitle(){
500 if( is_null($this->mTitle) )
501 return true;
502 return false;
503 }
504
505 /**
506 * Check if target page is missing, happens when index is out of date
507 *
508 * @return boolean
509 * @access public
510 */
511 function isMissingRevision(){
512 if( !$this->mRevision )
513 return true;
514 return false;
515 }
516
517 /**
518 * @return Title
519 * @access public
520 */
521 function getTitle() {
522 return $this->mTitle;
523 }
524
525 /**
526 * @return double or null if not supported
527 */
528 function getScore() {
529 return null;
530 }
531
532 /**
533 * Lazy initialization of article text from DB
534 */
535 protected function initText(){
536 if( !isset($this->mText) ){
537 $this->mText = $this->mRevision->getText();
538 }
539 }
540
541 /**
542 * @param array $terms terms to highlight
543 * @return string highlighted text snippet, null (and not '') if not supported
544 */
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 );
554 }
555
556 /**
557 * @param array $terms terms to highlight
558 * @return string highlighted title, '' if not supported
559 */
560 function getTitleSnippet($terms){
561 return '';
562 }
563
564 /**
565 * @param array $terms terms to highlight
566 * @return string highlighted redirect name (redirect to this page), '' if none or not supported
567 */
568 function getRedirectSnippet($terms){
569 return '';
570 }
571
572 /**
573 * @return Title object for the redirect to this page, null if none or not supported
574 */
575 function getRedirectTitle(){
576 return null;
577 }
578
579 /**
580 * @return string highlighted relevant section name, null if none or not supported
581 */
582 function getSectionSnippet(){
583 return '';
584 }
585
586 /**
587 * @return Title object (pagename+fragment) for the section, null if none or not supported
588 */
589 function getSectionTitle(){
590 return null;
591 }
592
593 /**
594 * @return string timestamp
595 */
596 function getTimestamp(){
597 return $this->mRevision->getTimestamp();
598 }
599
600 /**
601 * @return int number of words
602 */
603 function getWordCount(){
604 $this->initText();
605 return str_word_count( $this->mText );
606 }
607
608 /**
609 * @return int size in bytes
610 */
611 function getByteSize(){
612 $this->initText();
613 return strlen( $this->mText );
614 }
615
616 /**
617 * @return boolean if hit has related articles
618 */
619 function hasRelated(){
620 return false;
621 }
622
623 /**
624 * @return interwiki prefix of the title (return iw even if title is broken)
625 */
626 function getInterwikiPrefix(){
627 return '';
628 }
629 }
630
631 /**
632 * Highlight bits of wikitext
633 *
634 * @ingroup Search
635 */
636 class SearchHighlighter {
637 var $mCleanWikitext = true;
638
639 function SearchHighlighter($cleanupWikitext = true){
640 $this->mCleanWikitext = $cleanupWikitext;
641 }
642
643 /**
644 * Default implementation of wikitext highlighting
645 *
646 * @param string $text
647 * @param array $terms Terms to highlight (unescaped)
648 * @param int $contextlines
649 * @param int $contextchars
650 * @return string
651 */
652 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
653 global $wgLang, $wgContLang;
654 global $wgSearchHighlightBoundaries;
655 $fname = __METHOD__;
656
657 if($text == '')
658 return '';
659
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
667
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>)/';
672 }
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;
691
692 }
693 $epat = $endPatterns[$key];
694 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
695 $start = $val[1];
696 break;
697 }
698 }
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;
718 }
719 } else{
720 // nested
721 $level += 1;
722 }
723 $offset = $endMatches[0][1] + strlen($endMatches[0][0]);
724 }
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]);
729 }
730 continue;
731 }
732 }
733 // else: add as text extract
734 $this->splitAndAdd( $textExt, $count, substr($text,$start) );
735 break;
736 }
737
738 $all = $textExt + $otherExt; // these have disjunct key sets
739
740 wfProfileOut( "$fname-split" );
741
742 // prepare regexps
743 foreach( $terms as $index => $term ) {
744 $terms[$index] = preg_quote( $term, '/' );
745 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
746 if(preg_match('/[\x80-\xff]/', $term) ){
747 $terms[$index] = preg_replace_callback('/./us',array($this,'caseCallback'),$terms[$index]);
748 }
749
750
751 }
752 $anyterm = implode( '|', $terms );
753 $phrase = implode("$wgSearchHighlightBoundaries+", $terms );
754
755 // FIXME: a hack to scale contextchars, a correct solution
756 // would be to have contextchars actually be char and not byte
757 // length, and do proper utf-8 substrings and lengths everywhere,
758 // but PHP is making that very hard and unclean to implement :(
759 $scale = strlen($anyterm) / mb_strlen($anyterm);
760 $contextchars = intval( $contextchars * $scale );
761
762 $patPre = "(^|$wgSearchHighlightBoundaries)";
763 $patPost = "($wgSearchHighlightBoundaries|$)";
764
765 $pat1 = "/(".$phrase.")/ui";
766 $pat2 = "/$patPre(".$anyterm.")$patPost/ui";
767
768 wfProfileIn( "$fname-extract" );
769
770 $left = $contextlines;
771
772 $snippets = array();
773 $offsets = array();
774
775 // show beginning only if it contains all words
776 $first = 0;
777 $firstText = '';
778 foreach($textExt as $index => $line){
779 if(strlen($line)>0 && $line[0] != ';' && $line[0] != ':'){
780 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
781 $first = $index;
782 break;
783 }
784 }
785 if( $firstText ){
786 $succ = true;
787 // check if first text contains all terms
788 foreach($terms as $term){
789 if( ! preg_match("/$patPre".$term."$patPost/ui", $firstText) ){
790 $succ = false;
791 break;
792 }
793 }
794 if( $succ ){
795 $snippets[$first] = $firstText;
796 $offsets[$first] = 0;
797 }
798 }
799 if( ! $snippets ) {
800 // match whole query on text
801 $this->process($pat1, $textExt, $left, $contextchars, $snippets, $offsets);
802 // match whole query on templates/tables/images
803 $this->process($pat1, $otherExt, $left, $contextchars, $snippets, $offsets);
804 // match any words on text
805 $this->process($pat2, $textExt, $left, $contextchars, $snippets, $offsets);
806 // match any words on templates/tables/images
807 $this->process($pat2, $otherExt, $left, $contextchars, $snippets, $offsets);
808
809 ksort($snippets);
810 }
811
812 // add extra chars to each snippet to make snippets constant size
813 $extended = array();
814 if( count( $snippets ) == 0){
815 // couldn't find the target words, just show beginning of article
816 $targetchars = $contextchars * $contextlines;
817 $snippets[$first] = '';
818 $offsets[$first] = 0;
819 } else{
820 // if begin of the article contains the whole phrase, show only that !!
821 if( array_key_exists($first,$snippets) && preg_match($pat1,$snippets[$first])
822 && $offsets[$first] < $contextchars * 2 ){
823 $snippets = array ($first => $snippets[$first]);
824 }
825
826 // calc by how much to extend existing snippets
827 $targetchars = intval( ($contextchars * $contextlines) / count ( $snippets ) );
828 }
829
830 foreach($snippets as $index => $line){
831 $extended[$index] = $line;
832 $len = strlen($line);
833 if( $len < $targetchars - 20 ){
834 // complete this line
835 if($len < strlen( $all[$index] )){
836 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index]+$targetchars, $offsets[$index]);
837 $len = strlen( $extended[$index] );
838 }
839
840 // add more lines
841 $add = $index + 1;
842 while( $len < $targetchars - 20
843 && array_key_exists($add,$all)
844 && !array_key_exists($add,$snippets) ){
845 $offsets[$add] = 0;
846 $tt = "\n".$this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
847 $extended[$add] = $tt;
848 $len += strlen( $tt );
849 $add++;
850 }
851 }
852 }
853
854 //$snippets = array_map('htmlspecialchars', $extended);
855 $snippets = $extended;
856 $last = -1;
857 $extract = '';
858 foreach($snippets as $index => $line){
859 if($last == -1)
860 $extract .= $line; // first line
861 elseif($last+1 == $index && $offsets[$last]+strlen($snippets[$last]) >= strlen($all[$last]))
862 $extract .= " ".$line; // continous lines
863 else
864 $extract .= '<b> ... </b>' . $line;
865
866 $last = $index;
867 }
868 if( $extract )
869 $extract .= '<b> ... </b>';
870
871 $processed = array();
872 foreach($terms as $term){
873 if( ! isset($processed[$term]) ){
874 $pat3 = "/$patPre(".$term.")$patPost/ui"; // highlight word
875 $extract = preg_replace( $pat3,
876 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
877 $processed[$term] = true;
878 }
879 }
880
881 wfProfileOut( "$fname-extract" );
882
883 return $extract;
884 }
885
886 /**
887 * Split text into lines and add it to extracts array
888 *
889 * @param array $extracts index -> $line
890 * @param int $count
891 * @param string $text
892 */
893 function splitAndAdd(&$extracts, &$count, $text){
894 $split = explode( "\n", $this->mCleanWikitext? $this->removeWiki($text) : $text );
895 foreach($split as $line){
896 $tt = trim($line);
897 if( $tt )
898 $extracts[$count++] = $tt;
899 }
900 }
901
902 /**
903 * Do manual case conversion for non-ascii chars
904 *
905 * @param unknown_type $matches
906 */
907 function caseCallback($matches){
908 global $wgContLang;
909 if( strlen($matches[0]) > 1 ){
910 return '['.$wgContLang->lc($matches[0]).$wgContLang->uc($matches[0]).']';
911 } else
912 return $matches[0];
913 }
914
915 /**
916 * Extract part of the text from start to end, but by
917 * not chopping up words
918 * @param string $text
919 * @param int $start
920 * @param int $end
921 * @param int $posStart (out) actual start position
922 * @param int $posEnd (out) actual end position
923 * @return string
924 */
925 function extract($text, $start, $end, &$posStart = null, &$posEnd = null ){
926 global $wgContLang;
927
928 if( $start != 0)
929 $start = $this->position( $text, $start, 1 );
930 if( $end >= strlen($text) )
931 $end = strlen($text);
932 else
933 $end = $this->position( $text, $end );
934
935 if(!is_null($posStart))
936 $posStart = $start;
937 if(!is_null($posEnd))
938 $posEnd = $end;
939
940 if($end > $start)
941 return substr($text, $start, $end-$start);
942 else
943 return '';
944 }
945
946 /**
947 * Find a nonletter near a point (index) in the text
948 *
949 * @param string $text
950 * @param int $point
951 * @param int $offset to found index
952 * @return int nearest nonletter index, or beginning of utf8 char if none
953 */
954 function position($text, $point, $offset=0 ){
955 $tolerance = 10;
956 $s = max( 0, $point - $tolerance );
957 $l = min( strlen($text), $point + $tolerance ) - $s;
958 $m = array();
959 if( preg_match('/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr($text,$s,$l), $m, PREG_OFFSET_CAPTURE ) ){
960 return $m[0][1] + $s + $offset;
961 } else{
962 // check if point is on a valid first UTF8 char
963 $char = ord( $text[$point] );
964 while( $char >= 0x80 && $char < 0xc0 ) {
965 // skip trailing bytes
966 $point++;
967 if($point >= strlen($text))
968 return strlen($text);
969 $char = ord( $text[$point] );
970 }
971 return $point;
972
973 }
974 }
975
976 /**
977 * Search extracts for a pattern, and return snippets
978 *
979 * @param string $pattern regexp for matching lines
980 * @param array $extracts extracts to search
981 * @param int $linesleft number of extracts to make
982 * @param int $contextchars length of snippet
983 * @param array $out map for highlighted snippets
984 * @param array $offsets map of starting points of snippets
985 * @protected
986 */
987 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ){
988 if($linesleft == 0)
989 return; // nothing to do
990 foreach($extracts as $index => $line){
991 if( array_key_exists($index,$out) )
992 continue; // this line already highlighted
993
994 $m = array();
995 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) )
996 continue;
997
998 $offset = $m[0][1];
999 $len = strlen($m[0][0]);
1000 if($offset + $len < $contextchars)
1001 $begin = 0;
1002 elseif( $len > $contextchars)
1003 $begin = $offset;
1004 else
1005 $begin = $offset + intval( ($len - $contextchars) / 2 );
1006
1007 $end = $begin + $contextchars;
1008
1009 $posBegin = $begin;
1010 // basic snippet from this line
1011 $out[$index] = $this->extract($line,$begin,$end,$posBegin);
1012 $offsets[$index] = $posBegin;
1013 $linesleft--;
1014 if($linesleft == 0)
1015 return;
1016 }
1017 }
1018
1019 /**
1020 * Basic wikitext removal
1021 * @protected
1022 */
1023 function removeWiki($text) {
1024 $fname = __METHOD__;
1025 wfProfileIn( $fname );
1026
1027 //$text = preg_replace("/'{2,5}/", "", $text);
1028 //$text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1029 //$text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1030 //$text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1031 //$text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1032 //$text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1033 $text = preg_replace("/\\{\\{([^|]+?)\\}\\}/", "", $text);
1034 $text = preg_replace("/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text);
1035 $text = preg_replace("/\\[\\[([^|]+?)\\]\\]/", "\\1", $text);
1036 $text = preg_replace_callback("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array($this,'linkReplace'), $text);
1037 //$text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1038 $text = preg_replace("/<\/?[^>]+>/", "", $text);
1039 $text = preg_replace("/'''''/", "", $text);
1040 $text = preg_replace("/('''|<\/?[iIuUbB]>)/", "", $text);
1041 $text = preg_replace("/''/", "", $text);
1042
1043 wfProfileOut( $fname );
1044 return $text;
1045 }
1046
1047 /**
1048 * callback to replace [[target|caption]] kind of links, if
1049 * the target is category or image, leave it
1050 *
1051 * @param array $matches
1052 */
1053 function linkReplace($matches){
1054 $colon = strpos( $matches[1], ':' );
1055 if( $colon === false )
1056 return $matches[2]; // replace with caption
1057 global $wgContLang;
1058 $ns = substr( $matches[1], 0, $colon );
1059 $index = $wgContLang->getNsIndex($ns);
1060 if( $index !== false && ($index == NS_IMAGE || $index == NS_CATEGORY) )
1061 return $matches[0]; // return the whole thing
1062 else
1063 return $matches[2];
1064
1065 }
1066
1067 /**
1068 * Simple & fast snippet extraction, but gives completely unrelevant
1069 * snippets
1070 *
1071 * @param string $text
1072 * @param array $terms
1073 * @param int $contextlines
1074 * @param int $contextchars
1075 * @return string
1076 */
1077 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1078 global $wgLang, $wgContLang;
1079 $fname = __METHOD__;
1080
1081 $lines = explode( "\n", $text );
1082
1083 $terms = implode( '|', $terms );
1084 $terms = str_replace( '/', "\\/", $terms);
1085 $max = intval( $contextchars ) + 1;
1086 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1087
1088 $lineno = 0;
1089
1090 $extract = "";
1091 wfProfileIn( "$fname-extract" );
1092 foreach ( $lines as $line ) {
1093 if ( 0 == $contextlines ) {
1094 break;
1095 }
1096 ++$lineno;
1097 $m = array();
1098 if ( ! preg_match( $pat1, $line, $m ) ) {
1099 continue;
1100 }
1101 --$contextlines;
1102 $pre = $wgContLang->truncate( $m[1], -$contextchars, ' ... ' );
1103
1104 if ( count( $m ) < 3 ) {
1105 $post = '';
1106 } else {
1107 $post = $wgContLang->truncate( $m[3], $contextchars, ' ... ' );
1108 }
1109
1110 $found = $m[2];
1111
1112 $line = htmlspecialchars( $pre . $found . $post );
1113 $pat2 = '/(' . $terms . ")/i";
1114 $line = preg_replace( $pat2,
1115 "<span class='searchmatch'>\\1</span>", $line );
1116
1117 $extract .= "${line}\n";
1118 }
1119 wfProfileOut( "$fname-extract" );
1120
1121 return $extract;
1122 }
1123
1124 }
1125
1126 /**
1127 * Dummy class to be used when non-supported Database engine is present.
1128 * @fixme Dummy class should probably try something at least mildly useful,
1129 * such as a LIKE search through titles.
1130 * @ingroup Search
1131 */
1132 class SearchEngineDummy extends SearchEngine {
1133 // no-op
1134 }