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