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 $term String: raw search term
62 * @return SearchResultSet
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 $term String: raw search term
74 * @return SearchResultSet
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':
99 case 'title-suffix-filter':
106 * Way to pass custom data for engines
108 * @param $feature String
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
124 public function normalizeText( $string ) {
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 ) {
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
146 public static function getNearMatch( $searchterm ) {
147 $title = self
::getNearMatchInternal( $searchterm );
149 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
154 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
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 ) );
178 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
182 foreach ( $allSearchTerms as $term ) {
184 # Exact match? No need to look further.
185 $title = Title
::newFromText( $term );
186 if ( is_null( $title ) ){
190 if ( $title->isSpecialPage() ||
$title->isExternal() ||
$title->exists() ) {
194 # See if it still otherwise has content is some sane sense
195 $page = WikiPage
::factory( $title );
196 if ( $page->hasViewableContent() ) {
200 # Now try all lower case (i.e. first letter capitalized)
202 $title = Title
::newFromText( $wgContLang->lc( $term ) );
203 if ( $title && $title->exists() ) {
207 # Now try capitalized string
209 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
210 if ( $title && $title->exists() ) {
214 # Now try all upper case
216 $title = Title
::newFromText( $wgContLang->uc( $term ) );
217 if ( $title && $title->exists() ) {
221 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
222 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
223 if ( $title && $title->exists() ) {
227 // Give hooks a chance at better match variants
229 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
234 $title = Title
::newFromText( $searchterm );
237 # Entering an IP address goes to the contributions page
238 if ( $wgEnableSearchContributorsByIP ) {
239 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
240 || User
::isIP( trim( $searchterm ) ) ) {
241 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
246 # Entering a user goes to the user page whether it's there or not
247 if ( $title->getNamespace() == NS_USER
) {
251 # Go to images that exist even if there's no local page.
252 # There may have been a funny upload, or it may be on a shared
253 # file repository such as Wikimedia Commons.
254 if ( $title->getNamespace() == NS_FILE
) {
255 $image = wfFindFile( $title );
261 # MediaWiki namespace? Page may be "implied" if not customized.
262 # Just return it, with caps forced as the message system likes it.
263 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
264 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
267 # Quoted term? Try without the quotes...
269 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
270 return SearchEngine
::getNearMatch( $matches[1] );
276 public static function legalSearchChars() {
277 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
281 * Set the maximum number of results to return
282 * and how many to skip before returning the first.
284 * @param $limit Integer
285 * @param $offset Integer
287 function setLimitOffset( $limit, $offset = 0 ) {
288 $this->limit
= intval( $limit );
289 $this->offset
= intval( $offset );
293 * Set which namespaces the search should include.
294 * Give an array of namespace index numbers.
296 * @param $namespaces Array
298 function setNamespaces( $namespaces ) {
299 $this->namespaces
= $namespaces;
303 * Parse some common prefixes: all (search everything)
306 * @param $query String
309 function replacePrefixes( $query ) {
313 if ( strpos( $query, ':' ) === false ) { // nothing to do
314 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
318 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
319 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
320 $this->namespaces
= null;
321 $parsed = substr( $query, strlen( $allkeyword ) );
322 } elseif ( strpos( $query, ':' ) !== false ) {
323 $prefix = substr( $query, 0, strpos( $query, ':' ) );
324 $index = $wgContLang->getNsIndex( $prefix );
325 if ( $index !== false ) {
326 $this->namespaces
= array( $index );
327 $parsed = substr( $query, strlen( $prefix ) +
1 );
330 if ( trim( $parsed ) == '' )
331 $parsed = $query; // prefix was the whole query
333 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
339 * Make a list of searchable namespaces and their canonical names.
342 public static function searchableNamespaces() {
345 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
346 if ( $ns >= NS_MAIN
) {
351 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
356 * Extract default namespaces to search from the given user's
357 * settings, returning a list of index numbers.
362 public static function userNamespaces( $user ) {
363 global $wgSearchEverythingOnlyLoggedIn;
365 $searchableNamespaces = SearchEngine
::searchableNamespaces();
367 // get search everything preference, that can be set to be read for logged-in users
368 // it overrides other options
369 if ( !$wgSearchEverythingOnlyLoggedIn ||
$user->isLoggedIn() ) {
370 if ( $user->getOption( 'searcheverything' ) ) {
371 return array_keys( $searchableNamespaces );
376 foreach ( $searchableNamespaces as $ns => $name ) {
377 if ( $user->getOption( 'searchNs' . $ns ) ) {
386 * Find snippet highlight settings for all users
388 * @return Array contextlines, contextchars
390 public static function userHighlightPrefs() {
391 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
392 $contextchars = 75; // same as above.... :P
393 return array( $contextlines, $contextchars );
397 * An array of namespaces indexes to be searched by default
401 public static function defaultNamespaces() {
402 global $wgNamespacesToBeSearchedDefault;
404 return array_keys( $wgNamespacesToBeSearchedDefault, true );
408 * Get a list of namespace names useful for showing in tooltips
411 * @param $namespaces Array
414 public static function namespacesAsText( $namespaces ) {
417 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
418 foreach ( $formatted as $key => $ns ) {
420 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
426 * Return the help namespaces to be shown on Special:Search
430 public static function helpNamespaces() {
431 global $wgNamespacesToBeSearchedHelp;
433 return array_keys( $wgNamespacesToBeSearchedHelp, true );
437 * Return a 'cleaned up' search string
439 * @param $text String
442 function filter( $text ) {
443 $lc = $this->legalSearchChars();
444 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
447 * Load up the appropriate search engine class for the currently
448 * active database backend, and return a configured instance.
450 * @return SearchEngine
452 public static function create() {
453 global $wgSearchType;
455 if ( $wgSearchType ) {
456 $class = $wgSearchType;
458 $dbr = wfGetDB( DB_SLAVE
);
459 $class = $dbr->getSearchEngine();
461 $search = new $class( $dbr );
462 $search->setLimitOffset( 0, 0 );
467 * Create or update the search index record for the given page.
468 * Title and text should be pre-processed.
472 * @param $title String
473 * @param $text String
475 function update( $id, $title, $text ) {
480 * Update a search index record's title only.
481 * Title should be pre-processed.
485 * @param $title String
487 function updateTitle( $id, $title ) {
492 * Get OpenSearch suggestion template
496 public static function getOpenSearchTemplate() {
497 global $wgOpenSearchTemplate, $wgCanonicalServer;
498 if ( $wgOpenSearchTemplate ) {
499 return $wgOpenSearchTemplate;
501 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
505 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
510 * Get internal MediaWiki Suggest template
514 public static function getMWSuggestTemplate() {
515 global $wgMWSuggestTemplate, $wgServer;
516 if ( $wgMWSuggestTemplate )
517 return $wgMWSuggestTemplate;
519 return $wgServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
526 class SearchResultSet
{
528 * Fetch an array of regular expression fragments for matching
529 * the search terms as parsed by this engine in a text extract.
534 function termMatches() {
543 * Return true if results are included in this result set.
548 function hasResults() {
553 * Some search modes return a total hit count for the query
554 * in the entire article database. This may include pages
555 * in namespaces that would not be matched on the given
558 * Return null if no total hits number is supported.
562 function getTotalHits() {
567 * Some search modes return a suggested alternate term if there are
568 * no exact hits. Returns true if there is one on this set.
572 function hasSuggestion() {
577 * @return String: suggested query, null if none
579 function getSuggestionQuery() {
584 * @return String: HTML highlighted suggested query, '' if none
586 function getSuggestionSnippet() {
591 * Return information about how and from where the results were fetched,
592 * should be useful for diagnostics and debugging
601 * Return a result set of hits on other (multiple) wikis associated with this one
603 * @return SearchResultSet
605 function getInterwikiResults() {
610 * Check if there are results on other wikis
614 function hasInterwikiResults() {
615 return $this->getInterwikiResults() != null;
619 * Fetches next search result, or false.
622 * @return SearchResult
629 * Frees the result set, if applicable.
637 * This class is used for different SQL-based search engines shipped with MediaWiki
639 class SqlSearchResultSet
extends SearchResultSet
{
641 protected $mResultSet;
643 function __construct( $resultSet, $terms ) {
644 $this->mResultSet
= $resultSet;
645 $this->mTerms
= $terms;
648 function termMatches() {
649 return $this->mTerms
;
653 if ( $this->mResultSet
=== false )
656 return $this->mResultSet
->numRows();
660 if ( $this->mResultSet
=== false )
663 $row = $this->mResultSet
->fetchObject();
664 if ( $row === false )
667 return SearchResult
::newFromRow( $row );
671 if ( $this->mResultSet
=== false )
674 $this->mResultSet
->free();
681 class SearchResultTooMany
{
682 # # Some search engines may bail out if too many matches are found
687 * @todo FIXME: This class is horribly factored. It would probably be better to
688 * have a useful base class to which you pass some standard information, then
689 * let the fancy self-highlighters extend that.
697 var $mRevision = null;
711 * Return a new SearchResult and initializes it with a title.
713 * @param $title Title
714 * @return SearchResult
716 public static function newFromTitle( $title ) {
717 $result = new self();
718 $result->initFromTitle( $title );
722 * Return a new SearchResult and initializes it with a row.
725 * @return SearchResult
727 public static function newFromRow( $row ) {
728 $result = new self();
729 $result->initFromRow( $row );
733 public function __construct( $row = null ) {
734 if ( !is_null( $row ) ) {
735 // Backwards compatibility with pre-1.17 callers
736 $this->initFromRow( $row );
741 * Initialize from a database row. Makes a Title and passes that to
746 protected function initFromRow( $row ) {
747 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
751 * Initialize from a Title and if possible initializes a corresponding
754 * @param $title Title
756 protected function initFromTitle( $title ) {
757 $this->mTitle
= $title;
758 if ( !is_null( $this->mTitle
) ) {
760 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
761 $this->mRevision
= Revision
::newFromTitle(
762 $this->mTitle
, $id, Revision
::READ_NORMAL
);
763 if ( $this->mTitle
->getNamespace() === NS_FILE
)
764 $this->mImage
= wfFindFile( $this->mTitle
);
769 * Check if this is result points to an invalid title
773 function isBrokenTitle() {
774 if ( is_null( $this->mTitle
) )
780 * Check if target page is missing, happens when index is out of date
784 function isMissingRevision() {
785 return !$this->mRevision
&& !$this->mImage
;
791 function getTitle() {
792 return $this->mTitle
;
796 * @return float|null if not supported
798 function getScore() {
803 * Lazy initialization of article text from DB
805 protected function initText() {
806 if ( !isset( $this->mText
) ) {
807 if ( $this->mRevision
!= null ) {
808 //TODO: if we could plug in some code that knows about special content models *and* about
809 // special features of the search engine, the search could benefit.
810 $content = $this->mRevision
->getContent();
811 $this->mText
= $content->getTextForSearchIndex();
812 } else { // TODO: can we fetch raw wikitext for commons images?
819 * @param $terms Array: terms to highlight
820 * @return String: highlighted text snippet, null (and not '') if not supported
822 function getTextSnippet( $terms ) {
823 global $wgUser, $wgAdvancedSearchHighlighting;
826 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
827 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
828 $h = new SearchHighlighter();
829 if ( $wgAdvancedSearchHighlighting )
830 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
832 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
836 * @param $terms Array: terms to highlight
837 * @return String: highlighted title, '' if not supported
839 function getTitleSnippet( $terms ) {
844 * @param $terms Array: terms to highlight
845 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
847 function getRedirectSnippet( $terms ) {
852 * @return Title object for the redirect to this page, null if none or not supported
854 function getRedirectTitle() {
859 * @return string highlighted relevant section name, null if none or not supported
861 function getSectionSnippet() {
866 * @return Title object (pagename+fragment) for the section, null if none or not supported
868 function getSectionTitle() {
873 * @return String: timestamp
875 function getTimestamp() {
876 if ( $this->mRevision
)
877 return $this->mRevision
->getTimestamp();
878 elseif ( $this->mImage
)
879 return $this->mImage
->getTimestamp();
884 * @return Integer: number of words
886 function getWordCount() {
888 return str_word_count( $this->mText
);
892 * @return Integer: size in bytes
894 function getByteSize() {
896 return strlen( $this->mText
);
900 * @return Boolean if hit has related articles
902 function hasRelated() {
907 * @return String: interwiki prefix of the title (return iw even if title is broken)
909 function getInterwikiPrefix() {
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
) {
934 $this->fetched
= true;
935 return SearchResult
::newFromTitle( $this->result
);
940 * Highlight bits of wikitext
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 $terms Array: terms to highlight (unescaped)
956 * @param $contextlines Integer
957 * @param $contextchars Integer
960 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
962 global $wgSearchHighlightBoundaries;
968 // spli text into text + templates/links/tables
969 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
970 // first capture group is for detecting nested templates/links/tables/references
971 $endPatterns = array(
972 1 => '/(\{\{)|(\}\})/', // template
973 2 => '/(\[\[)|(\]\])/', // image
974 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
976 // @todo FIXME: This should prolly be a hook or something
977 if ( function_exists( 'wfCite' ) ) {
978 $spat .= '|(<ref>)'; // references via cite extension
979 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
982 $textExt = array(); // text extracts
983 $otherExt = array(); // other extracts
984 wfProfileIn( "$fname-split" );
986 $textLen = strlen( $text );
987 $count = 0; // sequence number to maintain ordering
988 while ( $start < $textLen ) {
989 // find start of template/image/table
990 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
992 foreach ( $matches as $key => $val ) {
993 if ( $key > 0 && $val[1] != - 1 ) {
995 // see if this is an image link
996 $ns = substr( $val[0], 2, - 1 );
997 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
)
1001 $epat = $endPatterns[$key];
1002 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1008 // find end (and detect any nested elements)
1010 $offset = $start +
1;
1012 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
1013 if ( array_key_exists( 2, $endMatches ) ) {
1015 if ( $level == 0 ) {
1016 $len = strlen( $endMatches[2][0] );
1017 $off = $endMatches[2][1];
1018 $this->splitAndAdd( $otherExt, $count,
1019 substr( $text, $start, $off +
$len - $start ) );
1020 $start = $off +
$len;
1024 // end of nested element
1031 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
1034 // couldn't find appropriate closing tag, skip
1035 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1036 $start +
= strlen( $matches[0][0] );
1041 // else: add as text extract
1042 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1046 $all = $textExt +
$otherExt; // these have disjunct key sets
1048 wfProfileOut( "$fname-split" );
1051 foreach ( $terms as $index => $term ) {
1052 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1053 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1054 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1056 $terms[$index] = $term;
1059 $anyterm = implode( '|', $terms );
1060 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1062 // @todo FIXME: A hack to scale contextchars, a correct solution
1063 // would be to have contextchars actually be char and not byte
1064 // length, and do proper utf-8 substrings and lengths everywhere,
1065 // but PHP is making that very hard and unclean to implement :(
1066 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1067 $contextchars = intval( $contextchars * $scale );
1069 $patPre = "(^|$wgSearchHighlightBoundaries)";
1070 $patPost = "($wgSearchHighlightBoundaries|$)";
1072 $pat1 = "/(" . $phrase . ")/ui";
1073 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1075 wfProfileIn( "$fname-extract" );
1077 $left = $contextlines;
1079 $snippets = array();
1082 // show beginning only if it contains all words
1085 foreach ( $textExt as $index => $line ) {
1086 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1087 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1094 // check if first text contains all terms
1095 foreach ( $terms as $term ) {
1096 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1102 $snippets[$first] = $firstText;
1103 $offsets[$first] = 0;
1106 if ( ! $snippets ) {
1107 // match whole query on text
1108 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1109 // match whole query on templates/tables/images
1110 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1111 // match any words on text
1112 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1113 // match any words on templates/tables/images
1114 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1119 // add extra chars to each snippet to make snippets constant size
1120 $extended = array();
1121 if ( count( $snippets ) == 0 ) {
1122 // couldn't find the target words, just show beginning of article
1123 if ( array_key_exists( $first, $all ) ) {
1124 $targetchars = $contextchars * $contextlines;
1125 $snippets[$first] = '';
1126 $offsets[$first] = 0;
1129 // if begin of the article contains the whole phrase, show only that !!
1130 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1131 && $offsets[$first] < $contextchars * 2 ) {
1132 $snippets = array ( $first => $snippets[$first] );
1135 // calc by how much to extend existing snippets
1136 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1139 foreach ( $snippets as $index => $line ) {
1140 $extended[$index] = $line;
1141 $len = strlen( $line );
1142 if ( $len < $targetchars - 20 ) {
1143 // complete this line
1144 if ( $len < strlen( $all[$index] ) ) {
1145 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1146 $len = strlen( $extended[$index] );
1151 while ( $len < $targetchars - 20
1152 && array_key_exists( $add, $all )
1153 && !array_key_exists( $add, $snippets ) ) {
1155 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1156 $extended[$add] = $tt;
1157 $len +
= strlen( $tt );
1163 // $snippets = array_map('htmlspecialchars', $extended);
1164 $snippets = $extended;
1167 foreach ( $snippets as $index => $line ) {
1169 $extract .= $line; // first line
1170 elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1171 $extract .= " " . $line; // continous lines
1173 $extract .= '<b> ... </b>' . $line;
1178 $extract .= '<b> ... </b>';
1180 $processed = array();
1181 foreach ( $terms as $term ) {
1182 if ( ! isset( $processed[$term] ) ) {
1183 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1184 $extract = preg_replace( $pat3,
1185 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1186 $processed[$term] = true;
1190 wfProfileOut( "$fname-extract" );
1196 * Split text into lines and add it to extracts array
1198 * @param $extracts Array: index -> $line
1199 * @param $count Integer
1200 * @param $text String
1202 function splitAndAdd( &$extracts, &$count, $text ) {
1203 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1204 foreach ( $split as $line ) {
1205 $tt = trim( $line );
1207 $extracts[$count++
] = $tt;
1212 * Do manual case conversion for non-ascii chars
1214 * @param $matches Array
1217 function caseCallback( $matches ) {
1219 if ( strlen( $matches[0] ) > 1 ) {
1220 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1227 * Extract part of the text from start to end, but by
1228 * not chopping up words
1229 * @param $text String
1230 * @param $start Integer
1231 * @param $end Integer
1232 * @param $posStart Integer: (out) actual start position
1233 * @param $posEnd Integer: (out) actual end position
1236 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1237 if ( $start != 0 ) {
1238 $start = $this->position( $text, $start, 1 );
1240 if ( $end >= strlen( $text ) ) {
1241 $end = strlen( $text );
1243 $end = $this->position( $text, $end );
1246 if ( !is_null( $posStart ) ) {
1249 if ( !is_null( $posEnd ) ) {
1253 if ( $end > $start ) {
1254 return substr( $text, $start, $end - $start );
1261 * Find a nonletter near a point (index) in the text
1263 * @param $text String
1264 * @param $point Integer
1265 * @param $offset Integer: offset to found index
1266 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1268 function position( $text, $point, $offset = 0 ) {
1270 $s = max( 0, $point - $tolerance );
1271 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1273 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1274 return $m[0][1] +
$s +
$offset;
1276 // check if point is on a valid first UTF8 char
1277 $char = ord( $text[$point] );
1278 while ( $char >= 0x80 && $char < 0xc0 ) {
1279 // skip trailing bytes
1281 if ( $point >= strlen( $text ) )
1282 return strlen( $text );
1283 $char = ord( $text[$point] );
1291 * Search extracts for a pattern, and return snippets
1293 * @param $pattern String: regexp for matching lines
1294 * @param $extracts Array: extracts to search
1295 * @param $linesleft Integer: number of extracts to make
1296 * @param $contextchars Integer: length of snippet
1297 * @param $out Array: map for highlighted snippets
1298 * @param $offsets Array: map of starting points of snippets
1301 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1302 if ( $linesleft == 0 )
1303 return; // nothing to do
1304 foreach ( $extracts as $index => $line ) {
1305 if ( array_key_exists( $index, $out ) )
1306 continue; // this line already highlighted
1309 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1313 $len = strlen( $m[0][0] );
1314 if ( $offset +
$len < $contextchars )
1316 elseif ( $len > $contextchars )
1319 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1321 $end = $begin +
$contextchars;
1324 // basic snippet from this line
1325 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1326 $offsets[$index] = $posBegin;
1328 if ( $linesleft == 0 )
1334 * Basic wikitext removal
1338 function removeWiki( $text ) {
1339 $fname = __METHOD__
;
1340 wfProfileIn( $fname );
1342 // $text = preg_replace("/'{2,5}/", "", $text);
1343 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1344 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1345 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1346 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1347 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1348 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1349 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1350 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1351 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1352 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1353 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1354 $text = preg_replace( "/'''''/", "", $text );
1355 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1356 $text = preg_replace( "/''/", "", $text );
1358 wfProfileOut( $fname );
1363 * callback to replace [[target|caption]] kind of links, if
1364 * the target is category or image, leave it
1366 * @param $matches Array
1368 function linkReplace( $matches ) {
1369 $colon = strpos( $matches[1], ':' );
1370 if ( $colon === false )
1371 return $matches[2]; // replace with caption
1373 $ns = substr( $matches[1], 0, $colon );
1374 $index = $wgContLang->getNsIndex( $ns );
1375 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) )
1376 return $matches[0]; // return the whole thing
1383 * Simple & fast snippet extraction, but gives completely unrelevant
1386 * @param $text String
1387 * @param $terms Array
1388 * @param $contextlines Integer
1389 * @param $contextchars Integer
1392 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1394 $fname = __METHOD__
;
1396 $lines = explode( "\n", $text );
1398 $terms = implode( '|', $terms );
1399 $max = intval( $contextchars ) +
1;
1400 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1405 wfProfileIn( "$fname-extract" );
1406 foreach ( $lines as $line ) {
1407 if ( 0 == $contextlines ) {
1412 if ( ! preg_match( $pat1, $line, $m ) ) {
1416 // truncate function changes ... to relevant i18n message.
1417 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1419 if ( count( $m ) < 3 ) {
1422 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1427 $line = htmlspecialchars( $pre . $found . $post );
1428 $pat2 = '/(' . $terms . ")/i";
1429 $line = preg_replace( $pat2,
1430 "<span class='searchmatch'>\\1</span>", $line );
1432 $extract .= "${line}\n";
1434 wfProfileOut( "$fname-extract" );
1442 * Dummy class to be used when non-supported Database engine is present.
1443 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1444 * such as a LIKE search through titles.
1447 class SearchEngineDummy
extends SearchEngine
{