Kill undefined variable warnings.
[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 // 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;
749 }
750 }
751 $anyterm = implode( '|', $terms );
752 $phrase = implode("$wgSearchHighlightBoundaries+", $terms );
753
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 );
760
761 $patPre = "(^|$wgSearchHighlightBoundaries)";
762 $patPost = "($wgSearchHighlightBoundaries|$)";
763
764 $pat1 = "/(".$phrase.")/ui";
765 $pat2 = "/$patPre(".$anyterm.")$patPost/ui";
766
767 wfProfileIn( "$fname-extract" );
768
769 $left = $contextlines;
770
771 $snippets = array();
772 $offsets = array();
773
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;
782 }
783 }
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;
791 }
792 }
793 if( $succ ){
794 $snippets[$first] = $firstText;
795 $offsets[$first] = 0;
796 }
797 }
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);
807
808 ksort($snippets);
809 }
810
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]);
823 }
824
825 // calc by how much to extend existing snippets
826 $targetchars = intval( ($contextchars * $contextlines) / count ( $snippets ) );
827 }
828
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] );
837 }
838
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++;
849 }
850 }
851 }
852
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;
864
865 $last = $index;
866 }
867 if( $extract )
868 $extract .= '<b> ... </b>';
869
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;
877 }
878 }
879
880 wfProfileOut( "$fname-extract" );
881
882 return $extract;
883 }
884
885 /**
886 * Split text into lines and add it to extracts array
887 *
888 * @param array $extracts index -> $line
889 * @param int $count
890 * @param string $text
891 */
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;
898 }
899 }
900
901 /**
902 * Do manual case conversion for non-ascii chars
903 *
904 * @param unknown_type $matches
905 */
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];
912 }
913
914 /**
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
923 */
924 function extract($text, $start, $end, &$posStart = null, &$posEnd = null ){
925 global $wgContLang;
926
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 );
933
934 if(!is_null($posStart))
935 $posStart = $start;
936 if(!is_null($posEnd))
937 $posEnd = $end;
938
939 if($end > $start)
940 return substr($text, $start, $end-$start);
941 else
942 return '';
943 }
944
945 /**
946 * Find a nonletter near a point (index) in the text
947 *
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
952 */
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] );
969 }
970 return $point;
971
972 }
973 }
974
975 /**
976 * Search extracts for a pattern, and return snippets
977 *
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
985 */
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
992
993 $m = array();
994 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) )
995 continue;
996
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 );
1005
1006 $end = $begin + $contextchars;
1007
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;
1015 }
1016 }
1017
1018 /**
1019 * Basic wikitext removal
1020 * @protected
1021 */
1022 function removeWiki($text) {
1023 $fname = __METHOD__;
1024 wfProfileIn( $fname );
1025
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);
1041
1042 wfProfileOut( $fname );
1043 return $text;
1044 }
1045
1046 /**
1047 * callback to replace [[target|caption]] kind of links, if
1048 * the target is category or image, leave it
1049 *
1050 * @param array $matches
1051 */
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];
1063
1064 }
1065
1066 /**
1067 * Simple & fast snippet extraction, but gives completely unrelevant
1068 * snippets
1069 *
1070 * @param string $text
1071 * @param array $terms
1072 * @param int $contextlines
1073 * @param int $contextchars
1074 * @return string
1075 */
1076 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1077 global $wgLang, $wgContLang;
1078 $fname = __METHOD__;
1079
1080 $lines = explode( "\n", $text );
1081
1082 $terms = implode( '|', $terms );
1083 $max = intval( $contextchars ) + 1;
1084 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1085
1086 $lineno = 0;
1087
1088 $extract = "";
1089 wfProfileIn( "$fname-extract" );
1090 foreach ( $lines as $line ) {
1091 if ( 0 == $contextlines ) {
1092 break;
1093 }
1094 ++$lineno;
1095 $m = array();
1096 if ( ! preg_match( $pat1, $line, $m ) ) {
1097 continue;
1098 }
1099 --$contextlines;
1100 $pre = $wgContLang->truncate( $m[1], -$contextchars, ' ... ' );
1101
1102 if ( count( $m ) < 3 ) {
1103 $post = '';
1104 } else {
1105 $post = $wgContLang->truncate( $m[3], $contextchars, ' ... ' );
1106 }
1107
1108 $found = $m[2];
1109
1110 $line = htmlspecialchars( $pre . $found . $post );
1111 $pat2 = '/(' . $terms . ")/i";
1112 $line = preg_replace( $pat2,
1113 "<span class='searchmatch'>\\1</span>", $line );
1114
1115 $extract .= "${line}\n";
1116 }
1117 wfProfileOut( "$fname-extract" );
1118
1119 return $extract;
1120 }
1121
1122 }
1123
1124 /**
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
1129 */
1130 class SearchEngineDummy extends SearchEngine {
1131 // no-op
1132 }