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