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