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