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