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