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