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 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 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
204 # Now try all lower case (i.e. first letter capitalized)
205 $title = Title
::newFromText( $wgContLang->lc( $term ) );
206 if ( $title && $title->exists() ) {
210 # Now try capitalized string
211 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
212 if ( $title && $title->exists() ) {
216 # Now try all upper case
217 $title = Title
::newFromText( $wgContLang->uc( $term ) );
218 if ( $title && $title->exists() ) {
222 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
223 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
224 if ( $title && $title->exists() ) {
228 // Give hooks a chance at better match variants
230 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
235 $title = Title
::newFromText( $searchterm );
238 # Entering an IP address goes to the contributions page
239 if ( $wgEnableSearchContributorsByIP ) {
240 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
241 || User
::isIP( trim( $searchterm ) ) ) {
242 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
247 # Entering a user goes to the user page whether it's there or not
248 if ( $title->getNamespace() == NS_USER
) {
252 # Go to images that exist even if there's no local page.
253 # There may have been a funny upload, or it may be on a shared
254 # file repository such as Wikimedia Commons.
255 if ( $title->getNamespace() == NS_FILE
) {
256 $image = wfFindFile( $title );
262 # MediaWiki namespace? Page may be "implied" if not customized.
263 # Just return it, with caps forced as the message system likes it.
264 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
265 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
268 # Quoted term? Try without the quotes...
270 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
271 return SearchEngine
::getNearMatch( $matches[1] );
277 public static function legalSearchChars() {
278 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
282 * Set the maximum number of results to return
283 * and how many to skip before returning the first.
285 * @param $limit Integer
286 * @param $offset Integer
288 function setLimitOffset( $limit, $offset = 0 ) {
289 $this->limit
= intval( $limit );
290 $this->offset
= intval( $offset );
294 * Set which namespaces the search should include.
295 * Give an array of namespace index numbers.
297 * @param $namespaces Array
299 function setNamespaces( $namespaces ) {
300 $this->namespaces
= $namespaces;
304 * Parse some common prefixes: all (search everything)
307 * @param $query String
310 function replacePrefixes( $query ) {
314 if ( strpos( $query, ':' ) === false ) { // nothing to do
315 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
319 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
320 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
321 $this->namespaces
= null;
322 $parsed = substr( $query, strlen( $allkeyword ) );
323 } elseif ( strpos( $query, ':' ) !== false ) {
324 $prefix = substr( $query, 0, strpos( $query, ':' ) );
325 $index = $wgContLang->getNsIndex( $prefix );
326 if ( $index !== false ) {
327 $this->namespaces
= array( $index );
328 $parsed = substr( $query, strlen( $prefix ) +
1 );
331 if ( trim( $parsed ) == '' )
332 $parsed = $query; // prefix was the whole query
334 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
340 * Make a list of searchable namespaces and their canonical names.
343 public static function searchableNamespaces() {
346 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
347 if ( $ns >= NS_MAIN
) {
352 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
357 * Extract default namespaces to search from the given user's
358 * settings, returning a list of index numbers.
363 public static function userNamespaces( $user ) {
364 global $wgSearchEverythingOnlyLoggedIn;
366 $searchableNamespaces = SearchEngine
::searchableNamespaces();
368 // get search everything preference, that can be set to be read for logged-in users
369 // it overrides other options
370 if ( !$wgSearchEverythingOnlyLoggedIn ||
$user->isLoggedIn() ) {
371 if ( $user->getOption( 'searcheverything' ) ) {
372 return array_keys( $searchableNamespaces );
377 foreach ( $searchableNamespaces as $ns => $name ) {
378 if ( $user->getOption( 'searchNs' . $ns ) ) {
387 * Find snippet highlight settings for all users
389 * @return Array contextlines, contextchars
391 public static function userHighlightPrefs() {
392 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
393 $contextchars = 75; // same as above.... :P
394 return array( $contextlines, $contextchars );
398 * An array of namespaces indexes to be searched by default
402 public static function defaultNamespaces() {
403 global $wgNamespacesToBeSearchedDefault;
405 return array_keys( $wgNamespacesToBeSearchedDefault, true );
409 * Get a list of namespace names useful for showing in tooltips
412 * @param $namespaces Array
415 public static function namespacesAsText( $namespaces ) {
418 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
419 foreach ( $formatted as $key => $ns ) {
421 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
427 * Return the help namespaces to be shown on Special:Search
431 public static function helpNamespaces() {
432 global $wgNamespacesToBeSearchedHelp;
434 return array_keys( $wgNamespacesToBeSearchedHelp, true );
438 * Return a 'cleaned up' search string
440 * @param $text String
443 function filter( $text ) {
444 $lc = $this->legalSearchChars();
445 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
448 * Load up the appropriate search engine class for the currently
449 * active database backend, and return a configured instance.
451 * @return SearchEngine
453 public static function create() {
454 global $wgSearchType;
456 if ( $wgSearchType ) {
457 $class = $wgSearchType;
459 $dbr = wfGetDB( DB_SLAVE
);
460 $class = $dbr->getSearchEngine();
462 $search = new $class( $dbr );
463 $search->setLimitOffset( 0, 0 );
468 * Create or update the search index record for the given page.
469 * Title and text should be pre-processed.
473 * @param $title String
474 * @param $text String
476 function update( $id, $title, $text ) {
481 * Update a search index record's title only.
482 * Title should be pre-processed.
486 * @param $title String
488 function updateTitle( $id, $title ) {
493 * Get OpenSearch suggestion template
497 public static function getOpenSearchTemplate() {
498 global $wgOpenSearchTemplate, $wgCanonicalServer;
499 if ( $wgOpenSearchTemplate ) {
500 return $wgOpenSearchTemplate;
502 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
506 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
514 class SearchResultSet
{
516 * Fetch an array of regular expression fragments for matching
517 * the search terms as parsed by this engine in a text extract.
522 function termMatches() {
531 * Return true if results are included in this result set.
536 function hasResults() {
541 * Some search modes return a total hit count for the query
542 * in the entire article database. This may include pages
543 * in namespaces that would not be matched on the given
546 * Return null if no total hits number is supported.
550 function getTotalHits() {
555 * Some search modes return a suggested alternate term if there are
556 * no exact hits. Returns true if there is one on this set.
560 function hasSuggestion() {
565 * @return String: suggested query, null if none
567 function getSuggestionQuery() {
572 * @return String: HTML highlighted suggested query, '' if none
574 function getSuggestionSnippet() {
579 * Return information about how and from where the results were fetched,
580 * should be useful for diagnostics and debugging
589 * Return a result set of hits on other (multiple) wikis associated with this one
591 * @return SearchResultSet
593 function getInterwikiResults() {
598 * Check if there are results on other wikis
602 function hasInterwikiResults() {
603 return $this->getInterwikiResults() != null;
607 * Fetches next search result, or false.
610 * @return SearchResult
617 * Frees the result set, if applicable.
625 * This class is used for different SQL-based search engines shipped with MediaWiki
627 class SqlSearchResultSet
extends SearchResultSet
{
629 protected $mResultSet;
631 function __construct( $resultSet, $terms ) {
632 $this->mResultSet
= $resultSet;
633 $this->mTerms
= $terms;
636 function termMatches() {
637 return $this->mTerms
;
641 if ( $this->mResultSet
=== false )
644 return $this->mResultSet
->numRows();
648 if ( $this->mResultSet
=== false )
651 $row = $this->mResultSet
->fetchObject();
652 if ( $row === false )
655 return SearchResult
::newFromRow( $row );
659 if ( $this->mResultSet
=== false )
662 $this->mResultSet
->free();
669 class SearchResultTooMany
{
670 # # Some search engines may bail out if too many matches are found
675 * @todo FIXME: This class is horribly factored. It would probably be better to
676 * have a useful base class to which you pass some standard information, then
677 * let the fancy self-highlighters extend that.
685 var $mRevision = null;
699 * Return a new SearchResult and initializes it with a title.
701 * @param $title Title
702 * @return SearchResult
704 public static function newFromTitle( $title ) {
705 $result = new self();
706 $result->initFromTitle( $title );
710 * Return a new SearchResult and initializes it with a row.
713 * @return SearchResult
715 public static function newFromRow( $row ) {
716 $result = new self();
717 $result->initFromRow( $row );
721 public function __construct( $row = null ) {
722 if ( !is_null( $row ) ) {
723 // Backwards compatibility with pre-1.17 callers
724 $this->initFromRow( $row );
729 * Initialize from a database row. Makes a Title and passes that to
734 protected function initFromRow( $row ) {
735 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
739 * Initialize from a Title and if possible initializes a corresponding
742 * @param $title Title
744 protected function initFromTitle( $title ) {
745 $this->mTitle
= $title;
746 if ( !is_null( $this->mTitle
) ) {
748 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
749 $this->mRevision
= Revision
::newFromTitle(
750 $this->mTitle
, $id, Revision
::READ_NORMAL
);
751 if ( $this->mTitle
->getNamespace() === NS_FILE
)
752 $this->mImage
= wfFindFile( $this->mTitle
);
757 * Check if this is result points to an invalid title
761 function isBrokenTitle() {
762 if ( is_null( $this->mTitle
) )
768 * Check if target page is missing, happens when index is out of date
772 function isMissingRevision() {
773 return !$this->mRevision
&& !$this->mImage
;
779 function getTitle() {
780 return $this->mTitle
;
784 * @return float|null if not supported
786 function getScore() {
791 * Lazy initialization of article text from DB
793 protected function initText() {
794 if ( !isset( $this->mText
) ) {
795 if ( $this->mRevision
!= null ) {
796 //TODO: if we could plug in some code that knows about special content models *and* about
797 // special features of the search engine, the search could benefit.
798 $content = $this->mRevision
->getContent();
799 $this->mText
= $content->getTextForSearchIndex();
800 } else { // TODO: can we fetch raw wikitext for commons images?
807 * @param $terms Array: terms to highlight
808 * @return String: highlighted text snippet, null (and not '') if not supported
810 function getTextSnippet( $terms ) {
811 global $wgUser, $wgAdvancedSearchHighlighting;
814 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
815 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
816 $h = new SearchHighlighter();
817 if ( $wgAdvancedSearchHighlighting )
818 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
820 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
824 * @param $terms Array: terms to highlight
825 * @return String: highlighted title, '' if not supported
827 function getTitleSnippet( $terms ) {
832 * @param $terms Array: terms to highlight
833 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
835 function getRedirectSnippet( $terms ) {
840 * @return Title object for the redirect to this page, null if none or not supported
842 function getRedirectTitle() {
847 * @return string highlighted relevant section name, null if none or not supported
849 function getSectionSnippet() {
854 * @return Title object (pagename+fragment) for the section, null if none or not supported
856 function getSectionTitle() {
861 * @return String: timestamp
863 function getTimestamp() {
864 if ( $this->mRevision
)
865 return $this->mRevision
->getTimestamp();
866 elseif ( $this->mImage
)
867 return $this->mImage
->getTimestamp();
872 * @return Integer: number of words
874 function getWordCount() {
876 return str_word_count( $this->mText
);
880 * @return Integer: size in bytes
882 function getByteSize() {
884 return strlen( $this->mText
);
888 * @return Boolean if hit has related articles
890 function hasRelated() {
895 * @return String: interwiki prefix of the title (return iw even if title is broken)
897 function getInterwikiPrefix() {
902 * A SearchResultSet wrapper for SearchEngine::getNearMatch
904 class SearchNearMatchResultSet
extends SearchResultSet
{
905 private $fetched = false;
907 * @param $match mixed Title if matched, else null
909 public function __construct( $match ) {
910 $this->result
= $match;
912 public function hasResult() {
913 return (bool)$this->result
;
915 public function numRows() {
916 return $this->hasResults() ?
1 : 0;
918 public function next() {
919 if ( $this->fetched ||
!$this->result
) {
922 $this->fetched
= true;
923 return SearchResult
::newFromTitle( $this->result
);
928 * Highlight bits of wikitext
932 class SearchHighlighter
{
933 var $mCleanWikitext = true;
935 function __construct( $cleanupWikitext = true ) {
936 $this->mCleanWikitext
= $cleanupWikitext;
940 * Default implementation of wikitext highlighting
942 * @param $text String
943 * @param $terms Array: terms to highlight (unescaped)
944 * @param $contextlines Integer
945 * @param $contextchars Integer
948 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
950 global $wgSearchHighlightBoundaries;
956 // spli text into text + templates/links/tables
957 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
958 // first capture group is for detecting nested templates/links/tables/references
959 $endPatterns = array(
960 1 => '/(\{\{)|(\}\})/', // template
961 2 => '/(\[\[)|(\]\])/', // image
962 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
964 // @todo FIXME: This should prolly be a hook or something
965 if ( function_exists( 'wfCite' ) ) {
966 $spat .= '|(<ref>)'; // references via cite extension
967 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
970 $textExt = array(); // text extracts
971 $otherExt = array(); // other extracts
972 wfProfileIn( "$fname-split" );
974 $textLen = strlen( $text );
975 $count = 0; // sequence number to maintain ordering
976 while ( $start < $textLen ) {
977 // find start of template/image/table
978 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
980 foreach ( $matches as $key => $val ) {
981 if ( $key > 0 && $val[1] != - 1 ) {
983 // see if this is an image link
984 $ns = substr( $val[0], 2, - 1 );
985 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
)
989 $epat = $endPatterns[$key];
990 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
996 // find end (and detect any nested elements)
998 $offset = $start +
1;
1000 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
1001 if ( array_key_exists( 2, $endMatches ) ) {
1003 if ( $level == 0 ) {
1004 $len = strlen( $endMatches[2][0] );
1005 $off = $endMatches[2][1];
1006 $this->splitAndAdd( $otherExt, $count,
1007 substr( $text, $start, $off +
$len - $start ) );
1008 $start = $off +
$len;
1012 // end of nested element
1019 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
1022 // couldn't find appropriate closing tag, skip
1023 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1024 $start +
= strlen( $matches[0][0] );
1029 // else: add as text extract
1030 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1034 $all = $textExt +
$otherExt; // these have disjunct key sets
1036 wfProfileOut( "$fname-split" );
1039 foreach ( $terms as $index => $term ) {
1040 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1041 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1042 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1044 $terms[$index] = $term;
1047 $anyterm = implode( '|', $terms );
1048 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1050 // @todo FIXME: A hack to scale contextchars, a correct solution
1051 // would be to have contextchars actually be char and not byte
1052 // length, and do proper utf-8 substrings and lengths everywhere,
1053 // but PHP is making that very hard and unclean to implement :(
1054 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1055 $contextchars = intval( $contextchars * $scale );
1057 $patPre = "(^|$wgSearchHighlightBoundaries)";
1058 $patPost = "($wgSearchHighlightBoundaries|$)";
1060 $pat1 = "/(" . $phrase . ")/ui";
1061 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1063 wfProfileIn( "$fname-extract" );
1065 $left = $contextlines;
1067 $snippets = array();
1070 // show beginning only if it contains all words
1073 foreach ( $textExt as $index => $line ) {
1074 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1075 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1082 // check if first text contains all terms
1083 foreach ( $terms as $term ) {
1084 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1090 $snippets[$first] = $firstText;
1091 $offsets[$first] = 0;
1094 if ( ! $snippets ) {
1095 // match whole query on text
1096 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1097 // match whole query on templates/tables/images
1098 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1099 // match any words on text
1100 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1101 // match any words on templates/tables/images
1102 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1107 // add extra chars to each snippet to make snippets constant size
1108 $extended = array();
1109 if ( count( $snippets ) == 0 ) {
1110 // couldn't find the target words, just show beginning of article
1111 if ( array_key_exists( $first, $all ) ) {
1112 $targetchars = $contextchars * $contextlines;
1113 $snippets[$first] = '';
1114 $offsets[$first] = 0;
1117 // if begin of the article contains the whole phrase, show only that !!
1118 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1119 && $offsets[$first] < $contextchars * 2 ) {
1120 $snippets = array ( $first => $snippets[$first] );
1123 // calc by how much to extend existing snippets
1124 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1127 foreach ( $snippets as $index => $line ) {
1128 $extended[$index] = $line;
1129 $len = strlen( $line );
1130 if ( $len < $targetchars - 20 ) {
1131 // complete this line
1132 if ( $len < strlen( $all[$index] ) ) {
1133 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1134 $len = strlen( $extended[$index] );
1139 while ( $len < $targetchars - 20
1140 && array_key_exists( $add, $all )
1141 && !array_key_exists( $add, $snippets ) ) {
1143 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1144 $extended[$add] = $tt;
1145 $len +
= strlen( $tt );
1151 // $snippets = array_map('htmlspecialchars', $extended);
1152 $snippets = $extended;
1155 foreach ( $snippets as $index => $line ) {
1157 $extract .= $line; // first line
1158 elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1159 $extract .= " " . $line; // continous lines
1161 $extract .= '<b> ... </b>' . $line;
1166 $extract .= '<b> ... </b>';
1168 $processed = array();
1169 foreach ( $terms as $term ) {
1170 if ( ! isset( $processed[$term] ) ) {
1171 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1172 $extract = preg_replace( $pat3,
1173 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1174 $processed[$term] = true;
1178 wfProfileOut( "$fname-extract" );
1184 * Split text into lines and add it to extracts array
1186 * @param $extracts Array: index -> $line
1187 * @param $count Integer
1188 * @param $text String
1190 function splitAndAdd( &$extracts, &$count, $text ) {
1191 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1192 foreach ( $split as $line ) {
1193 $tt = trim( $line );
1195 $extracts[$count++
] = $tt;
1200 * Do manual case conversion for non-ascii chars
1202 * @param $matches Array
1205 function caseCallback( $matches ) {
1207 if ( strlen( $matches[0] ) > 1 ) {
1208 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1215 * Extract part of the text from start to end, but by
1216 * not chopping up words
1217 * @param $text String
1218 * @param $start Integer
1219 * @param $end Integer
1220 * @param $posStart Integer: (out) actual start position
1221 * @param $posEnd Integer: (out) actual end position
1224 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1225 if ( $start != 0 ) {
1226 $start = $this->position( $text, $start, 1 );
1228 if ( $end >= strlen( $text ) ) {
1229 $end = strlen( $text );
1231 $end = $this->position( $text, $end );
1234 if ( !is_null( $posStart ) ) {
1237 if ( !is_null( $posEnd ) ) {
1241 if ( $end > $start ) {
1242 return substr( $text, $start, $end - $start );
1249 * Find a nonletter near a point (index) in the text
1251 * @param $text String
1252 * @param $point Integer
1253 * @param $offset Integer: offset to found index
1254 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1256 function position( $text, $point, $offset = 0 ) {
1258 $s = max( 0, $point - $tolerance );
1259 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1261 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1262 return $m[0][1] +
$s +
$offset;
1264 // check if point is on a valid first UTF8 char
1265 $char = ord( $text[$point] );
1266 while ( $char >= 0x80 && $char < 0xc0 ) {
1267 // skip trailing bytes
1269 if ( $point >= strlen( $text ) )
1270 return strlen( $text );
1271 $char = ord( $text[$point] );
1279 * Search extracts for a pattern, and return snippets
1281 * @param $pattern String: regexp for matching lines
1282 * @param $extracts Array: extracts to search
1283 * @param $linesleft Integer: number of extracts to make
1284 * @param $contextchars Integer: length of snippet
1285 * @param $out Array: map for highlighted snippets
1286 * @param $offsets Array: map of starting points of snippets
1289 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1290 if ( $linesleft == 0 )
1291 return; // nothing to do
1292 foreach ( $extracts as $index => $line ) {
1293 if ( array_key_exists( $index, $out ) )
1294 continue; // this line already highlighted
1297 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1301 $len = strlen( $m[0][0] );
1302 if ( $offset +
$len < $contextchars )
1304 elseif ( $len > $contextchars )
1307 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1309 $end = $begin +
$contextchars;
1312 // basic snippet from this line
1313 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1314 $offsets[$index] = $posBegin;
1316 if ( $linesleft == 0 )
1322 * Basic wikitext removal
1326 function removeWiki( $text ) {
1327 $fname = __METHOD__
;
1328 wfProfileIn( $fname );
1330 // $text = preg_replace("/'{2,5}/", "", $text);
1331 // $text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1332 // $text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1333 // $text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1334 // $text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1335 // $text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1336 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1337 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1338 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1339 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1340 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1341 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1342 $text = preg_replace( "/'''''/", "", $text );
1343 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1344 $text = preg_replace( "/''/", "", $text );
1346 wfProfileOut( $fname );
1351 * callback to replace [[target|caption]] kind of links, if
1352 * the target is category or image, leave it
1354 * @param $matches Array
1356 function linkReplace( $matches ) {
1357 $colon = strpos( $matches[1], ':' );
1358 if ( $colon === false )
1359 return $matches[2]; // replace with caption
1361 $ns = substr( $matches[1], 0, $colon );
1362 $index = $wgContLang->getNsIndex( $ns );
1363 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) )
1364 return $matches[0]; // return the whole thing
1371 * Simple & fast snippet extraction, but gives completely unrelevant
1374 * @param $text String
1375 * @param $terms Array
1376 * @param $contextlines Integer
1377 * @param $contextchars Integer
1380 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1382 $fname = __METHOD__
;
1384 $lines = explode( "\n", $text );
1386 $terms = implode( '|', $terms );
1387 $max = intval( $contextchars ) +
1;
1388 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1393 wfProfileIn( "$fname-extract" );
1394 foreach ( $lines as $line ) {
1395 if ( 0 == $contextlines ) {
1400 if ( ! preg_match( $pat1, $line, $m ) ) {
1404 // truncate function changes ... to relevant i18n message.
1405 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1407 if ( count( $m ) < 3 ) {
1410 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1415 $line = htmlspecialchars( $pre . $found . $post );
1416 $pat2 = '/(' . $terms . ")/i";
1417 $line = preg_replace( $pat2,
1418 "<span class='searchmatch'>\\1</span>", $line );
1420 $extract .= "${line}\n";
1422 wfProfileOut( "$fname-extract" );
1430 * Dummy class to be used when non-supported Database engine is present.
1431 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1432 * such as a LIKE search through titles.
1435 class SearchEngineDummy
extends SearchEngine
{