Redesign of the "new search UI" per Trevor's design plans from usability wiki:
[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 $prefix = '';
17 var $searchTerms = array();
18 var $namespaces = array( NS_MAIN );
19 var $showRedirects = false;
20
21 /**
22 * Perform a full text search query and return a result set.
23 * If title searches are not supported or disabled, return null.
24 * STUB
25 *
26 * @param $term String: raw search term
27 * @return SearchResultSet
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 * STUB
37 *
38 * @param $term String: raw search term
39 * @return SearchResultSet
40 */
41 function searchTitle( $term ) {
42 return null;
43 }
44
45 /** If this search backend can list/unlist redirects */
46 function acceptListRedirects() {
47 return true;
48 }
49
50 /**
51 * Transform search term in cases when parts of the query came as different GET params (when supported)
52 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
53 */
54 function transformSearchTerm( $term ) {
55 return $term;
56 }
57
58 /**
59 * If an exact title match can be find, or a very slightly close match,
60 * return the title. If no match, returns NULL.
61 *
62 * @param $searchterm String
63 * @return Title
64 */
65 public static function getNearMatch( $searchterm ) {
66 global $wgContLang;
67
68 $allSearchTerms = array($searchterm);
69
70 if($wgContLang->hasVariants()){
71 $allSearchTerms = array_merge($allSearchTerms,$wgContLang->convertLinkToAllVariants($searchterm));
72 }
73
74 foreach($allSearchTerms as $term){
75
76 # Exact match? No need to look further.
77 $title = Title::newFromText( $term );
78 if (is_null($title))
79 return NULL;
80
81 if ( $title->getNamespace() == NS_SPECIAL || $title->isExternal() || $title->exists() ) {
82 return $title;
83 }
84
85 # See if it still otherwise has content is some sane sense
86 $article = MediaWiki::articleFromTitle( $title );
87 if( $article->hasViewableContent() ) {
88 return $title;
89 }
90
91 # Now try all lower case (i.e. first letter capitalized)
92 #
93 $title = Title::newFromText( $wgContLang->lc( $term ) );
94 if ( $title && $title->exists() ) {
95 return $title;
96 }
97
98 # Now try capitalized string
99 #
100 $title = Title::newFromText( $wgContLang->ucwords( $term ) );
101 if ( $title && $title->exists() ) {
102 return $title;
103 }
104
105 # Now try all upper case
106 #
107 $title = Title::newFromText( $wgContLang->uc( $term ) );
108 if ( $title && $title->exists() ) {
109 return $title;
110 }
111
112 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
113 $title = Title::newFromText( $wgContLang->ucwordbreaks($term) );
114 if ( $title && $title->exists() ) {
115 return $title;
116 }
117
118 // Give hooks a chance at better match variants
119 $title = null;
120 if( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
121 return $title;
122 }
123 }
124
125 $title = Title::newFromText( $searchterm );
126
127 # Entering an IP address goes to the contributions page
128 if ( ( $title->getNamespace() == NS_USER && User::isIP($title->getText() ) )
129 || User::isIP( trim( $searchterm ) ) ) {
130 return SpecialPage::getTitleFor( 'Contributions', $title->getDBkey() );
131 }
132
133
134 # Entering a user goes to the user page whether it's there or not
135 if ( $title->getNamespace() == NS_USER ) {
136 return $title;
137 }
138
139 # Go to images that exist even if there's no local page.
140 # There may have been a funny upload, or it may be on a shared
141 # file repository such as Wikimedia Commons.
142 if( $title->getNamespace() == NS_FILE ) {
143 $image = wfFindFile( $title );
144 if( $image ) {
145 return $title;
146 }
147 }
148
149 # MediaWiki namespace? Page may be "implied" if not customized.
150 # Just return it, with caps forced as the message system likes it.
151 if( $title->getNamespace() == NS_MEDIAWIKI ) {
152 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( $title->getText() ) );
153 }
154
155 # Quoted term? Try without the quotes...
156 $matches = array();
157 if( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
158 return SearchEngine::getNearMatch( $matches[1] );
159 }
160
161 return NULL;
162 }
163
164 public static function legalSearchChars() {
165 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
166 }
167
168 /**
169 * Set the maximum number of results to return
170 * and how many to skip before returning the first.
171 *
172 * @param $limit Integer
173 * @param $offset Integer
174 */
175 function setLimitOffset( $limit, $offset = 0 ) {
176 $this->limit = intval( $limit );
177 $this->offset = intval( $offset );
178 }
179
180 /**
181 * Set which namespaces the search should include.
182 * Give an array of namespace index numbers.
183 *
184 * @param $namespaces Array
185 */
186 function setNamespaces( $namespaces ) {
187 $this->namespaces = $namespaces;
188 }
189
190 /**
191 * Parse some common prefixes: all (search everything)
192 * or namespace names
193 *
194 * @param $query String
195 */
196 function replacePrefixes( $query ){
197 global $wgContLang;
198
199 if( strpos($query,':') === false )
200 return $query; // nothing to do
201
202 $parsed = $query;
203 $allkeyword = wfMsgForContent('searchall').":";
204 if( strncmp($query, $allkeyword, strlen($allkeyword)) == 0 ){
205 $this->namespaces = null;
206 $parsed = substr($query,strlen($allkeyword));
207 } else if( strpos($query,':') !== false ) {
208 $prefix = substr($query,0,strpos($query,':'));
209 $index = $wgContLang->getNsIndex($prefix);
210 if($index !== false){
211 $this->namespaces = array($index);
212 $parsed = substr($query,strlen($prefix)+1);
213 }
214 }
215 if(trim($parsed) == '')
216 return $query; // prefix was the whole query
217
218 return $parsed;
219 }
220
221 /**
222 * Make a list of searchable namespaces and their canonical names.
223 * @return Array
224 */
225 public static function searchableNamespaces() {
226 global $wgContLang;
227 $arr = array();
228 foreach( $wgContLang->getNamespaces() as $ns => $name ) {
229 if( $ns >= NS_MAIN ) {
230 $arr[$ns] = $name;
231 }
232 }
233 return $arr;
234 }
235
236 /**
237 * Extract default namespaces to search from the given user's
238 * settings, returning a list of index numbers.
239 *
240 * @param $user User
241 * @return Array
242 */
243 public static function userNamespaces( $user ) {
244 $arr = Preferences::loadOldSearchNs( $user );
245 $searchableNamespaces = SearchEngine::searchableNamespaces();
246
247 $arr = array_intersect( $arr, array_keys($searchableNamespaces) ); // Filter
248
249 return $arr;
250 }
251
252 /**
253 * Find snippet highlight settings for a given user
254 *
255 * @param $user User
256 * @return Array contextlines, contextchars
257 */
258 public static function userHighlightPrefs( &$user ){
259 //$contextlines = $user->getOption( 'contextlines', 5 );
260 //$contextchars = $user->getOption( 'contextchars', 50 );
261 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
262 $contextchars = 75; // same as above.... :P
263 return array($contextlines, $contextchars);
264 }
265
266 /**
267 * An array of namespaces indexes to be searched by default
268 *
269 * @return Array
270 */
271 public static function defaultNamespaces(){
272 global $wgNamespacesToBeSearchedDefault;
273
274 return array_keys($wgNamespacesToBeSearchedDefault, true);
275 }
276
277 /**
278 * Get a list of namespace names useful for showing in tooltips
279 * and preferences
280 *
281 * @param $namespaces Array
282 */
283 public static function namespacesAsText( $namespaces ){
284 global $wgContLang;
285
286 $formatted = array_map( array($wgContLang,'getFormattedNsText'), $namespaces );
287 foreach( $formatted as $key => $ns ){
288 if ( empty($ns) )
289 $formatted[$key] = wfMsg( 'blanknamespace' );
290 }
291 return $formatted;
292 }
293
294 /**
295 * Return the help namespaces to be shown on Special:Search
296 *
297 * @return Array
298 */
299 public static function helpNamespaces() {
300 global $wgNamespacesToBeSearchedHelp;
301
302 return array_keys( $wgNamespacesToBeSearchedHelp, true );
303 }
304
305 /**
306 * Return a 'cleaned up' search string
307 *
308 * @param $text String
309 * @return String
310 */
311 function filter( $text ) {
312 $lc = $this->legalSearchChars();
313 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
314 }
315 /**
316 * Load up the appropriate search engine class for the currently
317 * active database backend, and return a configured instance.
318 *
319 * @return SearchEngine
320 */
321 public static function create() {
322 global $wgSearchType;
323 $dbr = wfGetDB( DB_SLAVE );
324 if( $wgSearchType ) {
325 $class = $wgSearchType;
326 } else {
327 $class = $dbr->getSearchEngine();
328 }
329 $search = new $class( $dbr );
330 $search->setLimitOffset(0,0);
331 return $search;
332 }
333
334 /**
335 * Create or update the search index record for the given page.
336 * Title and text should be pre-processed.
337 * STUB
338 *
339 * @param $id Integer
340 * @param $title String
341 * @param $text String
342 */
343 function update( $id, $title, $text ) {
344 // no-op
345 }
346
347 /**
348 * Update a search index record's title only.
349 * Title should be pre-processed.
350 * STUB
351 *
352 * @param $id Integer
353 * @param $title String
354 */
355 function updateTitle( $id, $title ) {
356 // no-op
357 }
358
359 /**
360 * Get OpenSearch suggestion template
361 *
362 * @return String
363 */
364 public static function getOpenSearchTemplate() {
365 global $wgOpenSearchTemplate, $wgServer, $wgScriptPath;
366 if( $wgOpenSearchTemplate ) {
367 return $wgOpenSearchTemplate;
368 } else {
369 $ns = implode( '|', SearchEngine::defaultNamespaces() );
370 if( !$ns ) $ns = "0";
371 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace='.$ns;
372 }
373 }
374
375 /**
376 * Get internal MediaWiki Suggest template
377 *
378 * @return String
379 */
380 public static function getMWSuggestTemplate() {
381 global $wgMWSuggestTemplate, $wgServer, $wgScriptPath;
382 if($wgMWSuggestTemplate)
383 return $wgMWSuggestTemplate;
384 else
385 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
386 }
387 }
388
389 /**
390 * @ingroup Search
391 */
392 class SearchResultSet {
393 /**
394 * Fetch an array of regular expression fragments for matching
395 * the search terms as parsed by this engine in a text extract.
396 * STUB
397 *
398 * @return Array
399 */
400 function termMatches() {
401 return array();
402 }
403
404 function numRows() {
405 return 0;
406 }
407
408 /**
409 * Return true if results are included in this result set.
410 * STUB
411 *
412 * @return Boolean
413 */
414 function hasResults() {
415 return false;
416 }
417
418 /**
419 * Some search modes return a total hit count for the query
420 * in the entire article database. This may include pages
421 * in namespaces that would not be matched on the given
422 * settings.
423 *
424 * Return null if no total hits number is supported.
425 *
426 * @return Integer
427 */
428 function getTotalHits() {
429 return null;
430 }
431
432 /**
433 * Some search modes return a suggested alternate term if there are
434 * no exact hits. Returns true if there is one on this set.
435 *
436 * @return Boolean
437 */
438 function hasSuggestion() {
439 return false;
440 }
441
442 /**
443 * @return String: suggested query, null if none
444 */
445 function getSuggestionQuery(){
446 return null;
447 }
448
449 /**
450 * @return String: HTML highlighted suggested query, '' if none
451 */
452 function getSuggestionSnippet(){
453 return '';
454 }
455
456 /**
457 * Return information about how and from where the results were fetched,
458 * should be useful for diagnostics and debugging
459 *
460 * @return String
461 */
462 function getInfo() {
463 return null;
464 }
465
466 /**
467 * Return a result set of hits on other (multiple) wikis associated with this one
468 *
469 * @return SearchResultSet
470 */
471 function getInterwikiResults() {
472 return null;
473 }
474
475 /**
476 * Check if there are results on other wikis
477 *
478 * @return Boolean
479 */
480 function hasInterwikiResults() {
481 return $this->getInterwikiResults() != null;
482 }
483
484
485 /**
486 * Fetches next search result, or false.
487 * STUB
488 *
489 * @return SearchResult
490 */
491 function next() {
492 return false;
493 }
494
495 /**
496 * Frees the result set, if applicable.
497 */
498 function free() {
499 // ...
500 }
501 }
502
503
504 /**
505 * @ingroup Search
506 */
507 class SearchResultTooMany {
508 ## Some search engines may bail out if too many matches are found
509 }
510
511
512 /**
513 * @todo Fixme: This class is horribly factored. It would probably be better to
514 * have a useful base class to which you pass some standard information, then
515 * let the fancy self-highlighters extend that.
516 * @ingroup Search
517 */
518 class SearchResult {
519 var $mRevision = null;
520 var $mImage = null;
521
522 function __construct( $row ) {
523 $this->mTitle = Title::makeTitle( $row->page_namespace, $row->page_title );
524 if( !is_null($this->mTitle) ){
525 $this->mRevision = Revision::newFromTitle( $this->mTitle );
526 if( $this->mTitle->getNamespace() === NS_FILE )
527 $this->mImage = wfFindFile( $this->mTitle );
528 }
529 }
530
531 /**
532 * Check if this is result points to an invalid title
533 *
534 * @return Boolean
535 */
536 function isBrokenTitle(){
537 if( is_null($this->mTitle) )
538 return true;
539 return false;
540 }
541
542 /**
543 * Check if target page is missing, happens when index is out of date
544 *
545 * @return Boolean
546 */
547 function isMissingRevision(){
548 return !$this->mRevision && !$this->mImage;
549 }
550
551 /**
552 * @return Title
553 */
554 function getTitle() {
555 return $this->mTitle;
556 }
557
558 /**
559 * @return Double or null if not supported
560 */
561 function getScore() {
562 return null;
563 }
564
565 /**
566 * Lazy initialization of article text from DB
567 */
568 protected function initText(){
569 if( !isset($this->mText) ){
570 if($this->mRevision != null)
571 $this->mText = $this->mRevision->getText();
572 else // TODO: can we fetch raw wikitext for commons images?
573 $this->mText = '';
574
575 }
576 }
577
578 /**
579 * @param $terms Array: terms to highlight
580 * @return String: highlighted text snippet, null (and not '') if not supported
581 */
582 function getTextSnippet($terms){
583 global $wgUser, $wgAdvancedSearchHighlighting;
584 $this->initText();
585 list($contextlines,$contextchars) = SearchEngine::userHighlightPrefs($wgUser);
586 $h = new SearchHighlighter();
587 if( $wgAdvancedSearchHighlighting )
588 return $h->highlightText( $this->mText, $terms, $contextlines, $contextchars );
589 else
590 return $h->highlightSimple( $this->mText, $terms, $contextlines, $contextchars );
591 }
592
593 /**
594 * @param $terms Array: terms to highlight
595 * @return String: highlighted title, '' if not supported
596 */
597 function getTitleSnippet($terms){
598 return '';
599 }
600
601 /**
602 * @param $terms Array: terms to highlight
603 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
604 */
605 function getRedirectSnippet($terms){
606 return '';
607 }
608
609 /**
610 * @return Title object for the redirect to this page, null if none or not supported
611 */
612 function getRedirectTitle(){
613 return null;
614 }
615
616 /**
617 * @return string highlighted relevant section name, null if none or not supported
618 */
619 function getSectionSnippet(){
620 return '';
621 }
622
623 /**
624 * @return Title object (pagename+fragment) for the section, null if none or not supported
625 */
626 function getSectionTitle(){
627 return null;
628 }
629
630 /**
631 * @return String: timestamp
632 */
633 function getTimestamp(){
634 if( $this->mRevision )
635 return $this->mRevision->getTimestamp();
636 else if( $this->mImage )
637 return $this->mImage->getTimestamp();
638 return '';
639 }
640
641 /**
642 * @return Integer: number of words
643 */
644 function getWordCount(){
645 $this->initText();
646 return str_word_count( $this->mText );
647 }
648
649 /**
650 * @return Integer: size in bytes
651 */
652 function getByteSize(){
653 $this->initText();
654 return strlen( $this->mText );
655 }
656
657 /**
658 * @return Boolean if hit has related articles
659 */
660 function hasRelated(){
661 return false;
662 }
663
664 /**
665 * @return String: interwiki prefix of the title (return iw even if title is broken)
666 */
667 function getInterwikiPrefix(){
668 return '';
669 }
670 }
671
672 /**
673 * Highlight bits of wikitext
674 *
675 * @ingroup Search
676 */
677 class SearchHighlighter {
678 var $mCleanWikitext = true;
679
680 function SearchHighlighter($cleanupWikitext = true){
681 $this->mCleanWikitext = $cleanupWikitext;
682 }
683
684 /**
685 * Default implementation of wikitext highlighting
686 *
687 * @param $text String
688 * @param $terms Array: terms to highlight (unescaped)
689 * @param $contextlines Integer
690 * @param $contextchars Integer
691 * @return String
692 */
693 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
694 global $wgLang, $wgContLang;
695 global $wgSearchHighlightBoundaries;
696 $fname = __METHOD__;
697
698 if($text == '')
699 return '';
700
701 // spli text into text + templates/links/tables
702 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
703 // first capture group is for detecting nested templates/links/tables/references
704 $endPatterns = array(
705 1 => '/(\{\{)|(\}\})/', // template
706 2 => '/(\[\[)|(\]\])/', // image
707 3 => "/(\n\\{\\|)|(\n\\|\\})/"); // table
708
709 // FIXME: this should prolly be a hook or something
710 if(function_exists('wfCite')){
711 $spat .= '|(<ref>)'; // references via cite extension
712 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
713 }
714 $spat .= '/';
715 $textExt = array(); // text extracts
716 $otherExt = array(); // other extracts
717 wfProfileIn( "$fname-split" );
718 $start = 0;
719 $textLen = strlen($text);
720 $count = 0; // sequence number to maintain ordering
721 while( $start < $textLen ){
722 // find start of template/image/table
723 if( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE, $start ) ){
724 $epat = '';
725 foreach($matches as $key => $val){
726 if($key > 0 && $val[1] != -1){
727 if($key == 2){
728 // see if this is an image link
729 $ns = substr($val[0],2,-1);
730 if( $wgContLang->getNsIndex($ns) != NS_FILE )
731 break;
732
733 }
734 $epat = $endPatterns[$key];
735 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
736 $start = $val[1];
737 break;
738 }
739 }
740 if( $epat ){
741 // find end (and detect any nested elements)
742 $level = 0;
743 $offset = $start + 1;
744 $found = false;
745 while( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE, $offset ) ){
746 if( array_key_exists(2,$endMatches) ){
747 // found end
748 if($level == 0){
749 $len = strlen($endMatches[2][0]);
750 $off = $endMatches[2][1];
751 $this->splitAndAdd( $otherExt, $count,
752 substr( $text, $start, $off + $len - $start ) );
753 $start = $off + $len;
754 $found = true;
755 break;
756 } else{
757 // end of nested element
758 $level -= 1;
759 }
760 } else{
761 // nested
762 $level += 1;
763 }
764 $offset = $endMatches[0][1] + strlen($endMatches[0][0]);
765 }
766 if( ! $found ){
767 // couldn't find appropriate closing tag, skip
768 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen($matches[0][0]) ) );
769 $start += strlen($matches[0][0]);
770 }
771 continue;
772 }
773 }
774 // else: add as text extract
775 $this->splitAndAdd( $textExt, $count, substr($text,$start) );
776 break;
777 }
778
779 $all = $textExt + $otherExt; // these have disjunct key sets
780
781 wfProfileOut( "$fname-split" );
782
783 // prepare regexps
784 foreach( $terms as $index => $term ) {
785 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
786 if(preg_match('/[\x80-\xff]/', $term) ){
787 $terms[$index] = preg_replace_callback('/./us',array($this,'caseCallback'),$terms[$index]);
788 } else {
789 $terms[$index] = $term;
790 }
791 }
792 $anyterm = implode( '|', $terms );
793 $phrase = implode("$wgSearchHighlightBoundaries+", $terms );
794
795 // FIXME: a hack to scale contextchars, a correct solution
796 // would be to have contextchars actually be char and not byte
797 // length, and do proper utf-8 substrings and lengths everywhere,
798 // but PHP is making that very hard and unclean to implement :(
799 $scale = strlen($anyterm) / mb_strlen($anyterm);
800 $contextchars = intval( $contextchars * $scale );
801
802 $patPre = "(^|$wgSearchHighlightBoundaries)";
803 $patPost = "($wgSearchHighlightBoundaries|$)";
804
805 $pat1 = "/(".$phrase.")/ui";
806 $pat2 = "/$patPre(".$anyterm.")$patPost/ui";
807
808 wfProfileIn( "$fname-extract" );
809
810 $left = $contextlines;
811
812 $snippets = array();
813 $offsets = array();
814
815 // show beginning only if it contains all words
816 $first = 0;
817 $firstText = '';
818 foreach($textExt as $index => $line){
819 if(strlen($line)>0 && $line[0] != ';' && $line[0] != ':'){
820 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
821 $first = $index;
822 break;
823 }
824 }
825 if( $firstText ){
826 $succ = true;
827 // check if first text contains all terms
828 foreach($terms as $term){
829 if( ! preg_match("/$patPre".$term."$patPost/ui", $firstText) ){
830 $succ = false;
831 break;
832 }
833 }
834 if( $succ ){
835 $snippets[$first] = $firstText;
836 $offsets[$first] = 0;
837 }
838 }
839 if( ! $snippets ) {
840 // match whole query on text
841 $this->process($pat1, $textExt, $left, $contextchars, $snippets, $offsets);
842 // match whole query on templates/tables/images
843 $this->process($pat1, $otherExt, $left, $contextchars, $snippets, $offsets);
844 // match any words on text
845 $this->process($pat2, $textExt, $left, $contextchars, $snippets, $offsets);
846 // match any words on templates/tables/images
847 $this->process($pat2, $otherExt, $left, $contextchars, $snippets, $offsets);
848
849 ksort($snippets);
850 }
851
852 // add extra chars to each snippet to make snippets constant size
853 $extended = array();
854 if( count( $snippets ) == 0){
855 // couldn't find the target words, just show beginning of article
856 $targetchars = $contextchars * $contextlines;
857 $snippets[$first] = '';
858 $offsets[$first] = 0;
859 } else{
860 // if begin of the article contains the whole phrase, show only that !!
861 if( array_key_exists($first,$snippets) && preg_match($pat1,$snippets[$first])
862 && $offsets[$first] < $contextchars * 2 ){
863 $snippets = array ($first => $snippets[$first]);
864 }
865
866 // calc by how much to extend existing snippets
867 $targetchars = intval( ($contextchars * $contextlines) / count ( $snippets ) );
868 }
869
870 foreach($snippets as $index => $line){
871 $extended[$index] = $line;
872 $len = strlen($line);
873 if( $len < $targetchars - 20 ){
874 // complete this line
875 if($len < strlen( $all[$index] )){
876 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index]+$targetchars, $offsets[$index]);
877 $len = strlen( $extended[$index] );
878 }
879
880 // add more lines
881 $add = $index + 1;
882 while( $len < $targetchars - 20
883 && array_key_exists($add,$all)
884 && !array_key_exists($add,$snippets) ){
885 $offsets[$add] = 0;
886 $tt = "\n".$this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
887 $extended[$add] = $tt;
888 $len += strlen( $tt );
889 $add++;
890 }
891 }
892 }
893
894 //$snippets = array_map('htmlspecialchars', $extended);
895 $snippets = $extended;
896 $last = -1;
897 $extract = '';
898 foreach($snippets as $index => $line){
899 if($last == -1)
900 $extract .= $line; // first line
901 elseif($last+1 == $index && $offsets[$last]+strlen($snippets[$last]) >= strlen($all[$last]))
902 $extract .= " ".$line; // continous lines
903 else
904 $extract .= '<b> ... </b>' . $line;
905
906 $last = $index;
907 }
908 if( $extract )
909 $extract .= '<b> ... </b>';
910
911 $processed = array();
912 foreach($terms as $term){
913 if( ! isset($processed[$term]) ){
914 $pat3 = "/$patPre(".$term.")$patPost/ui"; // highlight word
915 $extract = preg_replace( $pat3,
916 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
917 $processed[$term] = true;
918 }
919 }
920
921 wfProfileOut( "$fname-extract" );
922
923 return $extract;
924 }
925
926 /**
927 * Split text into lines and add it to extracts array
928 *
929 * @param $extracts Array: index -> $line
930 * @param $count Integer
931 * @param $text String
932 */
933 function splitAndAdd(&$extracts, &$count, $text){
934 $split = explode( "\n", $this->mCleanWikitext? $this->removeWiki($text) : $text );
935 foreach($split as $line){
936 $tt = trim($line);
937 if( $tt )
938 $extracts[$count++] = $tt;
939 }
940 }
941
942 /**
943 * Do manual case conversion for non-ascii chars
944 *
945 * @param $matches Array
946 */
947 function caseCallback($matches){
948 global $wgContLang;
949 if( strlen($matches[0]) > 1 ){
950 return '['.$wgContLang->lc($matches[0]).$wgContLang->uc($matches[0]).']';
951 } else
952 return $matches[0];
953 }
954
955 /**
956 * Extract part of the text from start to end, but by
957 * not chopping up words
958 * @param $text String
959 * @param $start Integer
960 * @param $end Integer
961 * @param $posStart Integer: (out) actual start position
962 * @param $posEnd Integer: (out) actual end position
963 * @return String
964 */
965 function extract($text, $start, $end, &$posStart = null, &$posEnd = null ){
966 global $wgContLang;
967
968 if( $start != 0)
969 $start = $this->position( $text, $start, 1 );
970 if( $end >= strlen($text) )
971 $end = strlen($text);
972 else
973 $end = $this->position( $text, $end );
974
975 if(!is_null($posStart))
976 $posStart = $start;
977 if(!is_null($posEnd))
978 $posEnd = $end;
979
980 if($end > $start)
981 return substr($text, $start, $end-$start);
982 else
983 return '';
984 }
985
986 /**
987 * Find a nonletter near a point (index) in the text
988 *
989 * @param $text String
990 * @param $point Integer
991 * @param $offset Integer: offset to found index
992 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
993 */
994 function position($text, $point, $offset=0 ){
995 $tolerance = 10;
996 $s = max( 0, $point - $tolerance );
997 $l = min( strlen($text), $point + $tolerance ) - $s;
998 $m = array();
999 if( preg_match('/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr($text,$s,$l), $m, PREG_OFFSET_CAPTURE ) ){
1000 return $m[0][1] + $s + $offset;
1001 } else{
1002 // check if point is on a valid first UTF8 char
1003 $char = ord( $text[$point] );
1004 while( $char >= 0x80 && $char < 0xc0 ) {
1005 // skip trailing bytes
1006 $point++;
1007 if($point >= strlen($text))
1008 return strlen($text);
1009 $char = ord( $text[$point] );
1010 }
1011 return $point;
1012
1013 }
1014 }
1015
1016 /**
1017 * Search extracts for a pattern, and return snippets
1018 *
1019 * @param $pattern String: regexp for matching lines
1020 * @param $extracts Array: extracts to search
1021 * @param $linesleft Integer: number of extracts to make
1022 * @param $contextchars Integer: length of snippet
1023 * @param $out Array: map for highlighted snippets
1024 * @param $offsets Array: map of starting points of snippets
1025 * @protected
1026 */
1027 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ){
1028 if($linesleft == 0)
1029 return; // nothing to do
1030 foreach($extracts as $index => $line){
1031 if( array_key_exists($index,$out) )
1032 continue; // this line already highlighted
1033
1034 $m = array();
1035 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) )
1036 continue;
1037
1038 $offset = $m[0][1];
1039 $len = strlen($m[0][0]);
1040 if($offset + $len < $contextchars)
1041 $begin = 0;
1042 elseif( $len > $contextchars)
1043 $begin = $offset;
1044 else
1045 $begin = $offset + intval( ($len - $contextchars) / 2 );
1046
1047 $end = $begin + $contextchars;
1048
1049 $posBegin = $begin;
1050 // basic snippet from this line
1051 $out[$index] = $this->extract($line,$begin,$end,$posBegin);
1052 $offsets[$index] = $posBegin;
1053 $linesleft--;
1054 if($linesleft == 0)
1055 return;
1056 }
1057 }
1058
1059 /**
1060 * Basic wikitext removal
1061 * @protected
1062 */
1063 function removeWiki($text) {
1064 $fname = __METHOD__;
1065 wfProfileIn( $fname );
1066
1067 //$text = preg_replace("/'{2,5}/", "", $text);
1068 //$text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1069 //$text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1070 //$text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1071 //$text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1072 //$text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1073 $text = preg_replace("/\\{\\{([^|]+?)\\}\\}/", "", $text);
1074 $text = preg_replace("/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text);
1075 $text = preg_replace("/\\[\\[([^|]+?)\\]\\]/", "\\1", $text);
1076 $text = preg_replace_callback("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array($this,'linkReplace'), $text);
1077 //$text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1078 $text = preg_replace("/<\/?[^>]+>/", "", $text);
1079 $text = preg_replace("/'''''/", "", $text);
1080 $text = preg_replace("/('''|<\/?[iIuUbB]>)/", "", $text);
1081 $text = preg_replace("/''/", "", $text);
1082
1083 wfProfileOut( $fname );
1084 return $text;
1085 }
1086
1087 /**
1088 * callback to replace [[target|caption]] kind of links, if
1089 * the target is category or image, leave it
1090 *
1091 * @param $matches Array
1092 */
1093 function linkReplace($matches){
1094 $colon = strpos( $matches[1], ':' );
1095 if( $colon === false )
1096 return $matches[2]; // replace with caption
1097 global $wgContLang;
1098 $ns = substr( $matches[1], 0, $colon );
1099 $index = $wgContLang->getNsIndex($ns);
1100 if( $index !== false && ($index == NS_FILE || $index == NS_CATEGORY) )
1101 return $matches[0]; // return the whole thing
1102 else
1103 return $matches[2];
1104
1105 }
1106
1107 /**
1108 * Simple & fast snippet extraction, but gives completely unrelevant
1109 * snippets
1110 *
1111 * @param $text String
1112 * @param $terms Array
1113 * @param $contextlines Integer
1114 * @param $contextchars Integer
1115 * @return String
1116 */
1117 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1118 global $wgLang, $wgContLang;
1119 $fname = __METHOD__;
1120
1121 $lines = explode( "\n", $text );
1122
1123 $terms = implode( '|', $terms );
1124 $max = intval( $contextchars ) + 1;
1125 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1126
1127 $lineno = 0;
1128
1129 $extract = "";
1130 wfProfileIn( "$fname-extract" );
1131 foreach ( $lines as $line ) {
1132 if ( 0 == $contextlines ) {
1133 break;
1134 }
1135 ++$lineno;
1136 $m = array();
1137 if ( ! preg_match( $pat1, $line, $m ) ) {
1138 continue;
1139 }
1140 --$contextlines;
1141 $pre = $wgContLang->truncate( $m[1], -$contextchars );
1142
1143 if ( count( $m ) < 3 ) {
1144 $post = '';
1145 } else {
1146 $post = $wgContLang->truncate( $m[3], $contextchars );
1147 }
1148
1149 $found = $m[2];
1150
1151 $line = htmlspecialchars( $pre . $found . $post );
1152 $pat2 = '/(' . $terms . ")/i";
1153 $line = preg_replace( $pat2,
1154 "<span class='searchmatch'>\\1</span>", $line );
1155
1156 $extract .= "${line}\n";
1157 }
1158 wfProfileOut( "$fname-extract" );
1159
1160 return $extract;
1161 }
1162
1163 }
1164
1165 /**
1166 * Dummy class to be used when non-supported Database engine is present.
1167 * @todo Fixme: dummy class should probably try something at least mildly useful,
1168 * such as a LIKE search through titles.
1169 * @ingroup Search
1170 */
1171 class SearchEngineDummy extends SearchEngine {
1172 // no-op
1173 }