5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Search Search
29 * Contain a class for special pages
36 var $searchTerms = array();
37 var $namespaces = array( NS_MAIN
);
38 var $showRedirects = false;
41 protected $features = array();
48 function __construct( $db = null ) {
52 $this->db
= wfGetDB( DB_SLAVE
);
57 * Perform a full text search query and return a result set.
58 * If title searches are not supported or disabled, return null.
61 * @param string $term raw search term
62 * @return SearchResultSet
64 function searchText( $term ) {
69 * Perform a title-only search query and return a result set.
70 * If title searches are not supported or disabled, return null.
73 * @param string $term raw search term
74 * @return SearchResultSet
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 );
242 # Entering an IP address goes to the contributions page
243 if ( $wgEnableSearchContributorsByIP ) {
244 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
245 || User
::isIP( trim( $searchterm ) ) ) {
246 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
250 # Entering a user goes to the user page whether it's there or not
251 if ( $title->getNamespace() == NS_USER
) {
255 # Go to images that exist even if there's no local page.
256 # There may have been a funny upload, or it may be on a shared
257 # file repository such as Wikimedia Commons.
258 if ( $title->getNamespace() == NS_FILE
) {
259 $image = wfFindFile( $title );
265 # MediaWiki namespace? Page may be "implied" if not customized.
266 # Just return it, with caps forced as the message system likes it.
267 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
268 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
271 # Quoted term? Try without the quotes...
273 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
274 return SearchEngine
::getNearMatch( $matches[1] );
280 public static function legalSearchChars() {
281 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
285 * Set the maximum number of results to return
286 * and how many to skip before returning the first.
288 * @param $limit Integer
289 * @param $offset Integer
291 function setLimitOffset( $limit, $offset = 0 ) {
292 $this->limit
= intval( $limit );
293 $this->offset
= intval( $offset );
297 * Set which namespaces the search should include.
298 * Give an array of namespace index numbers.
300 * @param $namespaces Array
302 function setNamespaces( $namespaces ) {
303 $this->namespaces
= $namespaces;
307 * Parse some common prefixes: all (search everything)
310 * @param $query String
313 function replacePrefixes( $query ) {
317 if ( strpos( $query, ':' ) === false ) { // nothing to do
318 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
322 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
323 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
324 $this->namespaces
= null;
325 $parsed = substr( $query, strlen( $allkeyword ) );
326 } elseif ( strpos( $query, ':' ) !== false ) {
327 $prefix = substr( $query, 0, strpos( $query, ':' ) );
328 $index = $wgContLang->getNsIndex( $prefix );
329 if ( $index !== false ) {
330 $this->namespaces
= array( $index );
331 $parsed = substr( $query, strlen( $prefix ) +
1 );
334 if ( trim( $parsed ) == '' )
335 $parsed = $query; // prefix was the whole query
337 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
343 * Make a list of searchable namespaces and their canonical names.
346 public static function searchableNamespaces() {
349 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
350 if ( $ns >= NS_MAIN
) {
355 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
360 * Extract default namespaces to search from the given user's
361 * settings, returning a list of index numbers.
366 public static function userNamespaces( $user ) {
367 global $wgSearchEverythingOnlyLoggedIn;
369 $searchableNamespaces = SearchEngine
::searchableNamespaces();
371 // get search everything preference, that can be set to be read for logged-in users
372 // it overrides other options
373 if ( !$wgSearchEverythingOnlyLoggedIn ||
$user->isLoggedIn() ) {
374 if ( $user->getOption( 'searcheverything' ) ) {
375 return array_keys( $searchableNamespaces );
380 foreach ( $searchableNamespaces as $ns => $name ) {
381 if ( $user->getOption( 'searchNs' . $ns ) ) {
390 * Find snippet highlight settings for all users
392 * @return Array contextlines, contextchars
394 public static function userHighlightPrefs() {
395 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
396 $contextchars = 75; // same as above.... :P
397 return array( $contextlines, $contextchars );
401 * An array of namespaces indexes to be searched by default
405 public static function defaultNamespaces() {
406 global $wgNamespacesToBeSearchedDefault;
408 return array_keys( $wgNamespacesToBeSearchedDefault, true );
412 * Get a list of namespace names useful for showing in tooltips
415 * @param $namespaces Array
418 public static function namespacesAsText( $namespaces ) {
421 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
422 foreach ( $formatted as $key => $ns ) {
424 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
430 * Return the help namespaces to be shown on Special:Search
434 public static function helpNamespaces() {
435 global $wgNamespacesToBeSearchedHelp;
437 return array_keys( $wgNamespacesToBeSearchedHelp, true );
441 * Return a 'cleaned up' search string
443 * @param $text String
446 function filter( $text ) {
447 $lc = $this->legalSearchChars();
448 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
451 * Load up the appropriate search engine class for the currently
452 * active database backend, and return a configured instance.
454 * @return SearchEngine
456 public static function create() {
457 global $wgSearchType;
459 if ( $wgSearchType ) {
460 $class = $wgSearchType;
462 $dbr = wfGetDB( DB_SLAVE
);
463 $class = $dbr->getSearchEngine();
465 $search = new $class( $dbr );
466 $search->setLimitOffset( 0, 0 );
471 * Create or update the search index record for the given page.
472 * Title and text should be pre-processed.
476 * @param $title String
477 * @param $text String
479 function update( $id, $title, $text ) {
484 * Update a search index record's title only.
485 * Title should be pre-processed.
489 * @param $title String
491 function updateTitle( $id, $title ) {
496 * Get OpenSearch suggestion template
500 public static function getOpenSearchTemplate() {
501 global $wgOpenSearchTemplate, $wgCanonicalServer;
502 if ( $wgOpenSearchTemplate ) {
503 return $wgOpenSearchTemplate;
505 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
509 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
517 class SearchResultSet
{
519 * Fetch an array of regular expression fragments for matching
520 * the search terms as parsed by this engine in a text extract.
525 function termMatches() {
534 * Return true if results are included in this result set.
539 function hasResults() {
544 * Some search modes return a total hit count for the query
545 * in the entire article database. This may include pages
546 * in namespaces that would not be matched on the given
549 * Return null if no total hits number is supported.
553 function getTotalHits() {
558 * Some search modes return a suggested alternate term if there are
559 * no exact hits. Returns true if there is one on this set.
563 function hasSuggestion() {
568 * @return String: suggested query, null if none
570 function getSuggestionQuery() {
575 * @return String: HTML highlighted suggested query, '' if none
577 function getSuggestionSnippet() {
582 * Return information about how and from where the results were fetched,
583 * should be useful for diagnostics and debugging
592 * Return a result set of hits on other (multiple) wikis associated with this one
594 * @return SearchResultSet
596 function getInterwikiResults() {
601 * Check if there are results on other wikis
605 function hasInterwikiResults() {
606 return $this->getInterwikiResults() != null;
610 * Fetches next search result, or false.
613 * @return SearchResult
620 * Frees the result set, if applicable.
628 * This class is used for different SQL-based search engines shipped with MediaWiki
630 class SqlSearchResultSet
extends SearchResultSet
{
632 protected $mResultSet;
634 function __construct( $resultSet, $terms ) {
635 $this->mResultSet
= $resultSet;
636 $this->mTerms
= $terms;
639 function termMatches() {
640 return $this->mTerms
;
644 if ( $this->mResultSet
=== false )
647 return $this->mResultSet
->numRows();
651 if ( $this->mResultSet
=== false )
654 $row = $this->mResultSet
->fetchObject();
655 if ( $row === false )
658 return SearchResult
::newFromRow( $row );
662 if ( $this->mResultSet
=== false )
665 $this->mResultSet
->free();
672 class SearchResultTooMany
{
673 # # Some search engines may bail out if too many matches are found
677 * @todo FIXME: This class is horribly factored. It would probably be better to
678 * have a useful base class to which you pass some standard information, then
679 * let the fancy self-highlighters extend that.
687 var $mRevision = null;
701 * Return a new SearchResult and initializes it with a title.
703 * @param $title Title
704 * @return SearchResult
706 public static function newFromTitle( $title ) {
707 $result = new self();
708 $result->initFromTitle( $title );
712 * Return a new SearchResult and initializes it with a row.
715 * @return SearchResult
717 public static function newFromRow( $row ) {
718 $result = new self();
719 $result->initFromRow( $row );
723 public function __construct( $row = null ) {
724 if ( !is_null( $row ) ) {
725 // Backwards compatibility with pre-1.17 callers
726 $this->initFromRow( $row );
731 * Initialize from a database row. Makes a Title and passes that to
736 protected function initFromRow( $row ) {
737 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
741 * Initialize from a Title and if possible initializes a corresponding
744 * @param $title Title
746 protected function initFromTitle( $title ) {
747 $this->mTitle
= $title;
748 if ( !is_null( $this->mTitle
) ) {
750 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
751 $this->mRevision
= Revision
::newFromTitle(
752 $this->mTitle
, $id, Revision
::READ_NORMAL
);
753 if ( $this->mTitle
->getNamespace() === NS_FILE
)
754 $this->mImage
= wfFindFile( $this->mTitle
);
759 * Check if this is result points to an invalid title
763 function isBrokenTitle() {
764 if ( is_null( $this->mTitle
) )
770 * Check if target page is missing, happens when index is out of date
774 function isMissingRevision() {
775 return !$this->mRevision
&& !$this->mImage
;
781 function getTitle() {
782 return $this->mTitle
;
786 * @return float|null if not supported
788 function getScore() {
793 * Lazy initialization of article text from DB
795 protected function initText() {
796 if ( !isset( $this->mText
) ) {
797 if ( $this->mRevision
!= null ) {
798 //TODO: if we could plug in some code that knows about special content models *and* about
799 // special features of the search engine, the search could benefit.
800 $content = $this->mRevision
->getContent();
801 $this->mText
= $content ?
$content->getTextForSearchIndex() : '';
802 } else { // TODO: can we fetch raw wikitext for commons images?
809 * @param array $terms terms to highlight
810 * @return String: highlighted text snippet, null (and not '') if not supported
812 function getTextSnippet( $terms ) {
813 global $wgUser, $wgAdvancedSearchHighlighting;
816 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
817 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
818 $h = new SearchHighlighter();
819 if ( $wgAdvancedSearchHighlighting )
820 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
822 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
826 * @param array $terms terms to highlight
827 * @return String: highlighted title, '' if not supported
829 function getTitleSnippet( $terms ) {
834 * @param array $terms terms to highlight
835 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
837 function getRedirectSnippet( $terms ) {
842 * @return Title object for the redirect to this page, null if none or not supported
844 function getRedirectTitle() {
849 * @return string highlighted relevant section name, null if none or not supported
851 function getSectionSnippet() {
856 * @return Title object (pagename+fragment) for the section, null if none or not supported
858 function getSectionTitle() {
863 * @return String: timestamp
865 function getTimestamp() {
866 if ( $this->mRevision
)
867 return $this->mRevision
->getTimestamp();
868 elseif ( $this->mImage
)
869 return $this->mImage
->getTimestamp();
874 * @return Integer: number of words
876 function getWordCount() {
878 return str_word_count( $this->mText
);
882 * @return Integer: size in bytes
884 function getByteSize() {
886 return strlen( $this->mText
);
890 * @return Boolean if hit has related articles
892 function hasRelated() {
897 * @return String: interwiki prefix of the title (return iw even if title is broken)
899 function getInterwikiPrefix() {
904 * A SearchResultSet wrapper for SearchEngine::getNearMatch
906 class SearchNearMatchResultSet
extends SearchResultSet
{
907 private $fetched = false;
909 * @param $match mixed Title if matched, else null
911 public function __construct( $match ) {
912 $this->result
= $match;
914 public function hasResult() {
915 return (bool)$this->result
;
917 public function numRows() {
918 return $this->hasResults() ?
1 : 0;
920 public function next() {
921 if ( $this->fetched ||
!$this->result
) {
924 $this->fetched
= true;
925 return SearchResult
::newFromTitle( $this->result
);
930 * Highlight bits of wikitext
934 class SearchHighlighter
{
935 var $mCleanWikitext = true;
937 function __construct( $cleanupWikitext = true ) {
938 $this->mCleanWikitext
= $cleanupWikitext;
942 * Default implementation of wikitext highlighting
944 * @param $text String
945 * @param array $terms terms to highlight (unescaped)
946 * @param $contextlines Integer
947 * @param $contextchars Integer
950 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
952 global $wgSearchHighlightBoundaries;
958 // spli text into text + templates/links/tables
959 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
960 // first capture group is for detecting nested templates/links/tables/references
961 $endPatterns = array(
962 1 => '/(\{\{)|(\}\})/', // template
963 2 => '/(\[\[)|(\]\])/', // image
964 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
966 // @todo FIXME: This should prolly be a hook or something
967 if ( function_exists( 'wfCite' ) ) {
968 $spat .= '|(<ref>)'; // references via cite extension
969 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
972 $textExt = array(); // text extracts
973 $otherExt = array(); // other extracts
974 wfProfileIn( "$fname-split" );
976 $textLen = strlen( $text );
977 $count = 0; // sequence number to maintain ordering
978 while ( $start < $textLen ) {
979 // find start of template/image/table
980 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
982 foreach ( $matches as $key => $val ) {
983 if ( $key > 0 && $val[1] != - 1 ) {
985 // see if this is an image link
986 $ns = substr( $val[0], 2, - 1 );
987 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
)
991 $epat = $endPatterns[$key];
992 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
998 // find end (and detect any nested elements)
1000 $offset = $start +
1;
1002 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
1003 if ( array_key_exists( 2, $endMatches ) ) {
1005 if ( $level == 0 ) {
1006 $len = strlen( $endMatches[2][0] );
1007 $off = $endMatches[2][1];
1008 $this->splitAndAdd( $otherExt, $count,
1009 substr( $text, $start, $off +
$len - $start ) );
1010 $start = $off +
$len;
1014 // end of nested element
1021 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
1024 // couldn't find appropriate closing tag, skip
1025 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1026 $start +
= strlen( $matches[0][0] );
1031 // else: add as text extract
1032 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1036 $all = $textExt +
$otherExt; // these have disjunct key sets
1038 wfProfileOut( "$fname-split" );
1041 foreach ( $terms as $index => $term ) {
1042 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1043 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1044 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1046 $terms[$index] = $term;
1049 $anyterm = implode( '|', $terms );
1050 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1052 // @todo FIXME: A hack to scale contextchars, a correct solution
1053 // would be to have contextchars actually be char and not byte
1054 // length, and do proper utf-8 substrings and lengths everywhere,
1055 // but PHP is making that very hard and unclean to implement :(
1056 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1057 $contextchars = intval( $contextchars * $scale );
1059 $patPre = "(^|$wgSearchHighlightBoundaries)";
1060 $patPost = "($wgSearchHighlightBoundaries|$)";
1062 $pat1 = "/(" . $phrase . ")/ui";
1063 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1065 wfProfileIn( "$fname-extract" );
1067 $left = $contextlines;
1069 $snippets = array();
1072 // show beginning only if it contains all words
1075 foreach ( $textExt as $index => $line ) {
1076 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1077 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1084 // check if first text contains all terms
1085 foreach ( $terms as $term ) {
1086 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1092 $snippets[$first] = $firstText;
1093 $offsets[$first] = 0;
1096 if ( ! $snippets ) {
1097 // match whole query on text
1098 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1099 // match whole query on templates/tables/images
1100 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1101 // match any words on text
1102 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1103 // match any words on templates/tables/images
1104 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1109 // add extra chars to each snippet to make snippets constant size
1110 $extended = array();
1111 if ( count( $snippets ) == 0 ) {
1112 // couldn't find the target words, just show beginning of article
1113 if ( array_key_exists( $first, $all ) ) {
1114 $targetchars = $contextchars * $contextlines;
1115 $snippets[$first] = '';
1116 $offsets[$first] = 0;
1119 // if begin of the article contains the whole phrase, show only that !!
1120 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1121 && $offsets[$first] < $contextchars * 2 ) {
1122 $snippets = array ( $first => $snippets[$first] );
1125 // calc by how much to extend existing snippets
1126 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1129 foreach ( $snippets as $index => $line ) {
1130 $extended[$index] = $line;
1131 $len = strlen( $line );
1132 if ( $len < $targetchars - 20 ) {
1133 // complete this line
1134 if ( $len < strlen( $all[$index] ) ) {
1135 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1136 $len = strlen( $extended[$index] );
1141 while ( $len < $targetchars - 20
1142 && array_key_exists( $add, $all )
1143 && !array_key_exists( $add, $snippets ) ) {
1145 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1146 $extended[$add] = $tt;
1147 $len +
= strlen( $tt );
1153 // $snippets = array_map( 'htmlspecialchars', $extended );
1154 $snippets = $extended;
1157 foreach ( $snippets as $index => $line ) {
1159 $extract .= $line; // first line
1160 elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) )
1161 $extract .= " " . $line; // continous lines
1163 $extract .= '<b> ... </b>' . $line;
1168 $extract .= '<b> ... </b>';
1170 $processed = array();
1171 foreach ( $terms as $term ) {
1172 if ( ! isset( $processed[$term] ) ) {
1173 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1174 $extract = preg_replace( $pat3,
1175 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1176 $processed[$term] = true;
1180 wfProfileOut( "$fname-extract" );
1186 * Split text into lines and add it to extracts array
1188 * @param array $extracts index -> $line
1189 * @param $count Integer
1190 * @param $text String
1192 function splitAndAdd( &$extracts, &$count, $text ) {
1193 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1194 foreach ( $split as $line ) {
1195 $tt = trim( $line );
1197 $extracts[$count++
] = $tt;
1202 * Do manual case conversion for non-ascii chars
1204 * @param $matches Array
1207 function caseCallback( $matches ) {
1209 if ( strlen( $matches[0] ) > 1 ) {
1210 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1217 * Extract part of the text from start to end, but by
1218 * not chopping up words
1219 * @param $text String
1220 * @param $start Integer
1221 * @param $end Integer
1222 * @param $posStart Integer: (out) actual start position
1223 * @param $posEnd Integer: (out) actual end position
1226 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1227 if ( $start != 0 ) {
1228 $start = $this->position( $text, $start, 1 );
1230 if ( $end >= strlen( $text ) ) {
1231 $end = strlen( $text );
1233 $end = $this->position( $text, $end );
1236 if ( !is_null( $posStart ) ) {
1239 if ( !is_null( $posEnd ) ) {
1243 if ( $end > $start ) {
1244 return substr( $text, $start, $end - $start );
1251 * Find a nonletter near a point (index) in the text
1253 * @param $text String
1254 * @param $point Integer
1255 * @param $offset Integer: offset to found index
1256 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1258 function position( $text, $point, $offset = 0 ) {
1260 $s = max( 0, $point - $tolerance );
1261 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1263 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1264 return $m[0][1] +
$s +
$offset;
1266 // check if point is on a valid first UTF8 char
1267 $char = ord( $text[$point] );
1268 while ( $char >= 0x80 && $char < 0xc0 ) {
1269 // skip trailing bytes
1271 if ( $point >= strlen( $text ) )
1272 return strlen( $text );
1273 $char = ord( $text[$point] );
1281 * Search extracts for a pattern, and return snippets
1283 * @param string $pattern regexp for matching lines
1284 * @param array $extracts extracts to search
1285 * @param $linesleft Integer: number of extracts to make
1286 * @param $contextchars Integer: length of snippet
1287 * @param array $out map for highlighted snippets
1288 * @param array $offsets map of starting points of snippets
1291 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1292 if ( $linesleft == 0 )
1293 return; // nothing to do
1294 foreach ( $extracts as $index => $line ) {
1295 if ( array_key_exists( $index, $out ) )
1296 continue; // this line already highlighted
1299 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1303 $len = strlen( $m[0][0] );
1304 if ( $offset +
$len < $contextchars )
1306 elseif ( $len > $contextchars )
1309 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1311 $end = $begin +
$contextchars;
1314 // basic snippet from this line
1315 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1316 $offsets[$index] = $posBegin;
1318 if ( $linesleft == 0 )
1324 * Basic wikitext removal
1328 function removeWiki( $text ) {
1329 $fname = __METHOD__
;
1330 wfProfileIn( $fname );
1332 // $text = preg_replace( "/'{2,5}/", "", $text );
1333 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1334 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1335 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1336 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1337 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1338 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1339 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1340 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1341 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1342 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1343 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1344 $text = preg_replace( "/'''''/", "", $text );
1345 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1346 $text = preg_replace( "/''/", "", $text );
1348 wfProfileOut( $fname );
1353 * callback to replace [[target|caption]] kind of links, if
1354 * the target is category or image, leave it
1356 * @param $matches Array
1358 function linkReplace( $matches ) {
1359 $colon = strpos( $matches[1], ':' );
1360 if ( $colon === false )
1361 return $matches[2]; // replace with caption
1363 $ns = substr( $matches[1], 0, $colon );
1364 $index = $wgContLang->getNsIndex( $ns );
1365 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) )
1366 return $matches[0]; // return the whole thing
1373 * Simple & fast snippet extraction, but gives completely unrelevant
1376 * @param $text String
1377 * @param $terms Array
1378 * @param $contextlines Integer
1379 * @param $contextchars Integer
1382 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1384 $fname = __METHOD__
;
1386 $lines = explode( "\n", $text );
1388 $terms = implode( '|', $terms );
1389 $max = intval( $contextchars ) +
1;
1390 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1395 wfProfileIn( "$fname-extract" );
1396 foreach ( $lines as $line ) {
1397 if ( 0 == $contextlines ) {
1402 if ( ! preg_match( $pat1, $line, $m ) ) {
1406 // truncate function changes ... to relevant i18n message.
1407 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1409 if ( count( $m ) < 3 ) {
1412 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1417 $line = htmlspecialchars( $pre . $found . $post );
1418 $pat2 = '/(' . $terms . ")/i";
1419 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1421 $extract .= "${line}\n";
1423 wfProfileOut( "$fname-extract" );
1431 * Dummy class to be used when non-supported Database engine is present.
1432 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1433 * such as a LIKE search through titles.
1436 class SearchEngineDummy
extends SearchEngine
{