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