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