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;
41 protected $features = array();
48 function __construct( $db = null ) {
52 $this->db
= wfGetDB( DB_SLAVE
);
57 * Perform a full text search query and return a result set.
58 * If title searches are not supported or disabled, return null.
61 * @param string $term raw search term
62 * @return SearchResultSet|Status|null
64 function searchText( $term ) {
69 * Perform a title-only search query and return a result set.
70 * If title searches are not supported or disabled, return null.
73 * @param string $term raw search term
74 * @return SearchResultSet|null
76 function searchTitle( $term ) {
81 * If this search backend can list/unlist redirects
82 * @deprecated since 1.18 Call supports( 'list-redirects' );
85 function acceptListRedirects() {
86 wfDeprecated( __METHOD__
, '1.18' );
87 return $this->supports( 'list-redirects' );
92 * @param $feature String
95 public function supports( $feature ) {
97 case 'list-redirects':
100 case 'title-suffix-filter':
107 * Way to pass custom data for engines
109 * @param $feature String
113 public function setFeatureData( $feature, $data ) {
114 $this->features
[$feature] = $data;
118 * When overridden in derived class, performs database-specific conversions
119 * on text to be used for searching or updating search index.
120 * Default implementation does nothing (simply returns $string).
122 * @param string $string String to process
125 public function normalizeText( $string ) {
128 // Some languages such as Chinese require word segmentation
129 return $wgContLang->segmentByWord( $string );
133 * Transform search term in cases when parts of the query came as different GET params (when supported)
134 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
136 function transformSearchTerm( $term ) {
141 * If an exact title match can be found, or a very slightly close match,
142 * return the title. If no match, returns NULL.
144 * @param $searchterm String
147 public static function getNearMatch( $searchterm ) {
148 $title = self
::getNearMatchInternal( $searchterm );
150 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
155 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
158 * @param $searchterm string
159 * @return SearchResultSet
161 public static function getNearMatchResultSet( $searchterm ) {
162 return new SearchNearMatchResultSet( self
::getNearMatch( $searchterm ) );
166 * Really find the title match.
169 private static function getNearMatchInternal( $searchterm ) {
170 global $wgContLang, $wgEnableSearchContributorsByIP;
172 $allSearchTerms = array( $searchterm );
174 if ( $wgContLang->hasVariants() ) {
175 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
179 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
183 foreach ( $allSearchTerms as $term ) {
185 # Exact match? No need to look further.
186 $title = Title
::newFromText( $term );
187 if ( is_null( $title ) ) {
191 # Try files if searching in the Media: namespace
192 if ( $title->getNamespace() == NS_MEDIA
) {
193 $title = Title
::makeTitle( NS_FILE
, $title->getText() );
196 if ( $title->isSpecialPage() ||
$title->isExternal() ||
$title->exists() ) {
200 # See if it still otherwise has content is some sane sense
201 $page = WikiPage
::factory( $title );
202 if ( $page->hasViewableContent() ) {
206 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
210 # Now try all lower case (i.e. first letter capitalized)
211 $title = Title
::newFromText( $wgContLang->lc( $term ) );
212 if ( $title && $title->exists() ) {
216 # Now try capitalized string
217 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
218 if ( $title && $title->exists() ) {
222 # Now try all upper case
223 $title = Title
::newFromText( $wgContLang->uc( $term ) );
224 if ( $title && $title->exists() ) {
228 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
229 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
230 if ( $title && $title->exists() ) {
234 // Give hooks a chance at better match variants
236 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
241 $title = Title
::newFromText( $searchterm );
243 # Entering an IP address goes to the contributions page
244 if ( $wgEnableSearchContributorsByIP ) {
245 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
246 || User
::isIP( trim( $searchterm ) ) ) {
247 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
251 # Entering a user goes to the user page whether it's there or not
252 if ( $title->getNamespace() == NS_USER
) {
256 # Go to images that exist even if there's no local page.
257 # There may have been a funny upload, or it may be on a shared
258 # file repository such as Wikimedia Commons.
259 if ( $title->getNamespace() == NS_FILE
) {
260 $image = wfFindFile( $title );
266 # MediaWiki namespace? Page may be "implied" if not customized.
267 # Just return it, with caps forced as the message system likes it.
268 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
269 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
272 # Quoted term? Try without the quotes...
274 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
275 return SearchEngine
::getNearMatch( $matches[1] );
281 public static function legalSearchChars() {
282 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
286 * Set the maximum number of results to return
287 * and how many to skip before returning the first.
289 * @param $limit Integer
290 * @param $offset Integer
292 function setLimitOffset( $limit, $offset = 0 ) {
293 $this->limit
= intval( $limit );
294 $this->offset
= intval( $offset );
298 * Set which namespaces the search should include.
299 * Give an array of namespace index numbers.
301 * @param $namespaces Array
303 function setNamespaces( $namespaces ) {
304 $this->namespaces
= $namespaces;
308 * Parse some common prefixes: all (search everything)
311 * @param $query String
314 function replacePrefixes( $query ) {
318 if ( strpos( $query, ':' ) === false ) { // nothing to do
319 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
323 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
324 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
325 $this->namespaces
= null;
326 $parsed = substr( $query, strlen( $allkeyword ) );
327 } elseif ( strpos( $query, ':' ) !== false ) {
328 $prefix = substr( $query, 0, strpos( $query, ':' ) );
329 $index = $wgContLang->getNsIndex( $prefix );
330 if ( $index !== false ) {
331 $this->namespaces
= array( $index );
332 $parsed = substr( $query, strlen( $prefix ) +
1 );
335 if ( trim( $parsed ) == '' ) {
336 $parsed = $query; // prefix was the whole query
339 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
345 * Make a list of searchable namespaces and their canonical names.
348 public static function searchableNamespaces() {
351 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
352 if ( $ns >= NS_MAIN
) {
357 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
362 * Extract default namespaces to search from the given user's
363 * settings, returning a list of index numbers.
368 public static function userNamespaces( $user ) {
369 global $wgSearchEverythingOnlyLoggedIn;
371 $searchableNamespaces = SearchEngine
::searchableNamespaces();
373 // get search everything preference, that can be set to be read for logged-in users
374 // it overrides other options
375 if ( !$wgSearchEverythingOnlyLoggedIn ||
$user->isLoggedIn() ) {
376 if ( $user->getOption( 'searcheverything' ) ) {
377 return array_keys( $searchableNamespaces );
382 foreach ( $searchableNamespaces as $ns => $name ) {
383 if ( $user->getOption( 'searchNs' . $ns ) ) {
392 * Find snippet highlight settings for all users
394 * @return Array contextlines, contextchars
396 public static function userHighlightPrefs() {
397 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
398 $contextchars = 75; // same as above.... :P
399 return array( $contextlines, $contextchars );
403 * An array of namespaces indexes to be searched by default
407 public static function defaultNamespaces() {
408 global $wgNamespacesToBeSearchedDefault;
410 return array_keys( $wgNamespacesToBeSearchedDefault, true );
414 * Get a list of namespace names useful for showing in tooltips
417 * @param $namespaces Array
420 public static function namespacesAsText( $namespaces ) {
423 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
424 foreach ( $formatted as $key => $ns ) {
425 if ( empty( $ns ) ) {
426 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
433 * Return the help namespaces to be shown on Special:Search
437 public static function helpNamespaces() {
438 global $wgNamespacesToBeSearchedHelp;
440 return array_keys( $wgNamespacesToBeSearchedHelp, true );
444 * Return a 'cleaned up' search string
446 * @param $text String
449 function filter( $text ) {
450 $lc = $this->legalSearchChars();
451 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
454 * Load up the appropriate search engine class for the currently
455 * active database backend, and return a configured instance.
457 * @param String $type Type of search backend, if not the default
458 * @return SearchEngine
460 public static function create( $type = null ) {
461 global $wgSearchType;
464 $alternatives = self
::getSearchTypes();
466 if ( $type && in_array( $type, $alternatives ) ) {
468 } elseif ( $wgSearchType !== null ) {
469 $class = $wgSearchType;
471 $dbr = wfGetDB( DB_SLAVE
);
472 $class = $dbr->getSearchEngine();
475 $search = new $class( $dbr );
476 $search->setLimitOffset( 0, 0 );
481 * Return the search engines we support. If only $wgSearchType
482 * is set, it'll be an array of just that one item.
486 public static function getSearchTypes() {
487 global $wgSearchType, $wgSearchTypeAlternatives;
488 static $alternatives = null;
489 if ( $alternatives === null ) {
490 $alternatives = $wgSearchTypeAlternatives ?
: array();
491 array_unshift( $alternatives, $wgSearchType );
493 return $alternatives;
497 * Create or update the search index record for the given page.
498 * Title and text should be pre-processed.
502 * @param $title String
503 * @param $text String
505 function update( $id, $title, $text ) {
510 * Update a search index record's title only.
511 * Title should be pre-processed.
515 * @param $title String
517 function updateTitle( $id, $title ) {
522 * Delete an indexed page
523 * Title should be pre-processed.
526 * @param Integer $id Page id that was deleted
527 * @param String $title Title of page that was deleted
529 function delete( $id, $title ) {
534 * Get OpenSearch suggestion template
538 public static function getOpenSearchTemplate() {
539 global $wgOpenSearchTemplate, $wgCanonicalServer;
540 if ( $wgOpenSearchTemplate ) {
541 return $wgOpenSearchTemplate;
543 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
547 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
552 * Get the raw text for updating the index from a content object
553 * Nicer search backends could possibly do something cooler than
554 * just returning raw text
556 * @todo This isn't ideal, we'd really like to have content-specific handling here
557 * @param Title $t Title we're indexing
558 * @param Content $c Content of the page to index
561 public function getTextFromContent( Title
$t, Content
$c = null ) {
562 return $c ?
$c->getTextForSearchIndex() : '';
566 * If an implementation of SearchEngine handles all of its own text processing
567 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
568 * rather silly handling, it should return true here instead.
572 public function textAlreadyUpdatedForIndex() {
580 class SearchResultSet
{
582 * Fetch an array of regular expression fragments for matching
583 * the search terms as parsed by this engine in a text extract.
588 function termMatches() {
597 * Return true if results are included in this result set.
602 function hasResults() {
607 * Some search modes return a total hit count for the query
608 * in the entire article database. This may include pages
609 * in namespaces that would not be matched on the given
612 * Return null if no total hits number is supported.
616 function getTotalHits() {
621 * Some search modes return a suggested alternate term if there are
622 * no exact hits. Returns true if there is one on this set.
626 function hasSuggestion() {
631 * @return String: suggested query, null if none
633 function getSuggestionQuery() {
638 * @return String: HTML highlighted suggested query, '' if none
640 function getSuggestionSnippet() {
645 * Return information about how and from where the results were fetched,
646 * should be useful for diagnostics and debugging
655 * Return a result set of hits on other (multiple) wikis associated with this one
657 * @return SearchResultSet
659 function getInterwikiResults() {
664 * Check if there are results on other wikis
668 function hasInterwikiResults() {
669 return $this->getInterwikiResults() != null;
673 * Fetches next search result, or false.
676 * @return SearchResult
683 * Frees the result set, if applicable.
691 * This class is used for different SQL-based search engines shipped with MediaWiki
693 class SqlSearchResultSet
extends SearchResultSet
{
695 protected $mResultSet;
697 function __construct( $resultSet, $terms ) {
698 $this->mResultSet
= $resultSet;
699 $this->mTerms
= $terms;
702 function termMatches() {
703 return $this->mTerms
;
707 if ( $this->mResultSet
=== false ) {
711 return $this->mResultSet
->numRows();
715 if ( $this->mResultSet
=== false ) {
719 $row = $this->mResultSet
->fetchObject();
720 if ( $row === false ) {
724 return SearchResult
::newFromRow( $row );
728 if ( $this->mResultSet
=== false ) {
732 $this->mResultSet
->free();
739 class SearchResultTooMany
{
740 # # Some search engines may bail out if too many matches are found
744 * @todo FIXME: This class is horribly factored. It would probably be better to
745 * have a useful base class to which you pass some standard information, then
746 * let the fancy self-highlighters extend that.
754 var $mRevision = null;
768 * Return a new SearchResult and initializes it with a title.
770 * @param $title Title
771 * @return SearchResult
773 public static function newFromTitle( $title ) {
774 $result = new self();
775 $result->initFromTitle( $title );
779 * Return a new SearchResult and initializes it with a row.
782 * @return SearchResult
784 public static function newFromRow( $row ) {
785 $result = new self();
786 $result->initFromRow( $row );
790 public function __construct( $row = null ) {
791 if ( !is_null( $row ) ) {
792 // Backwards compatibility with pre-1.17 callers
793 $this->initFromRow( $row );
798 * Initialize from a database row. Makes a Title and passes that to
803 protected function initFromRow( $row ) {
804 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
808 * Initialize from a Title and if possible initializes a corresponding
811 * @param $title Title
813 protected function initFromTitle( $title ) {
814 $this->mTitle
= $title;
815 if ( !is_null( $this->mTitle
) ) {
817 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
818 $this->mRevision
= Revision
::newFromTitle(
819 $this->mTitle
, $id, Revision
::READ_NORMAL
);
820 if ( $this->mTitle
->getNamespace() === NS_FILE
) {
821 $this->mImage
= wfFindFile( $this->mTitle
);
827 * Check if this is result points to an invalid title
831 function isBrokenTitle() {
832 if ( is_null( $this->mTitle
) ) {
839 * Check if target page is missing, happens when index is out of date
843 function isMissingRevision() {
844 return !$this->mRevision
&& !$this->mImage
;
850 function getTitle() {
851 return $this->mTitle
;
855 * @return float|null if not supported
857 function getScore() {
862 * Lazy initialization of article text from DB
864 protected function initText() {
865 if ( !isset( $this->mText
) ) {
866 if ( $this->mRevision
!= null ) {
867 $this->mText
= SearchEngine
::create()
868 ->getTextFromContent( $this->mTitle
, $this->mRevision
->getContent() );
869 } else { // TODO: can we fetch raw wikitext for commons images?
876 * @param array $terms terms to highlight
877 * @return String: highlighted text snippet, null (and not '') if not supported
879 function getTextSnippet( $terms ) {
880 global $wgUser, $wgAdvancedSearchHighlighting;
883 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
884 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
885 $h = new SearchHighlighter();
886 if ( $wgAdvancedSearchHighlighting ) {
887 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
889 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
894 * @param array $terms terms to highlight
895 * @return String: highlighted title, '' if not supported
897 function getTitleSnippet( $terms ) {
902 * @param array $terms terms to highlight
903 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
905 function getRedirectSnippet( $terms ) {
910 * @return Title object for the redirect to this page, null if none or not supported
912 function getRedirectTitle() {
917 * @return string highlighted relevant section name, null if none or not supported
919 function getSectionSnippet() {
924 * @return Title object (pagename+fragment) for the section, null if none or not supported
926 function getSectionTitle() {
931 * @return String: timestamp
933 function getTimestamp() {
934 if ( $this->mRevision
) {
935 return $this->mRevision
->getTimestamp();
936 } elseif ( $this->mImage
) {
937 return $this->mImage
->getTimestamp();
943 * @return Integer: number of words
945 function getWordCount() {
947 return str_word_count( $this->mText
);
951 * @return Integer: size in bytes
953 function getByteSize() {
955 return strlen( $this->mText
);
959 * @return Boolean if hit has related articles
961 function hasRelated() {
966 * @return String: interwiki prefix of the title (return iw even if title is broken)
968 function getInterwikiPrefix() {
973 * A SearchResultSet wrapper for SearchEngine::getNearMatch
975 class SearchNearMatchResultSet
extends SearchResultSet
{
976 private $fetched = false;
978 * @param $match mixed Title if matched, else null
980 public function __construct( $match ) {
981 $this->result
= $match;
983 public function hasResult() {
984 return (bool)$this->result
;
986 public function numRows() {
987 return $this->hasResults() ?
1 : 0;
989 public function next() {
990 if ( $this->fetched ||
!$this->result
) {
993 $this->fetched
= true;
994 return SearchResult
::newFromTitle( $this->result
);
999 * Highlight bits of wikitext
1003 class SearchHighlighter
{
1004 var $mCleanWikitext = true;
1006 function __construct( $cleanupWikitext = true ) {
1007 $this->mCleanWikitext
= $cleanupWikitext;
1011 * Default implementation of wikitext highlighting
1013 * @param $text String
1014 * @param array $terms terms to highlight (unescaped)
1015 * @param $contextlines Integer
1016 * @param $contextchars Integer
1019 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
1021 global $wgSearchHighlightBoundaries;
1022 $fname = __METHOD__
;
1024 if ( $text == '' ) {
1028 // spli text into text + templates/links/tables
1029 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
1030 // first capture group is for detecting nested templates/links/tables/references
1031 $endPatterns = array(
1032 1 => '/(\{\{)|(\}\})/', // template
1033 2 => '/(\[\[)|(\]\])/', // image
1034 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
1036 // @todo FIXME: This should prolly be a hook or something
1037 if ( function_exists( 'wfCite' ) ) {
1038 $spat .= '|(<ref>)'; // references via cite extension
1039 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
1042 $textExt = array(); // text extracts
1043 $otherExt = array(); // other extracts
1044 wfProfileIn( "$fname-split" );
1046 $textLen = strlen( $text );
1047 $count = 0; // sequence number to maintain ordering
1048 while ( $start < $textLen ) {
1049 // find start of template/image/table
1050 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
1052 foreach ( $matches as $key => $val ) {
1053 if ( $key > 0 && $val[1] != - 1 ) {
1055 // see if this is an image link
1056 $ns = substr( $val[0], 2, - 1 );
1057 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
) {
1062 $epat = $endPatterns[$key];
1063 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1069 // find end (and detect any nested elements)
1071 $offset = $start +
1;
1073 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
1074 if ( array_key_exists( 2, $endMatches ) ) {
1076 if ( $level == 0 ) {
1077 $len = strlen( $endMatches[2][0] );
1078 $off = $endMatches[2][1];
1079 $this->splitAndAdd( $otherExt, $count,
1080 substr( $text, $start, $off +
$len - $start ) );
1081 $start = $off +
$len;
1085 // end of nested element
1092 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
1095 // couldn't find appropriate closing tag, skip
1096 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1097 $start +
= strlen( $matches[0][0] );
1102 // else: add as text extract
1103 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1107 $all = $textExt +
$otherExt; // these have disjunct key sets
1109 wfProfileOut( "$fname-split" );
1112 foreach ( $terms as $index => $term ) {
1113 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1114 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1115 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1117 $terms[$index] = $term;
1120 $anyterm = implode( '|', $terms );
1121 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1123 // @todo FIXME: A hack to scale contextchars, a correct solution
1124 // would be to have contextchars actually be char and not byte
1125 // length, and do proper utf-8 substrings and lengths everywhere,
1126 // but PHP is making that very hard and unclean to implement :(
1127 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1128 $contextchars = intval( $contextchars * $scale );
1130 $patPre = "(^|$wgSearchHighlightBoundaries)";
1131 $patPost = "($wgSearchHighlightBoundaries|$)";
1133 $pat1 = "/(" . $phrase . ")/ui";
1134 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1136 wfProfileIn( "$fname-extract" );
1138 $left = $contextlines;
1140 $snippets = array();
1143 // show beginning only if it contains all words
1146 foreach ( $textExt as $index => $line ) {
1147 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1148 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1155 // check if first text contains all terms
1156 foreach ( $terms as $term ) {
1157 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1163 $snippets[$first] = $firstText;
1164 $offsets[$first] = 0;
1167 if ( ! $snippets ) {
1168 // match whole query on text
1169 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1170 // match whole query on templates/tables/images
1171 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1172 // match any words on text
1173 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1174 // match any words on templates/tables/images
1175 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1180 // add extra chars to each snippet to make snippets constant size
1181 $extended = array();
1182 if ( count( $snippets ) == 0 ) {
1183 // couldn't find the target words, just show beginning of article
1184 if ( array_key_exists( $first, $all ) ) {
1185 $targetchars = $contextchars * $contextlines;
1186 $snippets[$first] = '';
1187 $offsets[$first] = 0;
1190 // if begin of the article contains the whole phrase, show only that !!
1191 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1192 && $offsets[$first] < $contextchars * 2 ) {
1193 $snippets = array( $first => $snippets[$first] );
1196 // calc by how much to extend existing snippets
1197 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1200 foreach ( $snippets as $index => $line ) {
1201 $extended[$index] = $line;
1202 $len = strlen( $line );
1203 if ( $len < $targetchars - 20 ) {
1204 // complete this line
1205 if ( $len < strlen( $all[$index] ) ) {
1206 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1207 $len = strlen( $extended[$index] );
1212 while ( $len < $targetchars - 20
1213 && array_key_exists( $add, $all )
1214 && !array_key_exists( $add, $snippets ) ) {
1216 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1217 $extended[$add] = $tt;
1218 $len +
= strlen( $tt );
1224 // $snippets = array_map( 'htmlspecialchars', $extended );
1225 $snippets = $extended;
1228 foreach ( $snippets as $index => $line ) {
1229 if ( $last == - 1 ) {
1230 $extract .= $line; // first line
1231 } elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) ) {
1232 $extract .= " " . $line; // continous lines
1234 $extract .= '<b> ... </b>' . $line;
1240 $extract .= '<b> ... </b>';
1243 $processed = array();
1244 foreach ( $terms as $term ) {
1245 if ( ! isset( $processed[$term] ) ) {
1246 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1247 $extract = preg_replace( $pat3,
1248 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1249 $processed[$term] = true;
1253 wfProfileOut( "$fname-extract" );
1259 * Split text into lines and add it to extracts array
1261 * @param array $extracts index -> $line
1262 * @param $count Integer
1263 * @param $text String
1265 function splitAndAdd( &$extracts, &$count, $text ) {
1266 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1267 foreach ( $split as $line ) {
1268 $tt = trim( $line );
1270 $extracts[$count++
] = $tt;
1276 * Do manual case conversion for non-ascii chars
1278 * @param $matches Array
1281 function caseCallback( $matches ) {
1283 if ( strlen( $matches[0] ) > 1 ) {
1284 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1291 * Extract part of the text from start to end, but by
1292 * not chopping up words
1293 * @param $text String
1294 * @param $start Integer
1295 * @param $end Integer
1296 * @param $posStart Integer: (out) actual start position
1297 * @param $posEnd Integer: (out) actual end position
1300 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1301 if ( $start != 0 ) {
1302 $start = $this->position( $text, $start, 1 );
1304 if ( $end >= strlen( $text ) ) {
1305 $end = strlen( $text );
1307 $end = $this->position( $text, $end );
1310 if ( !is_null( $posStart ) ) {
1313 if ( !is_null( $posEnd ) ) {
1317 if ( $end > $start ) {
1318 return substr( $text, $start, $end - $start );
1325 * Find a nonletter near a point (index) in the text
1327 * @param $text String
1328 * @param $point Integer
1329 * @param $offset Integer: offset to found index
1330 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1332 function position( $text, $point, $offset = 0 ) {
1334 $s = max( 0, $point - $tolerance );
1335 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1337 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1338 return $m[0][1] +
$s +
$offset;
1340 // check if point is on a valid first UTF8 char
1341 $char = ord( $text[$point] );
1342 while ( $char >= 0x80 && $char < 0xc0 ) {
1343 // skip trailing bytes
1345 if ( $point >= strlen( $text ) ) {
1346 return strlen( $text );
1348 $char = ord( $text[$point] );
1356 * Search extracts for a pattern, and return snippets
1358 * @param string $pattern regexp for matching lines
1359 * @param array $extracts extracts to search
1360 * @param $linesleft Integer: number of extracts to make
1361 * @param $contextchars Integer: length of snippet
1362 * @param array $out map for highlighted snippets
1363 * @param array $offsets map of starting points of snippets
1366 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1367 if ( $linesleft == 0 ) {
1368 return; // nothing to do
1370 foreach ( $extracts as $index => $line ) {
1371 if ( array_key_exists( $index, $out ) ) {
1372 continue; // this line already highlighted
1376 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) ) {
1381 $len = strlen( $m[0][0] );
1382 if ( $offset +
$len < $contextchars ) {
1384 } elseif ( $len > $contextchars ) {
1387 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1390 $end = $begin +
$contextchars;
1393 // basic snippet from this line
1394 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1395 $offsets[$index] = $posBegin;
1397 if ( $linesleft == 0 ) {
1404 * Basic wikitext removal
1408 function removeWiki( $text ) {
1409 $fname = __METHOD__
;
1410 wfProfileIn( $fname );
1412 // $text = preg_replace( "/'{2,5}/", "", $text );
1413 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1414 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1415 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1416 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1417 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1418 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1419 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1420 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1421 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1422 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1423 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1424 $text = preg_replace( "/'''''/", "", $text );
1425 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1426 $text = preg_replace( "/''/", "", $text );
1428 wfProfileOut( $fname );
1433 * callback to replace [[target|caption]] kind of links, if
1434 * the target is category or image, leave it
1436 * @param $matches Array
1438 function linkReplace( $matches ) {
1439 $colon = strpos( $matches[1], ':' );
1440 if ( $colon === false ) {
1441 return $matches[2]; // replace with caption
1444 $ns = substr( $matches[1], 0, $colon );
1445 $index = $wgContLang->getNsIndex( $ns );
1446 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) ) {
1447 return $matches[0]; // return the whole thing
1454 * Simple & fast snippet extraction, but gives completely unrelevant
1457 * @param $text String
1458 * @param $terms Array
1459 * @param $contextlines Integer
1460 * @param $contextchars Integer
1463 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1465 $fname = __METHOD__
;
1467 $lines = explode( "\n", $text );
1469 $terms = implode( '|', $terms );
1470 $max = intval( $contextchars ) +
1;
1471 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1476 wfProfileIn( "$fname-extract" );
1477 foreach ( $lines as $line ) {
1478 if ( 0 == $contextlines ) {
1483 if ( ! preg_match( $pat1, $line, $m ) ) {
1487 // truncate function changes ... to relevant i18n message.
1488 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1490 if ( count( $m ) < 3 ) {
1493 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1498 $line = htmlspecialchars( $pre . $found . $post );
1499 $pat2 = '/(' . $terms . ")/i";
1500 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1502 $extract .= "${line}\n";
1504 wfProfileOut( "$fname-extract" );
1512 * Dummy class to be used when non-supported Database engine is present.
1513 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1514 * such as a LIKE search through titles.
1517 class SearchEngineDummy
extends SearchEngine
{