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.
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 # Try files if searching in the Media: namespace
191 if ( $title->getNamespace() == NS_MEDIA
) {
192 $title = Title
::makeTitle( NS_FILE
, $title->getText() );
195 if ( $title->isSpecialPage() ||
$title->isExternal() ||
$title->exists() ) {
199 # See if it still otherwise has content is some sane sense
200 $page = WikiPage
::factory( $title );
201 if ( $page->hasViewableContent() ) {
205 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
209 # Now try all lower case (i.e. first letter capitalized)
210 $title = Title
::newFromText( $wgContLang->lc( $term ) );
211 if ( $title && $title->exists() ) {
215 # Now try capitalized string
216 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
217 if ( $title && $title->exists() ) {
221 # Now try all upper case
222 $title = Title
::newFromText( $wgContLang->uc( $term ) );
223 if ( $title && $title->exists() ) {
227 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
228 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
229 if ( $title && $title->exists() ) {
233 // Give hooks a chance at better match variants
235 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
240 $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() );
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 * Parse some common prefixes: all (search everything)
312 * @param $query String
315 function replacePrefixes( $query ) {
319 if ( strpos( $query, ':' ) === false ) { // nothing to do
320 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
324 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
325 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
326 $this->namespaces
= null;
327 $parsed = substr( $query, strlen( $allkeyword ) );
328 } elseif ( strpos( $query, ':' ) !== false ) {
329 $prefix = substr( $query, 0, strpos( $query, ':' ) );
330 $index = $wgContLang->getNsIndex( $prefix );
331 if ( $index !== false ) {
332 $this->namespaces
= array( $index );
333 $parsed = substr( $query, strlen( $prefix ) +
1 );
336 if ( trim( $parsed ) == '' )
337 $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 ) {
426 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
432 * Return the help namespaces to be shown on Special:Search
436 public static function helpNamespaces() {
437 global $wgNamespacesToBeSearchedHelp;
439 return array_keys( $wgNamespacesToBeSearchedHelp, true );
443 * Return a 'cleaned up' search string
445 * @param $text String
448 function filter( $text ) {
449 $lc = $this->legalSearchChars();
450 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
453 * Load up the appropriate search engine class for the currently
454 * active database backend, and return a configured instance.
456 * @return SearchEngine
458 public static function create() {
459 global $wgSearchType;
461 if ( $wgSearchType ) {
462 $class = $wgSearchType;
464 $dbr = wfGetDB( DB_SLAVE
);
465 $class = $dbr->getSearchEngine();
467 $search = new $class( $dbr );
468 $search->setLimitOffset( 0, 0 );
473 * Create or update the search index record for the given page.
474 * Title and text should be pre-processed.
478 * @param $title String
479 * @param $text String
481 function update( $id, $title, $text ) {
486 * Update a search index record's title only.
487 * Title should be pre-processed.
491 * @param $title String
493 function updateTitle( $id, $title ) {
498 * Get OpenSearch suggestion template
502 public static function getOpenSearchTemplate() {
503 global $wgOpenSearchTemplate, $wgCanonicalServer;
504 if ( $wgOpenSearchTemplate ) {
505 return $wgOpenSearchTemplate;
507 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
511 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
519 class SearchResultSet
{
521 * Fetch an array of regular expression fragments for matching
522 * the search terms as parsed by this engine in a text extract.
527 function termMatches() {
536 * Return true if results are included in this result set.
541 function hasResults() {
546 * Some search modes return a total hit count for the query
547 * in the entire article database. This may include pages
548 * in namespaces that would not be matched on the given
551 * Return null if no total hits number is supported.
555 function getTotalHits() {
560 * Some search modes return a suggested alternate term if there are
561 * no exact hits. Returns true if there is one on this set.
565 function hasSuggestion() {
570 * @return String: suggested query, null if none
572 function getSuggestionQuery() {
577 * @return String: HTML highlighted suggested query, '' if none
579 function getSuggestionSnippet() {
584 * Return information about how and from where the results were fetched,
585 * should be useful for diagnostics and debugging
594 * Return a result set of hits on other (multiple) wikis associated with this one
596 * @return SearchResultSet
598 function getInterwikiResults() {
603 * Check if there are results on other wikis
607 function hasInterwikiResults() {
608 return $this->getInterwikiResults() != null;
612 * Fetches next search result, or false.
615 * @return SearchResult
622 * Frees the result set, if applicable.
630 * This class is used for different SQL-based search engines shipped with MediaWiki
632 class SqlSearchResultSet
extends SearchResultSet
{
634 protected $mResultSet;
636 function __construct( $resultSet, $terms ) {
637 $this->mResultSet
= $resultSet;
638 $this->mTerms
= $terms;
641 function termMatches() {
642 return $this->mTerms
;
646 if ( $this->mResultSet
=== false )
649 return $this->mResultSet
->numRows();
653 if ( $this->mResultSet
=== false )
656 $row = $this->mResultSet
->fetchObject();
657 if ( $row === false )
660 return SearchResult
::newFromRow( $row );
664 if ( $this->mResultSet
=== false )
667 $this->mResultSet
->free();
674 class SearchResultTooMany
{
675 # # Some search engines may bail out if too many matches are found
680 * @todo FIXME: This class is horribly factored. It would probably be better to
681 * have a useful base class to which you pass some standard information, then
682 * let the fancy self-highlighters extend that.
690 var $mRevision = null;
704 * Return a new SearchResult and initializes it with a title.
706 * @param $title Title
707 * @return SearchResult
709 public static function newFromTitle( $title ) {
710 $result = new self();
711 $result->initFromTitle( $title );
715 * Return a new SearchResult and initializes it with a row.
718 * @return SearchResult
720 public static function newFromRow( $row ) {
721 $result = new self();
722 $result->initFromRow( $row );
726 public function __construct( $row = null ) {
727 if ( !is_null( $row ) ) {
728 // Backwards compatibility with pre-1.17 callers
729 $this->initFromRow( $row );
734 * Initialize from a database row. Makes a Title and passes that to
739 protected function initFromRow( $row ) {
740 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
744 * Initialize from a Title and if possible initializes a corresponding
747 * @param $title Title
749 protected function initFromTitle( $title ) {
750 $this->mTitle
= $title;
751 if ( !is_null( $this->mTitle
) ) {
753 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
754 $this->mRevision
= Revision
::newFromTitle(
755 $this->mTitle
, $id, Revision
::READ_NORMAL
);
756 if ( $this->mTitle
->getNamespace() === NS_FILE
)
757 $this->mImage
= wfFindFile( $this->mTitle
);
762 * Check if this is result points to an invalid title
766 function isBrokenTitle() {
767 if ( is_null( $this->mTitle
) )
773 * Check if target page is missing, happens when index is out of date
777 function isMissingRevision() {
778 return !$this->mRevision
&& !$this->mImage
;
784 function getTitle() {
785 return $this->mTitle
;
789 * @return float|null if not supported
791 function getScore() {
796 * Lazy initialization of article text from DB
798 protected function initText() {
799 if ( !isset( $this->mText
) ) {
800 if ( $this->mRevision
!= null ) {
801 //TODO: if we could plug in some code that knows about special content models *and* about
802 // special features of the search engine, the search could benefit.
803 $content = $this->mRevision
->getContent();
804 $this->mText
= $content ?
$content->getTextForSearchIndex() : '';
805 } else { // TODO: can we fetch raw wikitext for commons images?
812 * @param $terms Array: terms to highlight
813 * @return String: highlighted text snippet, null (and not '') if not supported
815 function getTextSnippet( $terms ) {
816 global $wgUser, $wgAdvancedSearchHighlighting;
819 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
820 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
821 $h = new SearchHighlighter();
822 if ( $wgAdvancedSearchHighlighting )
823 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
825 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
829 * @param $terms Array: terms to highlight
830 * @return String: highlighted title, '' if not supported
832 function getTitleSnippet( $terms ) {
837 * @param $terms Array: terms to highlight
838 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
840 function getRedirectSnippet( $terms ) {
845 * @return Title object for the redirect to this page, null if none or not supported
847 function getRedirectTitle() {
852 * @return string highlighted relevant section name, null if none or not supported
854 function getSectionSnippet() {
859 * @return Title object (pagename+fragment) for the section, null if none or not supported
861 function getSectionTitle() {
866 * @return String: timestamp
868 function getTimestamp() {
869 if ( $this->mRevision
)
870 return $this->mRevision
->getTimestamp();
871 elseif ( $this->mImage
)
872 return $this->mImage
->getTimestamp();
877 * @return Integer: number of words
879 function getWordCount() {
881 return str_word_count( $this->mText
);
885 * @return Integer: size in bytes
887 function getByteSize() {
889 return strlen( $this->mText
);
893 * @return Boolean if hit has related articles
895 function hasRelated() {
900 * @return String: interwiki prefix of the title (return iw even if title is broken)
902 function getInterwikiPrefix() {
907 * A SearchResultSet wrapper for SearchEngine::getNearMatch
909 class SearchNearMatchResultSet
extends SearchResultSet
{
910 private $fetched = false;
912 * @param $match mixed Title if matched, else null
914 public function __construct( $match ) {
915 $this->result
= $match;
917 public function hasResult() {
918 return (bool)$this->result
;
920 public function numRows() {
921 return $this->hasResults() ?
1 : 0;
923 public function next() {
924 if ( $this->fetched ||
!$this->result
) {
927 $this->fetched
= true;
928 return SearchResult
::newFromTitle( $this->result
);
933 * Highlight bits of wikitext
937 class SearchHighlighter
{
938 var $mCleanWikitext = true;
940 function __construct( $cleanupWikitext = true ) {
941 $this->mCleanWikitext
= $cleanupWikitext;
945 * Default implementation of wikitext highlighting
947 * @param $text String
948 * @param $terms Array: terms to highlight (unescaped)
949 * @param $contextlines Integer
950 * @param $contextchars Integer
953 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
955 global $wgSearchHighlightBoundaries;
961 // spli text into text + templates/links/tables
962 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
963 // first capture group is for detecting nested templates/links/tables/references
964 $endPatterns = array(
965 1 => '/(\{\{)|(\}\})/', // template
966 2 => '/(\[\[)|(\]\])/', // image
967 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
969 // @todo FIXME: This should prolly be a hook or something
970 if ( function_exists( 'wfCite' ) ) {
971 $spat .= '|(<ref>)'; // references via cite extension
972 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
975 $textExt = array(); // text extracts
976 $otherExt = array(); // other extracts
977 wfProfileIn( "$fname-split" );
979 $textLen = strlen( $text );
980 $count = 0; // sequence number to maintain ordering
981 while ( $start < $textLen ) {
982 // find start of template/image/table
983 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
985 foreach ( $matches as $key => $val ) {
986 if ( $key > 0 && $val[1] != - 1 ) {
988 // see if this is an image link
989 $ns = substr( $val[0], 2, - 1 );
990 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
)
994 $epat = $endPatterns[$key];
995 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1001 // find end (and detect any nested elements)
1003 $offset = $start +
1;
1005 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
1006 if ( array_key_exists( 2, $endMatches ) ) {
1008 if ( $level == 0 ) {
1009 $len = strlen( $endMatches[2][0] );
1010 $off = $endMatches[2][1];
1011 $this->splitAndAdd( $otherExt, $count,
1012 substr( $text, $start, $off +
$len - $start ) );
1013 $start = $off +
$len;
1017 // end of nested element
1024 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
1027 // couldn't find appropriate closing tag, skip
1028 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1029 $start +
= strlen( $matches[0][0] );
1034 // else: add as text extract
1035 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1039 $all = $textExt +
$otherExt; // these have disjunct key sets
1041 wfProfileOut( "$fname-split" );
1044 foreach ( $terms as $index => $term ) {
1045 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1046 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1047 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1049 $terms[$index] = $term;
1052 $anyterm = implode( '|', $terms );
1053 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1055 // @todo FIXME: A hack to scale contextchars, a correct solution
1056 // would be to have contextchars actually be char and not byte
1057 // length, and do proper utf-8 substrings and lengths everywhere,
1058 // but PHP is making that very hard and unclean to implement :(
1059 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1060 $contextchars = intval( $contextchars * $scale );
1062 $patPre = "(^|$wgSearchHighlightBoundaries)";
1063 $patPost = "($wgSearchHighlightBoundaries|$)";
1065 $pat1 = "/(" . $phrase . ")/ui";
1066 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1068 wfProfileIn( "$fname-extract" );
1070 $left = $contextlines;
1072 $snippets = array();
1075 // show beginning only if it contains all words
1078 foreach ( $textExt as $index => $line ) {
1079 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1080 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1087 // check if first text contains all terms
1088 foreach ( $terms as $term ) {
1089 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1095 $snippets[$first] = $firstText;
1096 $offsets[$first] = 0;
1099 if ( ! $snippets ) {
1100 // match whole query on text
1101 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1102 // match whole query on templates/tables/images
1103 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1104 // match any words on text
1105 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1106 // match any words on templates/tables/images
1107 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1112 // add extra chars to each snippet to make snippets constant size
1113 $extended = array();
1114 if ( count( $snippets ) == 0 ) {
1115 // couldn't find the target words, just show beginning of article
1116 if ( array_key_exists( $first, $all ) ) {
1117 $targetchars = $contextchars * $contextlines;
1118 $snippets[$first] = '';
1119 $offsets[$first] = 0;
1122 // if begin of the article contains the whole phrase, show only that !!
1123 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1124 && $offsets[$first] < $contextchars * 2 ) {
1125 $snippets = array ( $first => $snippets[$first] );
1128 // calc by how much to extend existing snippets
1129 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1132 foreach ( $snippets as $index => $line ) {
1133 $extended[$index] = $line;
1134 $len = strlen( $line );
1135 if ( $len < $targetchars - 20 ) {
1136 // complete this line
1137 if ( $len < strlen( $all[$index] ) ) {
1138 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1139 $len = strlen( $extended[$index] );
1144 while ( $len < $targetchars - 20
1145 && array_key_exists( $add, $all )
1146 && !array_key_exists( $add, $snippets ) ) {
1148 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1149 $extended[$add] = $tt;
1150 $len +
= strlen( $tt );
1156 // $snippets = array_map('htmlspecialchars', $extended);
1157 $snippets = $extended;
1160 foreach ( $snippets as $index => $line ) {
1162 $extract .= $line; // first line
1163 elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1164 $extract .= " " . $line; // continous lines
1166 $extract .= '<b> ... </b>' . $line;
1171 $extract .= '<b> ... </b>';
1173 $processed = array();
1174 foreach ( $terms as $term ) {
1175 if ( ! isset( $processed[$term] ) ) {
1176 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1177 $extract = preg_replace( $pat3,
1178 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1179 $processed[$term] = true;
1183 wfProfileOut( "$fname-extract" );
1189 * Split text into lines and add it to extracts array
1191 * @param $extracts Array: index -> $line
1192 * @param $count Integer
1193 * @param $text String
1195 function splitAndAdd( &$extracts, &$count, $text ) {
1196 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1197 foreach ( $split as $line ) {
1198 $tt = trim( $line );
1200 $extracts[$count++
] = $tt;
1205 * Do manual case conversion for non-ascii chars
1207 * @param $matches Array
1210 function caseCallback( $matches ) {
1212 if ( strlen( $matches[0] ) > 1 ) {
1213 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1220 * Extract part of the text from start to end, but by
1221 * not chopping up words
1222 * @param $text String
1223 * @param $start Integer
1224 * @param $end Integer
1225 * @param $posStart Integer: (out) actual start position
1226 * @param $posEnd Integer: (out) actual end position
1229 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1230 if ( $start != 0 ) {
1231 $start = $this->position( $text, $start, 1 );
1233 if ( $end >= strlen( $text ) ) {
1234 $end = strlen( $text );
1236 $end = $this->position( $text, $end );
1239 if ( !is_null( $posStart ) ) {
1242 if ( !is_null( $posEnd ) ) {
1246 if ( $end > $start ) {
1247 return substr( $text, $start, $end - $start );
1254 * Find a nonletter near a point (index) in the text
1256 * @param $text String
1257 * @param $point Integer
1258 * @param $offset Integer: offset to found index
1259 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1261 function position( $text, $point, $offset = 0 ) {
1263 $s = max( 0, $point - $tolerance );
1264 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1266 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1267 return $m[0][1] +
$s +
$offset;
1269 // check if point is on a valid first UTF8 char
1270 $char = ord( $text[$point] );
1271 while ( $char >= 0x80 && $char < 0xc0 ) {
1272 // skip trailing bytes
1274 if ( $point >= strlen( $text ) )
1275 return strlen( $text );
1276 $char = ord( $text[$point] );
1284 * Search extracts for a pattern, and return snippets
1286 * @param $pattern String: regexp for matching lines
1287 * @param $extracts Array: extracts to search
1288 * @param $linesleft Integer: number of extracts to make
1289 * @param $contextchars Integer: length of snippet
1290 * @param $out Array: map for highlighted snippets
1291 * @param $offsets Array: map of starting points of snippets
1294 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1295 if ( $linesleft == 0 )
1296 return; // nothing to do
1297 foreach ( $extracts as $index => $line ) {
1298 if ( array_key_exists( $index, $out ) )
1299 continue; // this line already highlighted
1302 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1306 $len = strlen( $m[0][0] );
1307 if ( $offset +
$len < $contextchars )
1309 elseif ( $len > $contextchars )
1312 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1314 $end = $begin +
$contextchars;
1317 // basic snippet from this line
1318 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1319 $offsets[$index] = $posBegin;
1321 if ( $linesleft == 0 )
1327 * Basic wikitext removal
1331 function removeWiki( $text ) {
1332 $fname = __METHOD__
;
1333 wfProfileIn( $fname );
1335 // $text = preg_replace("/'{2,5}/", "", $text);
1336 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1337 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1338 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1339 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1340 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1341 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1342 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1343 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1344 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1345 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1346 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1347 $text = preg_replace( "/'''''/", "", $text );
1348 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1349 $text = preg_replace( "/''/", "", $text );
1351 wfProfileOut( $fname );
1356 * callback to replace [[target|caption]] kind of links, if
1357 * the target is category or image, leave it
1359 * @param $matches Array
1361 function linkReplace( $matches ) {
1362 $colon = strpos( $matches[1], ':' );
1363 if ( $colon === false )
1364 return $matches[2]; // replace with caption
1366 $ns = substr( $matches[1], 0, $colon );
1367 $index = $wgContLang->getNsIndex( $ns );
1368 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) )
1369 return $matches[0]; // return the whole thing
1376 * Simple & fast snippet extraction, but gives completely unrelevant
1379 * @param $text String
1380 * @param $terms Array
1381 * @param $contextlines Integer
1382 * @param $contextchars Integer
1385 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1387 $fname = __METHOD__
;
1389 $lines = explode( "\n", $text );
1391 $terms = implode( '|', $terms );
1392 $max = intval( $contextchars ) +
1;
1393 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1398 wfProfileIn( "$fname-extract" );
1399 foreach ( $lines as $line ) {
1400 if ( 0 == $contextlines ) {
1405 if ( ! preg_match( $pat1, $line, $m ) ) {
1409 // truncate function changes ... to relevant i18n message.
1410 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1412 if ( count( $m ) < 3 ) {
1415 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1420 $line = htmlspecialchars( $pre . $found . $post );
1421 $pat2 = '/(' . $terms . ")/i";
1422 $line = preg_replace( $pat2,
1423 "<span class='searchmatch'>\\1</span>", $line );
1425 $extract .= "${line}\n";
1427 wfProfileOut( "$fname-extract" );
1435 * Dummy class to be used when non-supported Database engine is present.
1436 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1437 * such as a LIKE search through titles.
1440 class SearchEngineDummy
extends SearchEngine
{