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
25 * @defgroup Search Search
29 * Contain a class for special pages
36 var $searchTerms = array();
37 var $namespaces = array( NS_MAIN
);
38 var $showRedirects = false;
39 protected $showSuggestion = true;
42 protected $features = array();
49 function __construct( $db = null ) {
53 $this->db
= wfGetDB( DB_SLAVE
);
58 * Perform a full text search query and return a result set.
59 * If title searches are not supported or disabled, return null.
62 * @param string $term raw search term
63 * @return SearchResultSet|Status|null
65 function searchText( $term ) {
70 * Perform a title-only search query and return a result set.
71 * If title searches are not supported or disabled, return null.
74 * @param string $term raw search term
75 * @return SearchResultSet|null
77 function searchTitle( $term ) {
82 * If this search backend can list/unlist redirects
83 * @deprecated since 1.18 Call supports( 'list-redirects' );
86 function acceptListRedirects() {
87 wfDeprecated( __METHOD__
, '1.18' );
88 return $this->supports( 'list-redirects' );
93 * @param $feature String
96 public function supports( $feature ) {
98 case 'list-redirects':
101 case 'title-suffix-filter':
108 * Way to pass custom data for engines
110 * @param $feature String
114 public function setFeatureData( $feature, $data ) {
115 $this->features
[$feature] = $data;
119 * When overridden in derived class, performs database-specific conversions
120 * on text to be used for searching or updating search index.
121 * Default implementation does nothing (simply returns $string).
123 * @param string $string String to process
126 public function normalizeText( $string ) {
129 // Some languages such as Chinese require word segmentation
130 return $wgContLang->segmentByWord( $string );
134 * Transform search term in cases when parts of the query came as different GET params (when supported)
135 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
137 function transformSearchTerm( $term ) {
142 * If an exact title match can be found, or a very slightly close match,
143 * return the title. If no match, returns NULL.
145 * @param $searchterm String
148 public static function getNearMatch( $searchterm ) {
149 $title = self
::getNearMatchInternal( $searchterm );
151 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
156 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
159 * @param $searchterm string
160 * @return SearchResultSet
162 public static function getNearMatchResultSet( $searchterm ) {
163 return new SearchNearMatchResultSet( self
::getNearMatch( $searchterm ) );
167 * Really find the title match.
170 private static function getNearMatchInternal( $searchterm ) {
171 global $wgContLang, $wgEnableSearchContributorsByIP;
173 $allSearchTerms = array( $searchterm );
175 if ( $wgContLang->hasVariants() ) {
176 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
180 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
184 foreach ( $allSearchTerms as $term ) {
186 # Exact match? No need to look further.
187 $title = Title
::newFromText( $term );
188 if ( is_null( $title ) ) {
192 # Try files if searching in the Media: namespace
193 if ( $title->getNamespace() == NS_MEDIA
) {
194 $title = Title
::makeTitle( NS_FILE
, $title->getText() );
197 if ( $title->isSpecialPage() ||
$title->isExternal() ||
$title->exists() ) {
201 # See if it still otherwise has content is some sane sense
202 $page = WikiPage
::factory( $title );
203 if ( $page->hasViewableContent() ) {
207 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
211 # Now try all lower case (i.e. first letter capitalized)
212 $title = Title
::newFromText( $wgContLang->lc( $term ) );
213 if ( $title && $title->exists() ) {
217 # Now try capitalized string
218 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
219 if ( $title && $title->exists() ) {
223 # Now try all upper case
224 $title = Title
::newFromText( $wgContLang->uc( $term ) );
225 if ( $title && $title->exists() ) {
229 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
230 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
231 if ( $title && $title->exists() ) {
235 // Give hooks a chance at better match variants
237 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
242 $title = Title
::newFromText( $searchterm );
244 # Entering an IP address goes to the contributions page
245 if ( $wgEnableSearchContributorsByIP ) {
246 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
247 || User
::isIP( trim( $searchterm ) ) ) {
248 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
252 # Entering a user goes to the user page whether it's there or not
253 if ( $title->getNamespace() == NS_USER
) {
257 # Go to images that exist even if there's no local page.
258 # There may have been a funny upload, or it may be on a shared
259 # file repository such as Wikimedia Commons.
260 if ( $title->getNamespace() == NS_FILE
) {
261 $image = wfFindFile( $title );
267 # MediaWiki namespace? Page may be "implied" if not customized.
268 # Just return it, with caps forced as the message system likes it.
269 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
270 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
273 # Quoted term? Try without the quotes...
275 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
276 return SearchEngine
::getNearMatch( $matches[1] );
282 public static function legalSearchChars() {
283 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
287 * Set the maximum number of results to return
288 * and how many to skip before returning the first.
290 * @param $limit Integer
291 * @param $offset Integer
293 function setLimitOffset( $limit, $offset = 0 ) {
294 $this->limit
= intval( $limit );
295 $this->offset
= intval( $offset );
299 * Set which namespaces the search should include.
300 * Give an array of namespace index numbers.
302 * @param $namespaces Array
304 function setNamespaces( $namespaces ) {
305 $this->namespaces
= $namespaces;
309 * Set whether the searcher should try to build a suggestion. Note: some searchers
310 * don't support building a suggestion in the first place and others don't respect
313 * @param boolean $showSuggestion should the searcher try to build suggestions
315 function setShowSuggestion( $showSuggestion ) {
316 $this->showSuggestion
= $showSuggestion;
320 * Parse some common prefixes: all (search everything)
323 * @param $query String
326 function replacePrefixes( $query ) {
330 if ( strpos( $query, ':' ) === false ) { // nothing to do
331 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
335 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
336 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
337 $this->namespaces
= null;
338 $parsed = substr( $query, strlen( $allkeyword ) );
339 } elseif ( strpos( $query, ':' ) !== false ) {
340 $prefix = substr( $query, 0, strpos( $query, ':' ) );
341 $index = $wgContLang->getNsIndex( $prefix );
342 if ( $index !== false ) {
343 $this->namespaces
= array( $index );
344 $parsed = substr( $query, strlen( $prefix ) +
1 );
347 if ( trim( $parsed ) == '' ) {
348 $parsed = $query; // prefix was the whole query
351 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
357 * Make a list of searchable namespaces and their canonical names.
360 public static function searchableNamespaces() {
363 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
364 if ( $ns >= NS_MAIN
) {
369 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
374 * Extract default namespaces to search from the given user's
375 * settings, returning a list of index numbers.
380 public static function userNamespaces( $user ) {
381 global $wgSearchEverythingOnlyLoggedIn;
383 $searchableNamespaces = SearchEngine
::searchableNamespaces();
385 // get search everything preference, that can be set to be read for logged-in users
386 // it overrides other options
387 if ( !$wgSearchEverythingOnlyLoggedIn ||
$user->isLoggedIn() ) {
388 if ( $user->getOption( 'searcheverything' ) ) {
389 return array_keys( $searchableNamespaces );
394 foreach ( $searchableNamespaces as $ns => $name ) {
395 if ( $user->getOption( 'searchNs' . $ns ) ) {
404 * Find snippet highlight settings for all users
406 * @return Array contextlines, contextchars
408 public static function userHighlightPrefs() {
409 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
410 $contextchars = 75; // same as above.... :P
411 return array( $contextlines, $contextchars );
415 * An array of namespaces indexes to be searched by default
419 public static function defaultNamespaces() {
420 global $wgNamespacesToBeSearchedDefault;
422 return array_keys( $wgNamespacesToBeSearchedDefault, true );
426 * Get a list of namespace names useful for showing in tooltips
429 * @param $namespaces Array
432 public static function namespacesAsText( $namespaces ) {
435 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
436 foreach ( $formatted as $key => $ns ) {
437 if ( empty( $ns ) ) {
438 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
445 * Return the help namespaces to be shown on Special:Search
449 public static function helpNamespaces() {
450 global $wgNamespacesToBeSearchedHelp;
452 return array_keys( $wgNamespacesToBeSearchedHelp, true );
456 * Return a 'cleaned up' search string
458 * @param $text String
461 function filter( $text ) {
462 $lc = $this->legalSearchChars();
463 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
466 * Load up the appropriate search engine class for the currently
467 * active database backend, and return a configured instance.
469 * @param String $type Type of search backend, if not the default
470 * @return SearchEngine
472 public static function create( $type = null ) {
473 global $wgSearchType;
476 $alternatives = self
::getSearchTypes();
478 if ( $type && in_array( $type, $alternatives ) ) {
480 } elseif ( $wgSearchType !== null ) {
481 $class = $wgSearchType;
483 $dbr = wfGetDB( DB_SLAVE
);
484 $class = $dbr->getSearchEngine();
487 $search = new $class( $dbr );
488 $search->setLimitOffset( 0, 0 );
493 * Return the search engines we support. If only $wgSearchType
494 * is set, it'll be an array of just that one item.
498 public static function getSearchTypes() {
499 global $wgSearchType, $wgSearchTypeAlternatives;
501 $alternatives = $wgSearchTypeAlternatives ?
: array();
502 array_unshift( $alternatives, $wgSearchType );
504 return $alternatives;
508 * Create or update the search index record for the given page.
509 * Title and text should be pre-processed.
513 * @param $title String
514 * @param $text String
516 function update( $id, $title, $text ) {
521 * Update a search index record's title only.
522 * Title should be pre-processed.
526 * @param $title String
528 function updateTitle( $id, $title ) {
533 * Delete an indexed page
534 * Title should be pre-processed.
537 * @param Integer $id Page id that was deleted
538 * @param String $title Title of page that was deleted
540 function delete( $id, $title ) {
545 * Get OpenSearch suggestion template
549 public static function getOpenSearchTemplate() {
550 global $wgOpenSearchTemplate, $wgCanonicalServer;
551 if ( $wgOpenSearchTemplate ) {
552 return $wgOpenSearchTemplate;
554 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
558 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
563 * Get the raw text for updating the index from a content object
564 * Nicer search backends could possibly do something cooler than
565 * just returning raw text
567 * @todo This isn't ideal, we'd really like to have content-specific handling here
568 * @param Title $t Title we're indexing
569 * @param Content $c Content of the page to index
572 public function getTextFromContent( Title
$t, Content
$c = null ) {
573 return $c ?
$c->getTextForSearchIndex() : '';
577 * If an implementation of SearchEngine handles all of its own text processing
578 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
579 * rather silly handling, it should return true here instead.
583 public function textAlreadyUpdatedForIndex() {
591 class SearchResultSet
{
593 * Fetch an array of regular expression fragments for matching
594 * the search terms as parsed by this engine in a text extract.
599 function termMatches() {
608 * Return true if results are included in this result set.
613 function hasResults() {
618 * Some search modes return a total hit count for the query
619 * in the entire article database. This may include pages
620 * in namespaces that would not be matched on the given
623 * Return null if no total hits number is supported.
627 function getTotalHits() {
632 * Some search modes return a suggested alternate term if there are
633 * no exact hits. Returns true if there is one on this set.
637 function hasSuggestion() {
642 * @return String: suggested query, null if none
644 function getSuggestionQuery() {
649 * @return String: HTML highlighted suggested query, '' if none
651 function getSuggestionSnippet() {
656 * Return information about how and from where the results were fetched,
657 * should be useful for diagnostics and debugging
666 * Return a result set of hits on other (multiple) wikis associated with this one
668 * @return SearchResultSet
670 function getInterwikiResults() {
675 * Check if there are results on other wikis
679 function hasInterwikiResults() {
680 return $this->getInterwikiResults() != null;
684 * Fetches next search result, or false.
687 * @return SearchResult
694 * Frees the result set, if applicable.
702 * This class is used for different SQL-based search engines shipped with MediaWiki
704 class SqlSearchResultSet
extends SearchResultSet
{
706 protected $mResultSet;
708 function __construct( $resultSet, $terms ) {
709 $this->mResultSet
= $resultSet;
710 $this->mTerms
= $terms;
713 function termMatches() {
714 return $this->mTerms
;
718 if ( $this->mResultSet
=== false ) {
722 return $this->mResultSet
->numRows();
726 if ( $this->mResultSet
=== false ) {
730 $row = $this->mResultSet
->fetchObject();
731 if ( $row === false ) {
735 return SearchResult
::newFromRow( $row );
739 if ( $this->mResultSet
=== false ) {
743 $this->mResultSet
->free();
750 class SearchResultTooMany
{
751 # # Some search engines may bail out if too many matches are found
755 * @todo FIXME: This class is horribly factored. It would probably be better to
756 * have a useful base class to which you pass some standard information, then
757 * let the fancy self-highlighters extend that.
765 var $mRevision = null;
779 * Return a new SearchResult and initializes it with a title.
781 * @param $title Title
782 * @return SearchResult
784 public static function newFromTitle( $title ) {
785 $result = new self();
786 $result->initFromTitle( $title );
790 * Return a new SearchResult and initializes it with a row.
793 * @return SearchResult
795 public static function newFromRow( $row ) {
796 $result = new self();
797 $result->initFromRow( $row );
801 public function __construct( $row = null ) {
802 if ( !is_null( $row ) ) {
803 // Backwards compatibility with pre-1.17 callers
804 $this->initFromRow( $row );
809 * Initialize from a database row. Makes a Title and passes that to
814 protected function initFromRow( $row ) {
815 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
819 * Initialize from a Title and if possible initializes a corresponding
822 * @param $title Title
824 protected function initFromTitle( $title ) {
825 $this->mTitle
= $title;
826 if ( !is_null( $this->mTitle
) ) {
828 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
829 $this->mRevision
= Revision
::newFromTitle(
830 $this->mTitle
, $id, Revision
::READ_NORMAL
);
831 if ( $this->mTitle
->getNamespace() === NS_FILE
) {
832 $this->mImage
= wfFindFile( $this->mTitle
);
838 * Check if this is result points to an invalid title
842 function isBrokenTitle() {
843 if ( is_null( $this->mTitle
) ) {
850 * Check if target page is missing, happens when index is out of date
854 function isMissingRevision() {
855 return !$this->mRevision
&& !$this->mImage
;
861 function getTitle() {
862 return $this->mTitle
;
866 * @return float|null if not supported
868 function getScore() {
873 * Lazy initialization of article text from DB
875 protected function initText() {
876 if ( !isset( $this->mText
) ) {
877 if ( $this->mRevision
!= null ) {
878 $this->mText
= SearchEngine
::create()
879 ->getTextFromContent( $this->mTitle
, $this->mRevision
->getContent() );
880 } else { // TODO: can we fetch raw wikitext for commons images?
887 * @param array $terms terms to highlight
888 * @return String: highlighted text snippet, null (and not '') if not supported
890 function getTextSnippet( $terms ) {
891 global $wgAdvancedSearchHighlighting;
894 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
895 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs();
896 $h = new SearchHighlighter();
897 if ( $wgAdvancedSearchHighlighting ) {
898 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
900 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
905 * @param array $terms terms to highlight
906 * @return String: highlighted title, '' if not supported
908 function getTitleSnippet( $terms ) {
913 * @param array $terms terms to highlight
914 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
916 function getRedirectSnippet( $terms ) {
921 * @return Title object for the redirect to this page, null if none or not supported
923 function getRedirectTitle() {
928 * @return string highlighted relevant section name, null if none or not supported
930 function getSectionSnippet() {
935 * @return Title object (pagename+fragment) for the section, null if none or not supported
937 function getSectionTitle() {
942 * @return String: timestamp
944 function getTimestamp() {
945 if ( $this->mRevision
) {
946 return $this->mRevision
->getTimestamp();
947 } elseif ( $this->mImage
) {
948 return $this->mImage
->getTimestamp();
954 * @return Integer: number of words
956 function getWordCount() {
958 return str_word_count( $this->mText
);
962 * @return Integer: size in bytes
964 function getByteSize() {
966 return strlen( $this->mText
);
970 * @return Boolean if hit has related articles
972 function hasRelated() {
977 * @return String: interwiki prefix of the title (return iw even if title is broken)
979 function getInterwikiPrefix() {
984 * A SearchResultSet wrapper for SearchEngine::getNearMatch
986 class SearchNearMatchResultSet
extends SearchResultSet
{
987 private $fetched = false;
989 * @param $match mixed Title if matched, else null
991 public function __construct( $match ) {
992 $this->result
= $match;
994 public function hasResult() {
995 return (bool)$this->result
;
997 public function numRows() {
998 return $this->hasResults() ?
1 : 0;
1000 public function next() {
1001 if ( $this->fetched ||
!$this->result
) {
1004 $this->fetched
= true;
1005 return SearchResult
::newFromTitle( $this->result
);
1010 * Highlight bits of wikitext
1014 class SearchHighlighter
{
1015 var $mCleanWikitext = true;
1017 function __construct( $cleanupWikitext = true ) {
1018 $this->mCleanWikitext
= $cleanupWikitext;
1022 * Default implementation of wikitext highlighting
1024 * @param $text String
1025 * @param array $terms terms to highlight (unescaped)
1026 * @param $contextlines Integer
1027 * @param $contextchars Integer
1030 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
1032 global $wgSearchHighlightBoundaries;
1033 $fname = __METHOD__
;
1035 if ( $text == '' ) {
1039 // spli text into text + templates/links/tables
1040 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
1041 // first capture group is for detecting nested templates/links/tables/references
1042 $endPatterns = array(
1043 1 => '/(\{\{)|(\}\})/', // template
1044 2 => '/(\[\[)|(\]\])/', // image
1045 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
1047 // @todo FIXME: This should prolly be a hook or something
1048 if ( function_exists( 'wfCite' ) ) {
1049 $spat .= '|(<ref>)'; // references via cite extension
1050 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
1053 $textExt = array(); // text extracts
1054 $otherExt = array(); // other extracts
1055 wfProfileIn( "$fname-split" );
1057 $textLen = strlen( $text );
1058 $count = 0; // sequence number to maintain ordering
1059 while ( $start < $textLen ) {
1060 // find start of template/image/table
1061 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
1063 foreach ( $matches as $key => $val ) {
1064 if ( $key > 0 && $val[1] != - 1 ) {
1066 // see if this is an image link
1067 $ns = substr( $val[0], 2, - 1 );
1068 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
) {
1073 $epat = $endPatterns[$key];
1074 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1080 // find end (and detect any nested elements)
1082 $offset = $start +
1;
1084 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
1085 if ( array_key_exists( 2, $endMatches ) ) {
1087 if ( $level == 0 ) {
1088 $len = strlen( $endMatches[2][0] );
1089 $off = $endMatches[2][1];
1090 $this->splitAndAdd( $otherExt, $count,
1091 substr( $text, $start, $off +
$len - $start ) );
1092 $start = $off +
$len;
1096 // end of nested element
1103 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
1106 // couldn't find appropriate closing tag, skip
1107 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1108 $start +
= strlen( $matches[0][0] );
1113 // else: add as text extract
1114 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1118 $all = $textExt +
$otherExt; // these have disjunct key sets
1120 wfProfileOut( "$fname-split" );
1123 foreach ( $terms as $index => $term ) {
1124 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1125 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1126 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1128 $terms[$index] = $term;
1131 $anyterm = implode( '|', $terms );
1132 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1134 // @todo FIXME: A hack to scale contextchars, a correct solution
1135 // would be to have contextchars actually be char and not byte
1136 // length, and do proper utf-8 substrings and lengths everywhere,
1137 // but PHP is making that very hard and unclean to implement :(
1138 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1139 $contextchars = intval( $contextchars * $scale );
1141 $patPre = "(^|$wgSearchHighlightBoundaries)";
1142 $patPost = "($wgSearchHighlightBoundaries|$)";
1144 $pat1 = "/(" . $phrase . ")/ui";
1145 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1147 wfProfileIn( "$fname-extract" );
1149 $left = $contextlines;
1151 $snippets = array();
1154 // show beginning only if it contains all words
1157 foreach ( $textExt as $index => $line ) {
1158 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1159 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1166 // check if first text contains all terms
1167 foreach ( $terms as $term ) {
1168 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1174 $snippets[$first] = $firstText;
1175 $offsets[$first] = 0;
1178 if ( ! $snippets ) {
1179 // match whole query on text
1180 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1181 // match whole query on templates/tables/images
1182 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1183 // match any words on text
1184 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1185 // match any words on templates/tables/images
1186 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1191 // add extra chars to each snippet to make snippets constant size
1192 $extended = array();
1193 if ( count( $snippets ) == 0 ) {
1194 // couldn't find the target words, just show beginning of article
1195 if ( array_key_exists( $first, $all ) ) {
1196 $targetchars = $contextchars * $contextlines;
1197 $snippets[$first] = '';
1198 $offsets[$first] = 0;
1201 // if begin of the article contains the whole phrase, show only that !!
1202 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1203 && $offsets[$first] < $contextchars * 2 ) {
1204 $snippets = array( $first => $snippets[$first] );
1207 // calc by how much to extend existing snippets
1208 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1211 foreach ( $snippets as $index => $line ) {
1212 $extended[$index] = $line;
1213 $len = strlen( $line );
1214 if ( $len < $targetchars - 20 ) {
1215 // complete this line
1216 if ( $len < strlen( $all[$index] ) ) {
1217 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1218 $len = strlen( $extended[$index] );
1223 while ( $len < $targetchars - 20
1224 && array_key_exists( $add, $all )
1225 && !array_key_exists( $add, $snippets ) ) {
1227 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1228 $extended[$add] = $tt;
1229 $len +
= strlen( $tt );
1235 // $snippets = array_map( 'htmlspecialchars', $extended );
1236 $snippets = $extended;
1239 foreach ( $snippets as $index => $line ) {
1240 if ( $last == - 1 ) {
1241 $extract .= $line; // first line
1242 } elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) ) {
1243 $extract .= " " . $line; // continous lines
1245 $extract .= '<b> ... </b>' . $line;
1251 $extract .= '<b> ... </b>';
1254 $processed = array();
1255 foreach ( $terms as $term ) {
1256 if ( ! isset( $processed[$term] ) ) {
1257 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1258 $extract = preg_replace( $pat3,
1259 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1260 $processed[$term] = true;
1264 wfProfileOut( "$fname-extract" );
1270 * Split text into lines and add it to extracts array
1272 * @param array $extracts index -> $line
1273 * @param $count Integer
1274 * @param $text String
1276 function splitAndAdd( &$extracts, &$count, $text ) {
1277 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1278 foreach ( $split as $line ) {
1279 $tt = trim( $line );
1281 $extracts[$count++
] = $tt;
1287 * Do manual case conversion for non-ascii chars
1289 * @param $matches Array
1292 function caseCallback( $matches ) {
1294 if ( strlen( $matches[0] ) > 1 ) {
1295 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1302 * Extract part of the text from start to end, but by
1303 * not chopping up words
1304 * @param $text String
1305 * @param $start Integer
1306 * @param $end Integer
1307 * @param $posStart Integer: (out) actual start position
1308 * @param $posEnd Integer: (out) actual end position
1311 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1312 if ( $start != 0 ) {
1313 $start = $this->position( $text, $start, 1 );
1315 if ( $end >= strlen( $text ) ) {
1316 $end = strlen( $text );
1318 $end = $this->position( $text, $end );
1321 if ( !is_null( $posStart ) ) {
1324 if ( !is_null( $posEnd ) ) {
1328 if ( $end > $start ) {
1329 return substr( $text, $start, $end - $start );
1336 * Find a nonletter near a point (index) in the text
1338 * @param $text String
1339 * @param $point Integer
1340 * @param $offset Integer: offset to found index
1341 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1343 function position( $text, $point, $offset = 0 ) {
1345 $s = max( 0, $point - $tolerance );
1346 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1348 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1349 return $m[0][1] +
$s +
$offset;
1351 // check if point is on a valid first UTF8 char
1352 $char = ord( $text[$point] );
1353 while ( $char >= 0x80 && $char < 0xc0 ) {
1354 // skip trailing bytes
1356 if ( $point >= strlen( $text ) ) {
1357 return strlen( $text );
1359 $char = ord( $text[$point] );
1367 * Search extracts for a pattern, and return snippets
1369 * @param string $pattern regexp for matching lines
1370 * @param array $extracts extracts to search
1371 * @param $linesleft Integer: number of extracts to make
1372 * @param $contextchars Integer: length of snippet
1373 * @param array $out map for highlighted snippets
1374 * @param array $offsets map of starting points of snippets
1377 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1378 if ( $linesleft == 0 ) {
1379 return; // nothing to do
1381 foreach ( $extracts as $index => $line ) {
1382 if ( array_key_exists( $index, $out ) ) {
1383 continue; // this line already highlighted
1387 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) ) {
1392 $len = strlen( $m[0][0] );
1393 if ( $offset +
$len < $contextchars ) {
1395 } elseif ( $len > $contextchars ) {
1398 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1401 $end = $begin +
$contextchars;
1404 // basic snippet from this line
1405 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1406 $offsets[$index] = $posBegin;
1408 if ( $linesleft == 0 ) {
1415 * Basic wikitext removal
1419 function removeWiki( $text ) {
1420 $fname = __METHOD__
;
1421 wfProfileIn( $fname );
1423 // $text = preg_replace( "/'{2,5}/", "", $text );
1424 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1425 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1426 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1427 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1428 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1429 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1430 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1431 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1432 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1433 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1434 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1435 $text = preg_replace( "/'''''/", "", $text );
1436 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1437 $text = preg_replace( "/''/", "", $text );
1439 wfProfileOut( $fname );
1444 * callback to replace [[target|caption]] kind of links, if
1445 * the target is category or image, leave it
1447 * @param $matches Array
1449 function linkReplace( $matches ) {
1450 $colon = strpos( $matches[1], ':' );
1451 if ( $colon === false ) {
1452 return $matches[2]; // replace with caption
1455 $ns = substr( $matches[1], 0, $colon );
1456 $index = $wgContLang->getNsIndex( $ns );
1457 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) ) {
1458 return $matches[0]; // return the whole thing
1465 * Simple & fast snippet extraction, but gives completely unrelevant
1468 * @param $text String
1469 * @param $terms Array
1470 * @param $contextlines Integer
1471 * @param $contextchars Integer
1474 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1476 $fname = __METHOD__
;
1478 $lines = explode( "\n", $text );
1480 $terms = implode( '|', $terms );
1481 $max = intval( $contextchars ) +
1;
1482 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1487 wfProfileIn( "$fname-extract" );
1488 foreach ( $lines as $line ) {
1489 if ( 0 == $contextlines ) {
1494 if ( ! preg_match( $pat1, $line, $m ) ) {
1498 // truncate function changes ... to relevant i18n message.
1499 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1501 if ( count( $m ) < 3 ) {
1504 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1509 $line = htmlspecialchars( $pre . $found . $post );
1510 $pat2 = '/(' . $terms . ")/i";
1511 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1513 $extract .= "${line}\n";
1515 wfProfileOut( "$fname-extract" );
1523 * Dummy class to be used when non-supported Database engine is present.
1524 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1525 * such as a LIKE search through titles.
1528 class SearchEngineDummy
extends SearchEngine
{