Fixed spacing in db/debug/diff/externalstore/objectcache folder
[mediawiki.git] / includes / search / SearchEngine.php
blobde9e99cdf99ca72a14c30f91f2eaf5e4ebd964b3
1 <?php
2 /**
3 * Basic search engine
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.
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.
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
20 * @file
21 * @ingroup Search
24 /**
25 * @defgroup Search Search
28 /**
29 * Contain a class for special pages
30 * @ingroup Search
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;
40 /// Feature values
41 protected $features = array();
43 /**
44 * @var DatabaseBase
46 protected $db;
48 function __construct( $db = null ) {
49 if ( $db ) {
50 $this->db = $db;
51 } else {
52 $this->db = wfGetDB( DB_SLAVE );
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
61 * @param string $term raw search term
62 * @return SearchResultSet
64 function searchText( $term ) {
65 return null;
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
73 * @param string $term raw search term
74 * @return SearchResultSet
76 function searchTitle( $term ) {
77 return null;
80 /**
81 * If this search backend can list/unlist redirects
82 * @deprecated since 1.18 Call supports( 'list-redirects' );
83 * @return bool
85 function acceptListRedirects() {
86 wfDeprecated( __METHOD__, '1.18' );
87 return $this->supports( 'list-redirects' );
90 /**
91 * @since 1.18
92 * @param $feature String
93 * @return Boolean
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;
106 * Way to pass custom data for engines
107 * @since 1.18
108 * @param $feature String
109 * @param $data Mixed
110 * @return bool
112 public function setFeatureData( $feature, $data ) {
113 $this->features[$feature] = $data;
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).
121 * @param string $string String to process
122 * @return string
124 public function normalizeText( $string ) {
125 global $wgContLang;
127 // Some languages such as Chinese require word segmentation
128 return $wgContLang->segmentByWord( $string );
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
135 function transformSearchTerm( $term ) {
136 return $term;
140 * If an exact title match can be found, or a very slightly close match,
141 * return the title. If no match, returns NULL.
143 * @param $searchterm String
144 * @return Title
146 public static function getNearMatch( $searchterm ) {
147 $title = self::getNearMatchInternal( $searchterm );
149 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
150 return $title;
154 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
155 * SearchResultSet.
157 * @param $searchterm string
158 * @return SearchResultSet
160 public static function getNearMatchResultSet( $searchterm ) {
161 return new SearchNearMatchResultSet( self::getNearMatch( $searchterm ) );
165 * Really find the title match.
166 * @return null|Title
168 private static function getNearMatchInternal( $searchterm ) {
169 global $wgContLang, $wgEnableSearchContributorsByIP;
171 $allSearchTerms = array( $searchterm );
173 if ( $wgContLang->hasVariants() ) {
174 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
177 $titleResult = null;
178 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
179 return $titleResult;
182 foreach ( $allSearchTerms as $term ) {
184 # Exact match? No need to look further.
185 $title = Title::newFromText( $term );
186 if ( is_null( $title ) ) {
187 return null;
190 # Try files if searching in the Media: namespace
191 if ( $title->getNamespace() == NS_MEDIA ) {
192 $title = Title::makeTitle( NS_FILE, $title->getText() );
195 if ( $title->isSpecialPage() || $title->isExternal() || $title->exists() ) {
196 return $title;
199 # See if it still otherwise has content is some sane sense
200 $page = WikiPage::factory( $title );
201 if ( $page->hasViewableContent() ) {
202 return $title;
205 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
206 return $title;
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;
215 # Now try capitalized string
216 $title = Title::newFromText( $wgContLang->ucwords( $term ) );
217 if ( $title && $title->exists() ) {
218 return $title;
221 # Now try all upper case
222 $title = Title::newFromText( $wgContLang->uc( $term ) );
223 if ( $title && $title->exists() ) {
224 return $title;
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;
233 // Give hooks a chance at better match variants
234 $title = null;
235 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
236 return $title;
240 $title = Title::newFromText( $searchterm );
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() );
250 # Entering a user goes to the user page whether it's there or not
251 if ( $title->getNamespace() == NS_USER ) {
252 return $title;
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;
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() ) );
271 # Quoted term? Try without the quotes...
272 $matches = array();
273 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
274 return SearchEngine::getNearMatch( $matches[1] );
277 return null;
280 public static function legalSearchChars() {
281 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
285 * Set the maximum number of results to return
286 * and how many to skip before returning the first.
288 * @param $limit Integer
289 * @param $offset Integer
291 function setLimitOffset( $limit, $offset = 0 ) {
292 $this->limit = intval( $limit );
293 $this->offset = intval( $offset );
297 * Set which namespaces the search should include.
298 * Give an array of namespace index numbers.
300 * @param $namespaces Array
302 function setNamespaces( $namespaces ) {
303 $this->namespaces = $namespaces;
307 * Parse some common prefixes: all (search everything)
308 * or namespace names
310 * @param $query String
311 * @return string
313 function replacePrefixes( $query ) {
314 global $wgContLang;
316 $parsed = $query;
317 if ( strpos( $query, ':' ) === false ) { // nothing to do
318 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
319 return $parsed;
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 );
334 if ( trim( $parsed ) == '' ) {
335 $parsed = $query; // prefix was the whole query
338 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
340 return $parsed;
344 * Make a list of searchable namespaces and their canonical names.
345 * @return Array
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;
356 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
357 return $arr;
361 * Extract default namespaces to search from the given user's
362 * settings, returning a list of index numbers.
364 * @param $user User
365 * @return Array
367 public static function userNamespaces( $user ) {
368 global $wgSearchEverythingOnlyLoggedIn;
370 $searchableNamespaces = SearchEngine::searchableNamespaces();
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 );
380 $arr = array();
381 foreach ( $searchableNamespaces as $ns => $name ) {
382 if ( $user->getOption( 'searchNs' . $ns ) ) {
383 $arr[] = $ns;
387 return $arr;
391 * Find snippet highlight settings for all users
393 * @return Array contextlines, contextchars
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 );
402 * An array of namespaces indexes to be searched by default
404 * @return Array
406 public static function defaultNamespaces() {
407 global $wgNamespacesToBeSearchedDefault;
409 return array_keys( $wgNamespacesToBeSearchedDefault, true );
413 * Get a list of namespace names useful for showing in tooltips
414 * and preferences
416 * @param $namespaces Array
417 * @return array
419 public static function namespacesAsText( $namespaces ) {
420 global $wgContLang;
422 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
423 foreach ( $formatted as $key => $ns ) {
424 if ( empty( $ns ) ) {
425 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
428 return $formatted;
432 * Return the help namespaces to be shown on Special:Search
434 * @return Array
436 public static function helpNamespaces() {
437 global $wgNamespacesToBeSearchedHelp;
439 return array_keys( $wgNamespacesToBeSearchedHelp, true );
443 * Return a 'cleaned up' search string
445 * @param $text String
446 * @return String
448 function filter( $text ) {
449 $lc = $this->legalSearchChars();
450 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
453 * Load up the appropriate search engine class for the currently
454 * active database backend, and return a configured instance.
456 * @return SearchEngine
458 public static function create() {
459 global $wgSearchType;
460 $dbr = null;
461 if ( $wgSearchType ) {
462 $class = $wgSearchType;
463 } else {
464 $dbr = wfGetDB( DB_SLAVE );
465 $class = $dbr->getSearchEngine();
467 $search = new $class( $dbr );
468 $search->setLimitOffset( 0, 0 );
469 return $search;
473 * Create or update the search index record for the given page.
474 * Title and text should be pre-processed.
475 * STUB
477 * @param $id Integer
478 * @param $title String
479 * @param $text String
481 function update( $id, $title, $text ) {
482 // no-op
486 * Update a search index record's title only.
487 * Title should be pre-processed.
488 * STUB
490 * @param $id Integer
491 * @param $title String
493 function updateTitle( $id, $title ) {
494 // no-op
498 * Get OpenSearch suggestion template
500 * @return String
502 public static function getOpenSearchTemplate() {
503 global $wgOpenSearchTemplate, $wgCanonicalServer;
504 if ( $wgOpenSearchTemplate ) {
505 return $wgOpenSearchTemplate;
506 } else {
507 $ns = implode( '|', SearchEngine::defaultNamespaces() );
508 if ( !$ns ) {
509 $ns = "0";
511 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
517 * @ingroup Search
519 class SearchResultSet {
521 * Fetch an array of regular expression fragments for matching
522 * the search terms as parsed by this engine in a text extract.
523 * STUB
525 * @return Array
527 function termMatches() {
528 return array();
531 function numRows() {
532 return 0;
536 * Return true if results are included in this result set.
537 * STUB
539 * @return Boolean
541 function hasResults() {
542 return false;
546 * Some search modes return a total hit count for the query
547 * in the entire article database. This may include pages
548 * in namespaces that would not be matched on the given
549 * settings.
551 * Return null if no total hits number is supported.
553 * @return Integer
555 function getTotalHits() {
556 return null;
560 * Some search modes return a suggested alternate term if there are
561 * no exact hits. Returns true if there is one on this set.
563 * @return Boolean
565 function hasSuggestion() {
566 return false;
570 * @return String: suggested query, null if none
572 function getSuggestionQuery() {
573 return null;
577 * @return String: HTML highlighted suggested query, '' if none
579 function getSuggestionSnippet() {
580 return '';
584 * Return information about how and from where the results were fetched,
585 * should be useful for diagnostics and debugging
587 * @return String
589 function getInfo() {
590 return null;
594 * Return a result set of hits on other (multiple) wikis associated with this one
596 * @return SearchResultSet
598 function getInterwikiResults() {
599 return null;
603 * Check if there are results on other wikis
605 * @return Boolean
607 function hasInterwikiResults() {
608 return $this->getInterwikiResults() != null;
612 * Fetches next search result, or false.
613 * STUB
615 * @return SearchResult
617 function next() {
618 return false;
622 * Frees the result set, if applicable.
624 function free() {
625 // ...
630 * This class is used for different SQL-based search engines shipped with MediaWiki
632 class SqlSearchResultSet extends SearchResultSet {
634 protected $mResultSet;
636 function __construct( $resultSet, $terms ) {
637 $this->mResultSet = $resultSet;
638 $this->mTerms = $terms;
641 function termMatches() {
642 return $this->mTerms;
645 function numRows() {
646 if ( $this->mResultSet === false ) {
647 return false;
650 return $this->mResultSet->numRows();
653 function next() {
654 if ( $this->mResultSet === false ) {
655 return false;
658 $row = $this->mResultSet->fetchObject();
659 if ( $row === false ) {
660 return false;
663 return SearchResult::newFromRow( $row );
666 function free() {
667 if ( $this->mResultSet === false ) {
668 return false;
671 $this->mResultSet->free();
676 * @ingroup Search
678 class SearchResultTooMany {
679 # # Some search engines may bail out if too many matches are found
683 * @todo FIXME: This class is horribly factored. It would probably be better to
684 * have a useful base class to which you pass some standard information, then
685 * let the fancy self-highlighters extend that.
686 * @ingroup Search
688 class SearchResult {
691 * @var Revision
693 var $mRevision = null;
694 var $mImage = null;
697 * @var Title
699 var $mTitle;
702 * @var String
704 var $mText;
707 * Return a new SearchResult and initializes it with a title.
709 * @param $title Title
710 * @return SearchResult
712 public static function newFromTitle( $title ) {
713 $result = new self();
714 $result->initFromTitle( $title );
715 return $result;
718 * Return a new SearchResult and initializes it with a row.
720 * @param $row object
721 * @return SearchResult
723 public static function newFromRow( $row ) {
724 $result = new self();
725 $result->initFromRow( $row );
726 return $result;
729 public function __construct( $row = null ) {
730 if ( !is_null( $row ) ) {
731 // Backwards compatibility with pre-1.17 callers
732 $this->initFromRow( $row );
737 * Initialize from a database row. Makes a Title and passes that to
738 * initFromTitle.
740 * @param $row object
742 protected function initFromRow( $row ) {
743 $this->initFromTitle( Title::makeTitle( $row->page_namespace, $row->page_title ) );
747 * Initialize from a Title and if possible initializes a corresponding
748 * Revision and File.
750 * @param $title Title
752 protected function initFromTitle( $title ) {
753 $this->mTitle = $title;
754 if ( !is_null( $this->mTitle ) ) {
755 $id = false;
756 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
757 $this->mRevision = Revision::newFromTitle(
758 $this->mTitle, $id, Revision::READ_NORMAL );
759 if ( $this->mTitle->getNamespace() === NS_FILE ) {
760 $this->mImage = wfFindFile( $this->mTitle );
766 * Check if this is result points to an invalid title
768 * @return Boolean
770 function isBrokenTitle() {
771 if ( is_null( $this->mTitle ) ) {
772 return true;
774 return false;
778 * Check if target page is missing, happens when index is out of date
780 * @return Boolean
782 function isMissingRevision() {
783 return !$this->mRevision && !$this->mImage;
787 * @return Title
789 function getTitle() {
790 return $this->mTitle;
794 * @return float|null if not supported
796 function getScore() {
797 return null;
801 * Lazy initialization of article text from DB
803 protected function initText() {
804 if ( !isset( $this->mText ) ) {
805 if ( $this->mRevision != null ) {
806 //TODO: if we could plug in some code that knows about special content models *and* about
807 // special features of the search engine, the search could benefit.
808 $content = $this->mRevision->getContent();
809 $this->mText = $content ? $content->getTextForSearchIndex() : '';
810 } else { // TODO: can we fetch raw wikitext for commons images?
811 $this->mText = '';
817 * @param array $terms terms to highlight
818 * @return String: highlighted text snippet, null (and not '') if not supported
820 function getTextSnippet( $terms ) {
821 global $wgUser, $wgAdvancedSearchHighlighting;
822 $this->initText();
824 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
825 list( $contextlines, $contextchars ) = SearchEngine::userHighlightPrefs( $wgUser );
826 $h = new SearchHighlighter();
827 if ( $wgAdvancedSearchHighlighting ) {
828 return $h->highlightText( $this->mText, $terms, $contextlines, $contextchars );
829 } else {
830 return $h->highlightSimple( $this->mText, $terms, $contextlines, $contextchars );
835 * @param array $terms terms to highlight
836 * @return String: highlighted title, '' if not supported
838 function getTitleSnippet( $terms ) {
839 return '';
843 * @param array $terms terms to highlight
844 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
846 function getRedirectSnippet( $terms ) {
847 return '';
851 * @return Title object for the redirect to this page, null if none or not supported
853 function getRedirectTitle() {
854 return null;
858 * @return string highlighted relevant section name, null if none or not supported
860 function getSectionSnippet() {
861 return '';
865 * @return Title object (pagename+fragment) for the section, null if none or not supported
867 function getSectionTitle() {
868 return null;
872 * @return String: timestamp
874 function getTimestamp() {
875 if ( $this->mRevision ) {
876 return $this->mRevision->getTimestamp();
877 } elseif ( $this->mImage ) {
878 return $this->mImage->getTimestamp();
880 return '';
884 * @return Integer: number of words
886 function getWordCount() {
887 $this->initText();
888 return str_word_count( $this->mText );
892 * @return Integer: size in bytes
894 function getByteSize() {
895 $this->initText();
896 return strlen( $this->mText );
900 * @return Boolean if hit has related articles
902 function hasRelated() {
903 return false;
907 * @return String: interwiki prefix of the title (return iw even if title is broken)
909 function getInterwikiPrefix() {
910 return '';
914 * A SearchResultSet wrapper for SearchEngine::getNearMatch
916 class SearchNearMatchResultSet extends SearchResultSet {
917 private $fetched = false;
919 * @param $match mixed Title if matched, else null
921 public function __construct( $match ) {
922 $this->result = $match;
924 public function hasResult() {
925 return (bool)$this->result;
927 public function numRows() {
928 return $this->hasResults() ? 1 : 0;
930 public function next() {
931 if ( $this->fetched || !$this->result ) {
932 return false;
934 $this->fetched = true;
935 return SearchResult::newFromTitle( $this->result );
940 * Highlight bits of wikitext
942 * @ingroup Search
944 class SearchHighlighter {
945 var $mCleanWikitext = true;
947 function __construct( $cleanupWikitext = true ) {
948 $this->mCleanWikitext = $cleanupWikitext;
952 * Default implementation of wikitext highlighting
954 * @param $text String
955 * @param array $terms terms to highlight (unescaped)
956 * @param $contextlines Integer
957 * @param $contextchars Integer
958 * @return String
960 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
961 global $wgContLang;
962 global $wgSearchHighlightBoundaries;
963 $fname = __METHOD__;
965 if ( $text == '' ) {
966 return '';
969 // spli text into text + templates/links/tables
970 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
971 // first capture group is for detecting nested templates/links/tables/references
972 $endPatterns = array(
973 1 => '/(\{\{)|(\}\})/', // template
974 2 => '/(\[\[)|(\]\])/', // image
975 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
977 // @todo FIXME: This should prolly be a hook or something
978 if ( function_exists( 'wfCite' ) ) {
979 $spat .= '|(<ref>)'; // references via cite extension
980 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
982 $spat .= '/';
983 $textExt = array(); // text extracts
984 $otherExt = array(); // other extracts
985 wfProfileIn( "$fname-split" );
986 $start = 0;
987 $textLen = strlen( $text );
988 $count = 0; // sequence number to maintain ordering
989 while ( $start < $textLen ) {
990 // find start of template/image/table
991 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE, $start ) ) {
992 $epat = '';
993 foreach ( $matches as $key => $val ) {
994 if ( $key > 0 && $val[1] != - 1 ) {
995 if ( $key == 2 ) {
996 // see if this is an image link
997 $ns = substr( $val[0], 2, - 1 );
998 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE ) {
999 break;
1003 $epat = $endPatterns[$key];
1004 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1005 $start = $val[1];
1006 break;
1009 if ( $epat ) {
1010 // find end (and detect any nested elements)
1011 $level = 0;
1012 $offset = $start + 1;
1013 $found = false;
1014 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE, $offset ) ) {
1015 if ( array_key_exists( 2, $endMatches ) ) {
1016 // found end
1017 if ( $level == 0 ) {
1018 $len = strlen( $endMatches[2][0] );
1019 $off = $endMatches[2][1];
1020 $this->splitAndAdd( $otherExt, $count,
1021 substr( $text, $start, $off + $len - $start ) );
1022 $start = $off + $len;
1023 $found = true;
1024 break;
1025 } else {
1026 // end of nested element
1027 $level -= 1;
1029 } else {
1030 // nested
1031 $level += 1;
1033 $offset = $endMatches[0][1] + strlen( $endMatches[0][0] );
1035 if ( ! $found ) {
1036 // couldn't find appropriate closing tag, skip
1037 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1038 $start += strlen( $matches[0][0] );
1040 continue;
1043 // else: add as text extract
1044 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1045 break;
1048 $all = $textExt + $otherExt; // these have disjunct key sets
1050 wfProfileOut( "$fname-split" );
1052 // prepare regexps
1053 foreach ( $terms as $index => $term ) {
1054 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1055 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1056 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1057 } else {
1058 $terms[$index] = $term;
1061 $anyterm = implode( '|', $terms );
1062 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1064 // @todo FIXME: A hack to scale contextchars, a correct solution
1065 // would be to have contextchars actually be char and not byte
1066 // length, and do proper utf-8 substrings and lengths everywhere,
1067 // but PHP is making that very hard and unclean to implement :(
1068 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1069 $contextchars = intval( $contextchars * $scale );
1071 $patPre = "(^|$wgSearchHighlightBoundaries)";
1072 $patPost = "($wgSearchHighlightBoundaries|$)";
1074 $pat1 = "/(" . $phrase . ")/ui";
1075 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1077 wfProfileIn( "$fname-extract" );
1079 $left = $contextlines;
1081 $snippets = array();
1082 $offsets = array();
1084 // show beginning only if it contains all words
1085 $first = 0;
1086 $firstText = '';
1087 foreach ( $textExt as $index => $line ) {
1088 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1089 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1090 $first = $index;
1091 break;
1094 if ( $firstText ) {
1095 $succ = true;
1096 // check if first text contains all terms
1097 foreach ( $terms as $term ) {
1098 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1099 $succ = false;
1100 break;
1103 if ( $succ ) {
1104 $snippets[$first] = $firstText;
1105 $offsets[$first] = 0;
1108 if ( ! $snippets ) {
1109 // match whole query on text
1110 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1111 // match whole query on templates/tables/images
1112 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1113 // match any words on text
1114 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1115 // match any words on templates/tables/images
1116 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1118 ksort( $snippets );
1121 // add extra chars to each snippet to make snippets constant size
1122 $extended = array();
1123 if ( count( $snippets ) == 0 ) {
1124 // couldn't find the target words, just show beginning of article
1125 if ( array_key_exists( $first, $all ) ) {
1126 $targetchars = $contextchars * $contextlines;
1127 $snippets[$first] = '';
1128 $offsets[$first] = 0;
1130 } else {
1131 // if begin of the article contains the whole phrase, show only that !!
1132 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1133 && $offsets[$first] < $contextchars * 2 ) {
1134 $snippets = array( $first => $snippets[$first] );
1137 // calc by how much to extend existing snippets
1138 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1141 foreach ( $snippets as $index => $line ) {
1142 $extended[$index] = $line;
1143 $len = strlen( $line );
1144 if ( $len < $targetchars - 20 ) {
1145 // complete this line
1146 if ( $len < strlen( $all[$index] ) ) {
1147 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] + $targetchars, $offsets[$index] );
1148 $len = strlen( $extended[$index] );
1151 // add more lines
1152 $add = $index + 1;
1153 while ( $len < $targetchars - 20
1154 && array_key_exists( $add, $all )
1155 && !array_key_exists( $add, $snippets ) ) {
1156 $offsets[$add] = 0;
1157 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1158 $extended[$add] = $tt;
1159 $len += strlen( $tt );
1160 $add++;
1165 // $snippets = array_map( 'htmlspecialchars', $extended );
1166 $snippets = $extended;
1167 $last = - 1;
1168 $extract = '';
1169 foreach ( $snippets as $index => $line ) {
1170 if ( $last == - 1 ) {
1171 $extract .= $line; // first line
1172 } elseif ( $last + 1 == $index && $offsets[$last] + strlen( $snippets[$last] ) >= strlen( $all[$last] ) ) {
1173 $extract .= " " . $line; // continous lines
1174 } else {
1175 $extract .= '<b> ... </b>' . $line;
1178 $last = $index;
1180 if ( $extract ) {
1181 $extract .= '<b> ... </b>';
1184 $processed = array();
1185 foreach ( $terms as $term ) {
1186 if ( ! isset( $processed[$term] ) ) {
1187 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1188 $extract = preg_replace( $pat3,
1189 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1190 $processed[$term] = true;
1194 wfProfileOut( "$fname-extract" );
1196 return $extract;
1200 * Split text into lines and add it to extracts array
1202 * @param array $extracts index -> $line
1203 * @param $count Integer
1204 * @param $text String
1206 function splitAndAdd( &$extracts, &$count, $text ) {
1207 $split = explode( "\n", $this->mCleanWikitext ? $this->removeWiki( $text ) : $text );
1208 foreach ( $split as $line ) {
1209 $tt = trim( $line );
1210 if ( $tt ) {
1211 $extracts[$count++] = $tt;
1217 * Do manual case conversion for non-ascii chars
1219 * @param $matches Array
1220 * @return string
1222 function caseCallback( $matches ) {
1223 global $wgContLang;
1224 if ( strlen( $matches[0] ) > 1 ) {
1225 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1226 } else {
1227 return $matches[0];
1232 * Extract part of the text from start to end, but by
1233 * not chopping up words
1234 * @param $text String
1235 * @param $start Integer
1236 * @param $end Integer
1237 * @param $posStart Integer: (out) actual start position
1238 * @param $posEnd Integer: (out) actual end position
1239 * @return String
1241 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1242 if ( $start != 0 ) {
1243 $start = $this->position( $text, $start, 1 );
1245 if ( $end >= strlen( $text ) ) {
1246 $end = strlen( $text );
1247 } else {
1248 $end = $this->position( $text, $end );
1251 if ( !is_null( $posStart ) ) {
1252 $posStart = $start;
1254 if ( !is_null( $posEnd ) ) {
1255 $posEnd = $end;
1258 if ( $end > $start ) {
1259 return substr( $text, $start, $end - $start );
1260 } else {
1261 return '';
1266 * Find a nonletter near a point (index) in the text
1268 * @param $text String
1269 * @param $point Integer
1270 * @param $offset Integer: offset to found index
1271 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1273 function position( $text, $point, $offset = 0 ) {
1274 $tolerance = 10;
1275 $s = max( 0, $point - $tolerance );
1276 $l = min( strlen( $text ), $point + $tolerance ) - $s;
1277 $m = array();
1278 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE ) ) {
1279 return $m[0][1] + $s + $offset;
1280 } else {
1281 // check if point is on a valid first UTF8 char
1282 $char = ord( $text[$point] );
1283 while ( $char >= 0x80 && $char < 0xc0 ) {
1284 // skip trailing bytes
1285 $point++;
1286 if ( $point >= strlen( $text ) ) {
1287 return strlen( $text );
1289 $char = ord( $text[$point] );
1291 return $point;
1297 * Search extracts for a pattern, and return snippets
1299 * @param string $pattern regexp for matching lines
1300 * @param array $extracts extracts to search
1301 * @param $linesleft Integer: number of extracts to make
1302 * @param $contextchars Integer: length of snippet
1303 * @param array $out map for highlighted snippets
1304 * @param array $offsets map of starting points of snippets
1305 * @protected
1307 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1308 if ( $linesleft == 0 ) {
1309 return; // nothing to do
1311 foreach ( $extracts as $index => $line ) {
1312 if ( array_key_exists( $index, $out ) ) {
1313 continue; // this line already highlighted
1316 $m = array();
1317 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) ) {
1318 continue;
1321 $offset = $m[0][1];
1322 $len = strlen( $m[0][0] );
1323 if ( $offset + $len < $contextchars ) {
1324 $begin = 0;
1325 } elseif ( $len > $contextchars ) {
1326 $begin = $offset;
1327 } else {
1328 $begin = $offset + intval( ( $len - $contextchars ) / 2 );
1331 $end = $begin + $contextchars;
1333 $posBegin = $begin;
1334 // basic snippet from this line
1335 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1336 $offsets[$index] = $posBegin;
1337 $linesleft--;
1338 if ( $linesleft == 0 ) {
1339 return;
1345 * Basic wikitext removal
1346 * @protected
1347 * @return mixed
1349 function removeWiki( $text ) {
1350 $fname = __METHOD__;
1351 wfProfileIn( $fname );
1353 // $text = preg_replace( "/'{2,5}/", "", $text );
1354 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1355 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1356 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1357 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1358 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1359 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1360 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1361 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1362 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1363 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1364 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1365 $text = preg_replace( "/'''''/", "", $text );
1366 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1367 $text = preg_replace( "/''/", "", $text );
1369 wfProfileOut( $fname );
1370 return $text;
1374 * callback to replace [[target|caption]] kind of links, if
1375 * the target is category or image, leave it
1377 * @param $matches Array
1379 function linkReplace( $matches ) {
1380 $colon = strpos( $matches[1], ':' );
1381 if ( $colon === false ) {
1382 return $matches[2]; // replace with caption
1384 global $wgContLang;
1385 $ns = substr( $matches[1], 0, $colon );
1386 $index = $wgContLang->getNsIndex( $ns );
1387 if ( $index !== false && ( $index == NS_FILE || $index == NS_CATEGORY ) ) {
1388 return $matches[0]; // return the whole thing
1389 } else {
1390 return $matches[2];
1395 * Simple & fast snippet extraction, but gives completely unrelevant
1396 * snippets
1398 * @param $text String
1399 * @param $terms Array
1400 * @param $contextlines Integer
1401 * @param $contextchars Integer
1402 * @return String
1404 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1405 global $wgContLang;
1406 $fname = __METHOD__;
1408 $lines = explode( "\n", $text );
1410 $terms = implode( '|', $terms );
1411 $max = intval( $contextchars ) + 1;
1412 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1414 $lineno = 0;
1416 $extract = "";
1417 wfProfileIn( "$fname-extract" );
1418 foreach ( $lines as $line ) {
1419 if ( 0 == $contextlines ) {
1420 break;
1422 ++$lineno;
1423 $m = array();
1424 if ( ! preg_match( $pat1, $line, $m ) ) {
1425 continue;
1427 --$contextlines;
1428 // truncate function changes ... to relevant i18n message.
1429 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1431 if ( count( $m ) < 3 ) {
1432 $post = '';
1433 } else {
1434 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1437 $found = $m[2];
1439 $line = htmlspecialchars( $pre . $found . $post );
1440 $pat2 = '/(' . $terms . ")/i";
1441 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1443 $extract .= "${line}\n";
1445 wfProfileOut( "$fname-extract" );
1447 return $extract;
1453 * Dummy class to be used when non-supported Database engine is present.
1454 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1455 * such as a LIKE search through titles.
1456 * @ingroup Search
1458 class SearchEngineDummy extends SearchEngine {
1459 // no-op