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