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