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