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