Merge "Allow individual search backends to control whether they SearchUpdate"
[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 $type = $type !== null ? $type : $wgSearchType;
466 if ( $type && in_array( $type, $alternatives ) ) {
467 $class = $type;
468 } else {
469 $dbr = wfGetDB( DB_SLAVE );
470 $class = $dbr->getSearchEngine();
471 }
472 $search = new $class( $dbr );
473 $search->setLimitOffset( 0, 0 );
474 return $search;
475 }
476
477 /**
478 * Return the search engines we support. If only $wgSearchType
479 * is set, it'll be an array of just that one item.
480 *
481 * @return array
482 */
483 public static function getSearchTypes() {
484 global $wgSearchType, $wgSearchTypeAlternatives;
485 static $alternatives = null;
486 if ( $alternatives === null ) {
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 var $mRevision = null;
752 var $mImage = null;
753
754 /**
755 * @var Title
756 */
757 var $mTitle;
758
759 /**
760 * @var String
761 */
762 var $mText;
763
764 /**
765 * Return a new SearchResult and initializes it with a title.
766 *
767 * @param $title Title
768 * @return SearchResult
769 */
770 public static function newFromTitle( $title ) {
771 $result = new self();
772 $result->initFromTitle( $title );
773 return $result;
774 }
775 /**
776 * Return a new SearchResult and initializes it with a row.
777 *
778 * @param $row object
779 * @return SearchResult
780 */
781 public static function newFromRow( $row ) {
782 $result = new self();
783 $result->initFromRow( $row );
784 return $result;
785 }
786
787 public function __construct( $row = null ) {
788 if ( !is_null( $row ) ) {
789 // Backwards compatibility with pre-1.17 callers
790 $this->initFromRow( $row );
791 }
792 }
793
794 /**
795 * Initialize from a database row. Makes a Title and passes that to
796 * initFromTitle.
797 *
798 * @param $row object
799 */
800 protected function initFromRow( $row ) {
801 $this->initFromTitle( Title::makeTitle( $row->page_namespace, $row->page_title ) );
802 }
803
804 /**
805 * Initialize from a Title and if possible initializes a corresponding
806 * Revision and File.
807 *
808 * @param $title Title
809 */
810 protected function initFromTitle( $title ) {
811 $this->mTitle = $title;
812 if ( !is_null( $this->mTitle ) ) {
813 $id = false;
814 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
815 $this->mRevision = Revision::newFromTitle(
816 $this->mTitle, $id, Revision::READ_NORMAL );
817 if ( $this->mTitle->getNamespace() === NS_FILE ) {
818 $this->mImage = wfFindFile( $this->mTitle );
819 }
820 }
821 }
822
823 /**
824 * Check if this is result points to an invalid title
825 *
826 * @return Boolean
827 */
828 function isBrokenTitle() {
829 if ( is_null( $this->mTitle ) ) {
830 return true;
831 }
832 return false;
833 }
834
835 /**
836 * Check if target page is missing, happens when index is out of date
837 *
838 * @return Boolean
839 */
840 function isMissingRevision() {
841 return !$this->mRevision && !$this->mImage;
842 }
843
844 /**
845 * @return Title
846 */
847 function getTitle() {
848 return $this->mTitle;
849 }
850
851 /**
852 * @return float|null if not supported
853 */
854 function getScore() {
855 return null;
856 }
857
858 /**
859 * Lazy initialization of article text from DB
860 */
861 protected function initText() {
862 if ( !isset( $this->mText ) ) {
863 if ( $this->mRevision != null ) {
864 $this->mText = SearchEngine::create()
865 ->getTextFromContent( $this->mTitle, $this->mRevision->getContent() );
866 } else { // TODO: can we fetch raw wikitext for commons images?
867 $this->mText = '';
868 }
869 }
870 }
871
872 /**
873 * @param array $terms terms to highlight
874 * @return String: highlighted text snippet, null (and not '') if not supported
875 */
876 function getTextSnippet( $terms ) {
877 global $wgUser, $wgAdvancedSearchHighlighting;
878 $this->initText();
879
880 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
881 list( $contextlines, $contextchars ) = SearchEngine::userHighlightPrefs( $wgUser );
882 $h = new SearchHighlighter();
883 if ( $wgAdvancedSearchHighlighting ) {
884 return $h->highlightText( $this->mText, $terms, $contextlines, $contextchars );
885 } else {
886 return $h->highlightSimple( $this->mText, $terms, $contextlines, $contextchars );
887 }
888 }
889
890 /**
891 * @param array $terms terms to highlight
892 * @return String: highlighted title, '' if not supported
893 */
894 function getTitleSnippet( $terms ) {
895 return '';
896 }
897
898 /**
899 * @param array $terms terms to highlight
900 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
901 */
902 function getRedirectSnippet( $terms ) {
903 return '';
904 }
905
906 /**
907 * @return Title object for the redirect to this page, null if none or not supported
908 */
909 function getRedirectTitle() {
910 return null;
911 }
912
913 /**
914 * @return string highlighted relevant section name, null if none or not supported
915 */
916 function getSectionSnippet() {
917 return '';
918 }
919
920 /**
921 * @return Title object (pagename+fragment) for the section, null if none or not supported
922 */
923 function getSectionTitle() {
924 return null;
925 }
926
927 /**
928 * @return String: timestamp
929 */
930 function getTimestamp() {
931 if ( $this->mRevision ) {
932 return $this->mRevision->getTimestamp();
933 } elseif ( $this->mImage ) {
934 return $this->mImage->getTimestamp();
935 }
936 return '';
937 }
938
939 /**
940 * @return Integer: number of words
941 */
942 function getWordCount() {
943 $this->initText();
944 return str_word_count( $this->mText );
945 }
946
947 /**
948 * @return Integer: size in bytes
949 */
950 function getByteSize() {
951 $this->initText();
952 return strlen( $this->mText );
953 }
954
955 /**
956 * @return Boolean if hit has related articles
957 */
958 function hasRelated() {
959 return false;
960 }
961
962 /**
963 * @return String: interwiki prefix of the title (return iw even if title is broken)
964 */
965 function getInterwikiPrefix() {
966 return '';
967 }
968 }
969 /**
970 * A SearchResultSet wrapper for SearchEngine::getNearMatch
971 */
972 class SearchNearMatchResultSet extends SearchResultSet {
973 private $fetched = false;
974 /**
975 * @param $match mixed Title if matched, else null
976 */
977 public function __construct( $match ) {
978 $this->result = $match;
979 }
980 public function hasResult() {
981 return (bool)$this->result;
982 }
983 public function numRows() {
984 return $this->hasResults() ? 1 : 0;
985 }
986 public function next() {
987 if ( $this->fetched || !$this->result ) {
988 return false;
989 }
990 $this->fetched = true;
991 return SearchResult::newFromTitle( $this->result );
992 }
993 }
994
995 /**
996 * Highlight bits of wikitext
997 *
998 * @ingroup Search
999 */
1000 class SearchHighlighter {
1001 var $mCleanWikitext = true;
1002
1003 function __construct( $cleanupWikitext = true ) {
1004 $this->mCleanWikitext = $cleanupWikitext;
1005 }
1006
1007 /**
1008 * Default implementation of wikitext highlighting
1009 *
1010 * @param $text String
1011 * @param array $terms terms to highlight (unescaped)
1012 * @param $contextlines Integer
1013 * @param $contextchars Integer
1014 * @return String
1015 */
1016 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
1017 global $wgContLang;
1018 global $wgSearchHighlightBoundaries;
1019 $fname = __METHOD__;
1020
1021 if ( $text == '' ) {
1022 return '';
1023 }
1024
1025 // spli text into text + templates/links/tables
1026 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
1027 // first capture group is for detecting nested templates/links/tables/references
1028 $endPatterns = array(
1029 1 => '/(\{\{)|(\}\})/', // template
1030 2 => '/(\[\[)|(\]\])/', // image
1031 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
1032
1033 // @todo FIXME: This should prolly be a hook or something
1034 if ( function_exists( 'wfCite' ) ) {
1035 $spat .= '|(<ref>)'; // references via cite extension
1036 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
1037 }
1038 $spat .= '/';
1039 $textExt = array(); // text extracts
1040 $otherExt = array(); // other extracts
1041 wfProfileIn( "$fname-split" );
1042 $start = 0;
1043 $textLen = strlen( $text );
1044 $count = 0; // sequence number to maintain ordering
1045 while ( $start < $textLen ) {
1046 // find start of template/image/table
1047 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE, $start ) ) {
1048 $epat = '';
1049 foreach ( $matches as $key => $val ) {
1050 if ( $key > 0 && $val[1] != - 1 ) {
1051 if ( $key == 2 ) {
1052 // see if this is an image link
1053 $ns = substr( $val[0], 2, - 1 );
1054 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE ) {
1055 break;
1056 }
1057
1058 }
1059 $epat = $endPatterns[$key];
1060 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1061 $start = $val[1];
1062 break;
1063 }
1064 }
1065 if ( $epat ) {
1066 // find end (and detect any nested elements)
1067 $level = 0;
1068 $offset = $start + 1;
1069 $found = false;
1070 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE, $offset ) ) {
1071 if ( array_key_exists( 2, $endMatches ) ) {
1072 // found end
1073 if ( $level == 0 ) {
1074 $len = strlen( $endMatches[2][0] );
1075 $off = $endMatches[2][1];
1076 $this->splitAndAdd( $otherExt, $count,
1077 substr( $text, $start, $off + $len - $start ) );
1078 $start = $off + $len;
1079 $found = true;
1080 break;
1081 } else {
1082 // end of nested element
1083 $level -= 1;
1084 }
1085 } else {
1086 // nested
1087 $level += 1;
1088 }
1089 $offset = $endMatches[0][1] + strlen( $endMatches[0][0] );
1090 }
1091 if ( ! $found ) {
1092 // couldn't find appropriate closing tag, skip
1093 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1094 $start += strlen( $matches[0][0] );
1095 }
1096 continue;
1097 }
1098 }
1099 // else: add as text extract
1100 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1101 break;
1102 }
1103
1104 $all = $textExt + $otherExt; // these have disjunct key sets
1105
1106 wfProfileOut( "$fname-split" );
1107
1108 // prepare regexps
1109 foreach ( $terms as $index => $term ) {
1110 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1111 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1112 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1113 } else {
1114 $terms[$index] = $term;
1115 }
1116 }
1117 $anyterm = implode( '|', $terms );
1118 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1119
1120 // @todo FIXME: A hack to scale contextchars, a correct solution
1121 // would be to have contextchars actually be char and not byte
1122 // length, and do proper utf-8 substrings and lengths everywhere,
1123 // but PHP is making that very hard and unclean to implement :(
1124 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1125 $contextchars = intval( $contextchars * $scale );
1126
1127 $patPre = "(^|$wgSearchHighlightBoundaries)";
1128 $patPost = "($wgSearchHighlightBoundaries|$)";
1129
1130 $pat1 = "/(" . $phrase . ")/ui";
1131 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1132
1133 wfProfileIn( "$fname-extract" );
1134
1135 $left = $contextlines;
1136
1137 $snippets = array();
1138 $offsets = array();
1139
1140 // show beginning only if it contains all words
1141 $first = 0;
1142 $firstText = '';
1143 foreach ( $textExt as $index => $line ) {
1144 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1145 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1146 $first = $index;
1147 break;
1148 }
1149 }
1150 if ( $firstText ) {
1151 $succ = true;
1152 // check if first text contains all terms
1153 foreach ( $terms as $term ) {
1154 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1155 $succ = false;
1156 break;
1157 }
1158 }
1159 if ( $succ ) {
1160 $snippets[$first] = $firstText;
1161 $offsets[$first] = 0;
1162 }
1163 }
1164 if ( ! $snippets ) {
1165 // match whole query on text
1166 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1167 // match whole query on templates/tables/images
1168 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1169 // match any words on text
1170 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1171 // match any words on templates/tables/images
1172 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1173
1174 ksort( $snippets );
1175 }
1176
1177 // add extra chars to each snippet to make snippets constant size
1178 $extended = array();
1179 if ( count( $snippets ) == 0 ) {
1180 // couldn't find the target words, just show beginning of article
1181 if ( array_key_exists( $first, $all ) ) {
1182 $targetchars = $contextchars * $contextlines;
1183 $snippets[$first] = '';
1184 $offsets[$first] = 0;
1185 }
1186 } else {
1187 // if begin of the article contains the whole phrase, show only that !!
1188 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1189 && $offsets[$first] < $contextchars * 2 ) {
1190 $snippets = array( $first => $snippets[$first] );
1191 }
1192
1193 // calc by how much to extend existing snippets
1194 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1195 }
1196
1197 foreach ( $snippets as $index => $line ) {
1198 $extended[$index] = $line;
1199 $len = strlen( $line );
1200 if ( $len < $targetchars - 20 ) {
1201 // complete this line
1202 if ( $len < strlen( $all[$index] ) ) {
1203 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] + $targetchars, $offsets[$index] );
1204 $len = strlen( $extended[$index] );
1205 }
1206
1207 // add more lines
1208 $add = $index + 1;
1209 while ( $len < $targetchars - 20
1210 && array_key_exists( $add, $all )
1211 && !array_key_exists( $add, $snippets ) ) {
1212 $offsets[$add] = 0;
1213 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1214 $extended[$add] = $tt;
1215 $len += strlen( $tt );
1216 $add++;
1217 }
1218 }
1219 }
1220
1221 // $snippets = array_map( 'htmlspecialchars', $extended );
1222 $snippets = $extended;
1223 $last = - 1;
1224 $extract = '';
1225 foreach ( $snippets as $index => $line ) {
1226 if ( $last == - 1 ) {
1227 $extract .= $line; // first line
1228 } elseif ( $last + 1 == $index && $offsets[$last] + strlen( $snippets[$last] ) >= strlen( $all[$last] ) ) {
1229 $extract .= " " . $line; // continous lines
1230 } else {
1231 $extract .= '<b> ... </b>' . $line;
1232 }
1233
1234 $last = $index;
1235 }
1236 if ( $extract ) {
1237 $extract .= '<b> ... </b>';
1238 }
1239
1240 $processed = array();
1241 foreach ( $terms as $term ) {
1242 if ( ! isset( $processed[$term] ) ) {
1243 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1244 $extract = preg_replace( $pat3,
1245 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1246 $processed[$term] = true;
1247 }
1248 }
1249
1250 wfProfileOut( "$fname-extract" );
1251
1252 return $extract;
1253 }
1254
1255 /**
1256 * Split text into lines and add it to extracts array
1257 *
1258 * @param array $extracts index -> $line
1259 * @param $count Integer
1260 * @param $text String
1261 */
1262 function splitAndAdd( &$extracts, &$count, $text ) {
1263 $split = explode( "\n", $this->mCleanWikitext ? $this->removeWiki( $text ) : $text );
1264 foreach ( $split as $line ) {
1265 $tt = trim( $line );
1266 if ( $tt ) {
1267 $extracts[$count++] = $tt;
1268 }
1269 }
1270 }
1271
1272 /**
1273 * Do manual case conversion for non-ascii chars
1274 *
1275 * @param $matches Array
1276 * @return string
1277 */
1278 function caseCallback( $matches ) {
1279 global $wgContLang;
1280 if ( strlen( $matches[0] ) > 1 ) {
1281 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1282 } else {
1283 return $matches[0];
1284 }
1285 }
1286
1287 /**
1288 * Extract part of the text from start to end, but by
1289 * not chopping up words
1290 * @param $text String
1291 * @param $start Integer
1292 * @param $end Integer
1293 * @param $posStart Integer: (out) actual start position
1294 * @param $posEnd Integer: (out) actual end position
1295 * @return String
1296 */
1297 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1298 if ( $start != 0 ) {
1299 $start = $this->position( $text, $start, 1 );
1300 }
1301 if ( $end >= strlen( $text ) ) {
1302 $end = strlen( $text );
1303 } else {
1304 $end = $this->position( $text, $end );
1305 }
1306
1307 if ( !is_null( $posStart ) ) {
1308 $posStart = $start;
1309 }
1310 if ( !is_null( $posEnd ) ) {
1311 $posEnd = $end;
1312 }
1313
1314 if ( $end > $start ) {
1315 return substr( $text, $start, $end - $start );
1316 } else {
1317 return '';
1318 }
1319 }
1320
1321 /**
1322 * Find a nonletter near a point (index) in the text
1323 *
1324 * @param $text String
1325 * @param $point Integer
1326 * @param $offset Integer: offset to found index
1327 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1328 */
1329 function position( $text, $point, $offset = 0 ) {
1330 $tolerance = 10;
1331 $s = max( 0, $point - $tolerance );
1332 $l = min( strlen( $text ), $point + $tolerance ) - $s;
1333 $m = array();
1334 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE ) ) {
1335 return $m[0][1] + $s + $offset;
1336 } else {
1337 // check if point is on a valid first UTF8 char
1338 $char = ord( $text[$point] );
1339 while ( $char >= 0x80 && $char < 0xc0 ) {
1340 // skip trailing bytes
1341 $point++;
1342 if ( $point >= strlen( $text ) ) {
1343 return strlen( $text );
1344 }
1345 $char = ord( $text[$point] );
1346 }
1347 return $point;
1348
1349 }
1350 }
1351
1352 /**
1353 * Search extracts for a pattern, and return snippets
1354 *
1355 * @param string $pattern regexp for matching lines
1356 * @param array $extracts extracts to search
1357 * @param $linesleft Integer: number of extracts to make
1358 * @param $contextchars Integer: length of snippet
1359 * @param array $out map for highlighted snippets
1360 * @param array $offsets map of starting points of snippets
1361 * @protected
1362 */
1363 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1364 if ( $linesleft == 0 ) {
1365 return; // nothing to do
1366 }
1367 foreach ( $extracts as $index => $line ) {
1368 if ( array_key_exists( $index, $out ) ) {
1369 continue; // this line already highlighted
1370 }
1371
1372 $m = array();
1373 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) ) {
1374 continue;
1375 }
1376
1377 $offset = $m[0][1];
1378 $len = strlen( $m[0][0] );
1379 if ( $offset + $len < $contextchars ) {
1380 $begin = 0;
1381 } elseif ( $len > $contextchars ) {
1382 $begin = $offset;
1383 } else {
1384 $begin = $offset + intval( ( $len - $contextchars ) / 2 );
1385 }
1386
1387 $end = $begin + $contextchars;
1388
1389 $posBegin = $begin;
1390 // basic snippet from this line
1391 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1392 $offsets[$index] = $posBegin;
1393 $linesleft--;
1394 if ( $linesleft == 0 ) {
1395 return;
1396 }
1397 }
1398 }
1399
1400 /**
1401 * Basic wikitext removal
1402 * @protected
1403 * @return mixed
1404 */
1405 function removeWiki( $text ) {
1406 $fname = __METHOD__;
1407 wfProfileIn( $fname );
1408
1409 // $text = preg_replace( "/'{2,5}/", "", $text );
1410 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1411 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1412 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1413 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1414 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1415 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1416 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1417 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1418 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1419 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1420 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1421 $text = preg_replace( "/'''''/", "", $text );
1422 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1423 $text = preg_replace( "/''/", "", $text );
1424
1425 wfProfileOut( $fname );
1426 return $text;
1427 }
1428
1429 /**
1430 * callback to replace [[target|caption]] kind of links, if
1431 * the target is category or image, leave it
1432 *
1433 * @param $matches Array
1434 */
1435 function linkReplace( $matches ) {
1436 $colon = strpos( $matches[1], ':' );
1437 if ( $colon === false ) {
1438 return $matches[2]; // replace with caption
1439 }
1440 global $wgContLang;
1441 $ns = substr( $matches[1], 0, $colon );
1442 $index = $wgContLang->getNsIndex( $ns );
1443 if ( $index !== false && ( $index == NS_FILE || $index == NS_CATEGORY ) ) {
1444 return $matches[0]; // return the whole thing
1445 } else {
1446 return $matches[2];
1447 }
1448 }
1449
1450 /**
1451 * Simple & fast snippet extraction, but gives completely unrelevant
1452 * snippets
1453 *
1454 * @param $text String
1455 * @param $terms Array
1456 * @param $contextlines Integer
1457 * @param $contextchars Integer
1458 * @return String
1459 */
1460 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1461 global $wgContLang;
1462 $fname = __METHOD__;
1463
1464 $lines = explode( "\n", $text );
1465
1466 $terms = implode( '|', $terms );
1467 $max = intval( $contextchars ) + 1;
1468 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1469
1470 $lineno = 0;
1471
1472 $extract = "";
1473 wfProfileIn( "$fname-extract" );
1474 foreach ( $lines as $line ) {
1475 if ( 0 == $contextlines ) {
1476 break;
1477 }
1478 ++$lineno;
1479 $m = array();
1480 if ( ! preg_match( $pat1, $line, $m ) ) {
1481 continue;
1482 }
1483 --$contextlines;
1484 // truncate function changes ... to relevant i18n message.
1485 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1486
1487 if ( count( $m ) < 3 ) {
1488 $post = '';
1489 } else {
1490 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1491 }
1492
1493 $found = $m[2];
1494
1495 $line = htmlspecialchars( $pre . $found . $post );
1496 $pat2 = '/(' . $terms . ")/i";
1497 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1498
1499 $extract .= "${line}\n";
1500 }
1501 wfProfileOut( "$fname-extract" );
1502
1503 return $extract;
1504 }
1505
1506 }
1507
1508 /**
1509 * Dummy class to be used when non-supported Database engine is present.
1510 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1511 * such as a LIKE search through titles.
1512 * @ingroup Search
1513 */
1514 class SearchEngineDummy extends SearchEngine {
1515 // no-op
1516 }