45d0044d7eb7060521e893084f2954b82920629f
[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 /**
444 * Load up the appropriate search engine class for the currently
445 * active database backend, and return a configured instance.
446 *
447 * @param String $type Type of search backend, if not the default
448 * @return SearchEngine
449 */
450 public static function create( $type = null ) {
451 global $wgSearchType;
452 $dbr = null;
453
454 $alternatives = self::getSearchTypes();
455
456 if ( $type && in_array( $type, $alternatives ) ) {
457 $class = $type;
458 } elseif ( $wgSearchType !== null ) {
459 $class = $wgSearchType;
460 } else {
461 $dbr = wfGetDB( DB_SLAVE );
462 $class = $dbr->getSearchEngine();
463 }
464
465 $search = new $class( $dbr );
466 return $search;
467 }
468
469 /**
470 * Return the search engines we support. If only $wgSearchType
471 * is set, it'll be an array of just that one item.
472 *
473 * @return array
474 */
475 public static function getSearchTypes() {
476 global $wgSearchType, $wgSearchTypeAlternatives;
477
478 $alternatives = $wgSearchTypeAlternatives ?: array();
479 array_unshift( $alternatives, $wgSearchType );
480
481 return $alternatives;
482 }
483
484 /**
485 * Create or update the search index record for the given page.
486 * Title and text should be pre-processed.
487 * STUB
488 *
489 * @param $id Integer
490 * @param $title String
491 * @param $text String
492 */
493 function update( $id, $title, $text ) {
494 // no-op
495 }
496
497 /**
498 * Update a search index record's title only.
499 * Title should be pre-processed.
500 * STUB
501 *
502 * @param $id Integer
503 * @param $title String
504 */
505 function updateTitle( $id, $title ) {
506 // no-op
507 }
508
509 /**
510 * Delete an indexed page
511 * Title should be pre-processed.
512 * STUB
513 *
514 * @param Integer $id Page id that was deleted
515 * @param String $title Title of page that was deleted
516 */
517 function delete( $id, $title ) {
518 // no-op
519 }
520
521 /**
522 * Get OpenSearch suggestion template
523 *
524 * @return String
525 */
526 public static function getOpenSearchTemplate() {
527 global $wgOpenSearchTemplate, $wgCanonicalServer;
528 if ( $wgOpenSearchTemplate ) {
529 return $wgOpenSearchTemplate;
530 } else {
531 $ns = implode( '|', SearchEngine::defaultNamespaces() );
532 if ( !$ns ) {
533 $ns = "0";
534 }
535 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
536 }
537 }
538
539 /**
540 * Get the raw text for updating the index from a content object
541 * Nicer search backends could possibly do something cooler than
542 * just returning raw text
543 *
544 * @todo This isn't ideal, we'd really like to have content-specific handling here
545 * @param Title $t Title we're indexing
546 * @param Content $c Content of the page to index
547 * @return string
548 */
549 public function getTextFromContent( Title $t, Content $c = null ) {
550 return $c ? $c->getTextForSearchIndex() : '';
551 }
552
553 /**
554 * If an implementation of SearchEngine handles all of its own text processing
555 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
556 * rather silly handling, it should return true here instead.
557 *
558 * @return bool
559 */
560 public function textAlreadyUpdatedForIndex() {
561 return false;
562 }
563 }
564
565 /**
566 * @ingroup Search
567 */
568 class SearchResultSet {
569 /**
570 * Fetch an array of regular expression fragments for matching
571 * the search terms as parsed by this engine in a text extract.
572 * STUB
573 *
574 * @return Array
575 */
576 function termMatches() {
577 return array();
578 }
579
580 function numRows() {
581 return 0;
582 }
583
584 /**
585 * Return true if results are included in this result set.
586 * STUB
587 *
588 * @return Boolean
589 */
590 function hasResults() {
591 return false;
592 }
593
594 /**
595 * Some search modes return a total hit count for the query
596 * in the entire article database. This may include pages
597 * in namespaces that would not be matched on the given
598 * settings.
599 *
600 * Return null if no total hits number is supported.
601 *
602 * @return Integer
603 */
604 function getTotalHits() {
605 return null;
606 }
607
608 /**
609 * Some search modes return a suggested alternate term if there are
610 * no exact hits. Returns true if there is one on this set.
611 *
612 * @return Boolean
613 */
614 function hasSuggestion() {
615 return false;
616 }
617
618 /**
619 * @return String: suggested query, null if none
620 */
621 function getSuggestionQuery() {
622 return null;
623 }
624
625 /**
626 * @return String: HTML highlighted suggested query, '' if none
627 */
628 function getSuggestionSnippet() {
629 return '';
630 }
631
632 /**
633 * Return information about how and from where the results were fetched,
634 * should be useful for diagnostics and debugging
635 *
636 * @return String
637 */
638 function getInfo() {
639 return null;
640 }
641
642 /**
643 * Return a result set of hits on other (multiple) wikis associated with this one
644 *
645 * @return SearchResultSet
646 */
647 function getInterwikiResults() {
648 return null;
649 }
650
651 /**
652 * Check if there are results on other wikis
653 *
654 * @return Boolean
655 */
656 function hasInterwikiResults() {
657 return $this->getInterwikiResults() != null;
658 }
659
660 /**
661 * Fetches next search result, or false.
662 * STUB
663 *
664 * @return SearchResult
665 */
666 function next() {
667 return false;
668 }
669
670 /**
671 * Frees the result set, if applicable.
672 */
673 function free() {
674 // ...
675 }
676
677 /**
678 * Did the search contain search syntax? If so, Special:Search won't offer
679 * the user a link to a create a page named by the search string because the
680 * name would contain the search syntax.
681 */
682 public function searchContainedSyntax() {
683 return false;
684 }
685 }
686
687 /**
688 * This class is used for different SQL-based search engines shipped with MediaWiki
689 */
690 class SqlSearchResultSet extends SearchResultSet {
691
692 protected $mResultSet;
693
694 function __construct( $resultSet, $terms ) {
695 $this->mResultSet = $resultSet;
696 $this->mTerms = $terms;
697 }
698
699 function termMatches() {
700 return $this->mTerms;
701 }
702
703 function numRows() {
704 if ( $this->mResultSet === false ) {
705 return false;
706 }
707
708 return $this->mResultSet->numRows();
709 }
710
711 function next() {
712 if ( $this->mResultSet === false ) {
713 return false;
714 }
715
716 $row = $this->mResultSet->fetchObject();
717 if ( $row === false ) {
718 return false;
719 }
720
721 return SearchResult::newFromRow( $row );
722 }
723
724 function free() {
725 if ( $this->mResultSet === false ) {
726 return false;
727 }
728
729 $this->mResultSet->free();
730 }
731 }
732
733 /**
734 * @ingroup Search
735 */
736 class SearchResultTooMany {
737 # # Some search engines may bail out if too many matches are found
738 }
739
740 /**
741 * @todo FIXME: This class is horribly factored. It would probably be better to
742 * have a useful base class to which you pass some standard information, then
743 * let the fancy self-highlighters extend that.
744 * @ingroup Search
745 */
746 class SearchResult {
747
748 /**
749 * @var Revision
750 */
751 protected $mRevision = null;
752
753 /**
754 * @var File
755 */
756 protected $mImage = null;
757
758 /**
759 * @var Title
760 */
761 protected $mTitle;
762
763 /**
764 * @var String
765 */
766 protected $mText;
767
768 /**
769 * Return a new SearchResult and initializes it with a title.
770 *
771 * @param $title Title
772 * @return SearchResult
773 */
774 public static function newFromTitle( $title ) {
775 $result = new self();
776 $result->initFromTitle( $title );
777 return $result;
778 }
779
780 /**
781 * Return a new SearchResult and initializes it with a row.
782 *
783 * @param $row object
784 * @return SearchResult
785 */
786 public static function newFromRow( $row ) {
787 $result = new self();
788 $result->initFromRow( $row );
789 return $result;
790 }
791
792 public function __construct( $row = null ) {
793 if ( !is_null( $row ) ) {
794 // Backwards compatibility with pre-1.17 callers
795 $this->initFromRow( $row );
796 }
797 }
798
799 /**
800 * Initialize from a database row. Makes a Title and passes that to
801 * initFromTitle.
802 *
803 * @param $row object
804 */
805 protected function initFromRow( $row ) {
806 $this->initFromTitle( Title::makeTitle( $row->page_namespace, $row->page_title ) );
807 }
808
809 /**
810 * Initialize from a Title and if possible initializes a corresponding
811 * Revision and File.
812 *
813 * @param $title Title
814 */
815 protected function initFromTitle( $title ) {
816 $this->mTitle = $title;
817 if ( !is_null( $this->mTitle ) ) {
818 $id = false;
819 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
820 $this->mRevision = Revision::newFromTitle(
821 $this->mTitle, $id, Revision::READ_NORMAL );
822 if ( $this->mTitle->getNamespace() === NS_FILE ) {
823 $this->mImage = wfFindFile( $this->mTitle );
824 }
825 }
826 }
827
828 /**
829 * Check if this is result points to an invalid title
830 *
831 * @return Boolean
832 */
833 function isBrokenTitle() {
834 return is_null( $this->mTitle );
835 }
836
837 /**
838 * Check if target page is missing, happens when index is out of date
839 *
840 * @return Boolean
841 */
842 function isMissingRevision() {
843 return !$this->mRevision && !$this->mImage;
844 }
845
846 /**
847 * @return Title
848 */
849 function getTitle() {
850 return $this->mTitle;
851 }
852
853 /**
854 * Get the file for this page, if one exists
855 * @return File|null
856 */
857 function getFile() {
858 return $this->mImage;
859 }
860
861 /**
862 * @return float|null if not supported
863 */
864 function getScore() {
865 return null;
866 }
867
868 /**
869 * Lazy initialization of article text from DB
870 */
871 protected function initText() {
872 if ( !isset( $this->mText ) ) {
873 if ( $this->mRevision != null ) {
874 $this->mText = SearchEngine::create()
875 ->getTextFromContent( $this->mTitle, $this->mRevision->getContent() );
876 } else { // TODO: can we fetch raw wikitext for commons images?
877 $this->mText = '';
878 }
879 }
880 }
881
882 /**
883 * @param array $terms terms to highlight
884 * @return String: highlighted text snippet, null (and not '') if not supported
885 */
886 function getTextSnippet( $terms ) {
887 global $wgAdvancedSearchHighlighting;
888 $this->initText();
889
890 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
891 list( $contextlines, $contextchars ) = SearchEngine::userHighlightPrefs();
892 $h = new SearchHighlighter();
893 if ( $wgAdvancedSearchHighlighting ) {
894 return $h->highlightText( $this->mText, $terms, $contextlines, $contextchars );
895 } else {
896 return $h->highlightSimple( $this->mText, $terms, $contextlines, $contextchars );
897 }
898 }
899
900 /**
901 * @return String: highlighted title, '' if not supported
902 */
903 function getTitleSnippet() {
904 return '';
905 }
906
907 /**
908 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
909 */
910 function getRedirectSnippet() {
911 return '';
912 }
913
914 /**
915 * @return Title object for the redirect to this page, null if none or not supported
916 */
917 function getRedirectTitle() {
918 return null;
919 }
920
921 /**
922 * @return string highlighted relevant section name, null if none or not supported
923 */
924 function getSectionSnippet() {
925 return '';
926 }
927
928 /**
929 * @return Title object (pagename+fragment) for the section, null if none or not supported
930 */
931 function getSectionTitle() {
932 return null;
933 }
934
935 /**
936 * @return String: timestamp
937 */
938 function getTimestamp() {
939 if ( $this->mRevision ) {
940 return $this->mRevision->getTimestamp();
941 } elseif ( $this->mImage ) {
942 return $this->mImage->getTimestamp();
943 }
944 return '';
945 }
946
947 /**
948 * @return Integer: number of words
949 */
950 function getWordCount() {
951 $this->initText();
952 return str_word_count( $this->mText );
953 }
954
955 /**
956 * @return Integer: size in bytes
957 */
958 function getByteSize() {
959 $this->initText();
960 return strlen( $this->mText );
961 }
962
963 /**
964 * @return Boolean if hit has related articles
965 */
966 function hasRelated() {
967 return false;
968 }
969
970 /**
971 * @return String: interwiki prefix of the title (return iw even if title is broken)
972 */
973 function getInterwikiPrefix() {
974 return '';
975 }
976
977 /**
978 * @return string interwiki namespace of the title (since we likely can't resolve it locally)
979 */
980 function getInterwikiNamespaceText() {
981 return '';
982 }
983
984 /**
985 * Did this match file contents (eg: PDF/DJVU)?
986 */
987 function isFileMatch() {
988 return false;
989 }
990 }
991
992 /**
993 * A SearchResultSet wrapper for SearchEngine::getNearMatch
994 */
995 class SearchNearMatchResultSet extends SearchResultSet {
996 private $fetched = false;
997
998 /**
999 * @param $match mixed Title if matched, else null
1000 */
1001 public function __construct( $match ) {
1002 $this->result = $match;
1003 }
1004
1005 public function hasResult() {
1006 return (bool)$this->result;
1007 }
1008
1009 public function numRows() {
1010 return $this->hasResults() ? 1 : 0;
1011 }
1012
1013 public function next() {
1014 if ( $this->fetched || !$this->result ) {
1015 return false;
1016 }
1017 $this->fetched = true;
1018 return SearchResult::newFromTitle( $this->result );
1019 }
1020 }
1021
1022 /**
1023 * Highlight bits of wikitext
1024 *
1025 * @ingroup Search
1026 */
1027 class SearchHighlighter {
1028 var $mCleanWikitext = true;
1029
1030 function __construct( $cleanupWikitext = true ) {
1031 $this->mCleanWikitext = $cleanupWikitext;
1032 }
1033
1034 /**
1035 * Default implementation of wikitext highlighting
1036 *
1037 * @param $text String
1038 * @param array $terms terms to highlight (unescaped)
1039 * @param $contextlines Integer
1040 * @param $contextchars Integer
1041 * @return String
1042 */
1043 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
1044 global $wgContLang;
1045 global $wgSearchHighlightBoundaries;
1046 $fname = __METHOD__;
1047
1048 if ( $text == '' ) {
1049 return '';
1050 }
1051
1052 // spli text into text + templates/links/tables
1053 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
1054 // first capture group is for detecting nested templates/links/tables/references
1055 $endPatterns = array(
1056 1 => '/(\{\{)|(\}\})/', // template
1057 2 => '/(\[\[)|(\]\])/', // image
1058 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
1059
1060 // @todo FIXME: This should prolly be a hook or something
1061 if ( function_exists( 'wfCite' ) ) {
1062 $spat .= '|(<ref>)'; // references via cite extension
1063 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
1064 }
1065 $spat .= '/';
1066 $textExt = array(); // text extracts
1067 $otherExt = array(); // other extracts
1068 wfProfileIn( "$fname-split" );
1069 $start = 0;
1070 $textLen = strlen( $text );
1071 $count = 0; // sequence number to maintain ordering
1072 while ( $start < $textLen ) {
1073 // find start of template/image/table
1074 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE, $start ) ) {
1075 $epat = '';
1076 foreach ( $matches as $key => $val ) {
1077 if ( $key > 0 && $val[1] != - 1 ) {
1078 if ( $key == 2 ) {
1079 // see if this is an image link
1080 $ns = substr( $val[0], 2, - 1 );
1081 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE ) {
1082 break;
1083 }
1084
1085 }
1086 $epat = $endPatterns[$key];
1087 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1088 $start = $val[1];
1089 break;
1090 }
1091 }
1092 if ( $epat ) {
1093 // find end (and detect any nested elements)
1094 $level = 0;
1095 $offset = $start + 1;
1096 $found = false;
1097 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE, $offset ) ) {
1098 if ( array_key_exists( 2, $endMatches ) ) {
1099 // found end
1100 if ( $level == 0 ) {
1101 $len = strlen( $endMatches[2][0] );
1102 $off = $endMatches[2][1];
1103 $this->splitAndAdd( $otherExt, $count,
1104 substr( $text, $start, $off + $len - $start ) );
1105 $start = $off + $len;
1106 $found = true;
1107 break;
1108 } else {
1109 // end of nested element
1110 $level -= 1;
1111 }
1112 } else {
1113 // nested
1114 $level += 1;
1115 }
1116 $offset = $endMatches[0][1] + strlen( $endMatches[0][0] );
1117 }
1118 if ( ! $found ) {
1119 // couldn't find appropriate closing tag, skip
1120 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1121 $start += strlen( $matches[0][0] );
1122 }
1123 continue;
1124 }
1125 }
1126 // else: add as text extract
1127 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1128 break;
1129 }
1130
1131 $all = $textExt + $otherExt; // these have disjunct key sets
1132
1133 wfProfileOut( "$fname-split" );
1134
1135 // prepare regexps
1136 foreach ( $terms as $index => $term ) {
1137 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1138 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1139 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1140 } else {
1141 $terms[$index] = $term;
1142 }
1143 }
1144 $anyterm = implode( '|', $terms );
1145 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1146
1147 // @todo FIXME: A hack to scale contextchars, a correct solution
1148 // would be to have contextchars actually be char and not byte
1149 // length, and do proper utf-8 substrings and lengths everywhere,
1150 // but PHP is making that very hard and unclean to implement :(
1151 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1152 $contextchars = intval( $contextchars * $scale );
1153
1154 $patPre = "(^|$wgSearchHighlightBoundaries)";
1155 $patPost = "($wgSearchHighlightBoundaries|$)";
1156
1157 $pat1 = "/(" . $phrase . ")/ui";
1158 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1159
1160 wfProfileIn( "$fname-extract" );
1161
1162 $left = $contextlines;
1163
1164 $snippets = array();
1165 $offsets = array();
1166
1167 // show beginning only if it contains all words
1168 $first = 0;
1169 $firstText = '';
1170 foreach ( $textExt as $index => $line ) {
1171 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1172 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1173 $first = $index;
1174 break;
1175 }
1176 }
1177 if ( $firstText ) {
1178 $succ = true;
1179 // check if first text contains all terms
1180 foreach ( $terms as $term ) {
1181 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1182 $succ = false;
1183 break;
1184 }
1185 }
1186 if ( $succ ) {
1187 $snippets[$first] = $firstText;
1188 $offsets[$first] = 0;
1189 }
1190 }
1191 if ( ! $snippets ) {
1192 // match whole query on text
1193 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1194 // match whole query on templates/tables/images
1195 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1196 // match any words on text
1197 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1198 // match any words on templates/tables/images
1199 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1200
1201 ksort( $snippets );
1202 }
1203
1204 // add extra chars to each snippet to make snippets constant size
1205 $extended = array();
1206 if ( count( $snippets ) == 0 ) {
1207 // couldn't find the target words, just show beginning of article
1208 if ( array_key_exists( $first, $all ) ) {
1209 $targetchars = $contextchars * $contextlines;
1210 $snippets[$first] = '';
1211 $offsets[$first] = 0;
1212 }
1213 } else {
1214 // if begin of the article contains the whole phrase, show only that !!
1215 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1216 && $offsets[$first] < $contextchars * 2 ) {
1217 $snippets = array( $first => $snippets[$first] );
1218 }
1219
1220 // calc by how much to extend existing snippets
1221 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1222 }
1223
1224 foreach ( $snippets as $index => $line ) {
1225 $extended[$index] = $line;
1226 $len = strlen( $line );
1227 if ( $len < $targetchars - 20 ) {
1228 // complete this line
1229 if ( $len < strlen( $all[$index] ) ) {
1230 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] + $targetchars, $offsets[$index] );
1231 $len = strlen( $extended[$index] );
1232 }
1233
1234 // add more lines
1235 $add = $index + 1;
1236 while ( $len < $targetchars - 20
1237 && array_key_exists( $add, $all )
1238 && !array_key_exists( $add, $snippets ) ) {
1239 $offsets[$add] = 0;
1240 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1241 $extended[$add] = $tt;
1242 $len += strlen( $tt );
1243 $add++;
1244 }
1245 }
1246 }
1247
1248 // $snippets = array_map( 'htmlspecialchars', $extended );
1249 $snippets = $extended;
1250 $last = - 1;
1251 $extract = '';
1252 foreach ( $snippets as $index => $line ) {
1253 if ( $last == - 1 ) {
1254 $extract .= $line; // first line
1255 } elseif ( $last + 1 == $index && $offsets[$last] + strlen( $snippets[$last] ) >= strlen( $all[$last] ) ) {
1256 $extract .= " " . $line; // continous lines
1257 } else {
1258 $extract .= '<b> ... </b>' . $line;
1259 }
1260
1261 $last = $index;
1262 }
1263 if ( $extract ) {
1264 $extract .= '<b> ... </b>';
1265 }
1266
1267 $processed = array();
1268 foreach ( $terms as $term ) {
1269 if ( ! isset( $processed[$term] ) ) {
1270 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1271 $extract = preg_replace( $pat3,
1272 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1273 $processed[$term] = true;
1274 }
1275 }
1276
1277 wfProfileOut( "$fname-extract" );
1278
1279 return $extract;
1280 }
1281
1282 /**
1283 * Split text into lines and add it to extracts array
1284 *
1285 * @param array $extracts index -> $line
1286 * @param $count Integer
1287 * @param $text String
1288 */
1289 function splitAndAdd( &$extracts, &$count, $text ) {
1290 $split = explode( "\n", $this->mCleanWikitext ? $this->removeWiki( $text ) : $text );
1291 foreach ( $split as $line ) {
1292 $tt = trim( $line );
1293 if ( $tt ) {
1294 $extracts[$count++] = $tt;
1295 }
1296 }
1297 }
1298
1299 /**
1300 * Do manual case conversion for non-ascii chars
1301 *
1302 * @param $matches Array
1303 * @return string
1304 */
1305 function caseCallback( $matches ) {
1306 global $wgContLang;
1307 if ( strlen( $matches[0] ) > 1 ) {
1308 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1309 } else {
1310 return $matches[0];
1311 }
1312 }
1313
1314 /**
1315 * Extract part of the text from start to end, but by
1316 * not chopping up words
1317 * @param $text String
1318 * @param $start Integer
1319 * @param $end Integer
1320 * @param $posStart Integer: (out) actual start position
1321 * @param $posEnd Integer: (out) actual end position
1322 * @return String
1323 */
1324 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1325 if ( $start != 0 ) {
1326 $start = $this->position( $text, $start, 1 );
1327 }
1328 if ( $end >= strlen( $text ) ) {
1329 $end = strlen( $text );
1330 } else {
1331 $end = $this->position( $text, $end );
1332 }
1333
1334 if ( !is_null( $posStart ) ) {
1335 $posStart = $start;
1336 }
1337 if ( !is_null( $posEnd ) ) {
1338 $posEnd = $end;
1339 }
1340
1341 if ( $end > $start ) {
1342 return substr( $text, $start, $end - $start );
1343 } else {
1344 return '';
1345 }
1346 }
1347
1348 /**
1349 * Find a nonletter near a point (index) in the text
1350 *
1351 * @param $text String
1352 * @param $point Integer
1353 * @param $offset Integer: offset to found index
1354 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1355 */
1356 function position( $text, $point, $offset = 0 ) {
1357 $tolerance = 10;
1358 $s = max( 0, $point - $tolerance );
1359 $l = min( strlen( $text ), $point + $tolerance ) - $s;
1360 $m = array();
1361 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE ) ) {
1362 return $m[0][1] + $s + $offset;
1363 } else {
1364 // check if point is on a valid first UTF8 char
1365 $char = ord( $text[$point] );
1366 while ( $char >= 0x80 && $char < 0xc0 ) {
1367 // skip trailing bytes
1368 $point++;
1369 if ( $point >= strlen( $text ) ) {
1370 return strlen( $text );
1371 }
1372 $char = ord( $text[$point] );
1373 }
1374 return $point;
1375
1376 }
1377 }
1378
1379 /**
1380 * Search extracts for a pattern, and return snippets
1381 *
1382 * @param string $pattern regexp for matching lines
1383 * @param array $extracts extracts to search
1384 * @param $linesleft Integer: number of extracts to make
1385 * @param $contextchars Integer: length of snippet
1386 * @param array $out map for highlighted snippets
1387 * @param array $offsets map of starting points of snippets
1388 * @protected
1389 */
1390 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1391 if ( $linesleft == 0 ) {
1392 return; // nothing to do
1393 }
1394 foreach ( $extracts as $index => $line ) {
1395 if ( array_key_exists( $index, $out ) ) {
1396 continue; // this line already highlighted
1397 }
1398
1399 $m = array();
1400 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) ) {
1401 continue;
1402 }
1403
1404 $offset = $m[0][1];
1405 $len = strlen( $m[0][0] );
1406 if ( $offset + $len < $contextchars ) {
1407 $begin = 0;
1408 } elseif ( $len > $contextchars ) {
1409 $begin = $offset;
1410 } else {
1411 $begin = $offset + intval( ( $len - $contextchars ) / 2 );
1412 }
1413
1414 $end = $begin + $contextchars;
1415
1416 $posBegin = $begin;
1417 // basic snippet from this line
1418 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1419 $offsets[$index] = $posBegin;
1420 $linesleft--;
1421 if ( $linesleft == 0 ) {
1422 return;
1423 }
1424 }
1425 }
1426
1427 /**
1428 * Basic wikitext removal
1429 * @protected
1430 * @return mixed
1431 */
1432 function removeWiki( $text ) {
1433 $fname = __METHOD__;
1434 wfProfileIn( $fname );
1435
1436 // $text = preg_replace( "/'{2,5}/", "", $text );
1437 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1438 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1439 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1440 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1441 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1442 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1443 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1444 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1445 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1446 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1447 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1448 $text = preg_replace( "/'''''/", "", $text );
1449 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1450 $text = preg_replace( "/''/", "", $text );
1451
1452 wfProfileOut( $fname );
1453 return $text;
1454 }
1455
1456 /**
1457 * callback to replace [[target|caption]] kind of links, if
1458 * the target is category or image, leave it
1459 *
1460 * @param $matches Array
1461 */
1462 function linkReplace( $matches ) {
1463 $colon = strpos( $matches[1], ':' );
1464 if ( $colon === false ) {
1465 return $matches[2]; // replace with caption
1466 }
1467 global $wgContLang;
1468 $ns = substr( $matches[1], 0, $colon );
1469 $index = $wgContLang->getNsIndex( $ns );
1470 if ( $index !== false && ( $index == NS_FILE || $index == NS_CATEGORY ) ) {
1471 return $matches[0]; // return the whole thing
1472 } else {
1473 return $matches[2];
1474 }
1475 }
1476
1477 /**
1478 * Simple & fast snippet extraction, but gives completely unrelevant
1479 * snippets
1480 *
1481 * @param $text String
1482 * @param $terms Array
1483 * @param $contextlines Integer
1484 * @param $contextchars Integer
1485 * @return String
1486 */
1487 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1488 global $wgContLang;
1489 $fname = __METHOD__;
1490
1491 $lines = explode( "\n", $text );
1492
1493 $terms = implode( '|', $terms );
1494 $max = intval( $contextchars ) + 1;
1495 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1496
1497 $lineno = 0;
1498
1499 $extract = "";
1500 wfProfileIn( "$fname-extract" );
1501 foreach ( $lines as $line ) {
1502 if ( 0 == $contextlines ) {
1503 break;
1504 }
1505 ++$lineno;
1506 $m = array();
1507 if ( ! preg_match( $pat1, $line, $m ) ) {
1508 continue;
1509 }
1510 --$contextlines;
1511 // truncate function changes ... to relevant i18n message.
1512 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1513
1514 if ( count( $m ) < 3 ) {
1515 $post = '';
1516 } else {
1517 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1518 }
1519
1520 $found = $m[2];
1521
1522 $line = htmlspecialchars( $pre . $found . $post );
1523 $pat2 = '/(' . $terms . ")/i";
1524 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1525
1526 $extract .= "${line}\n";
1527 }
1528 wfProfileOut( "$fname-extract" );
1529
1530 return $extract;
1531 }
1532
1533 }
1534
1535 /**
1536 * Dummy class to be used when non-supported Database engine is present.
1537 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1538 * such as a LIKE search through titles.
1539 * @ingroup Search
1540 */
1541 class SearchEngineDummy extends SearchEngine {
1542 // no-op
1543 }