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