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;
39 protected $showSuggestion = true;
42 protected $features = array();
49 function __construct( $db = null ) {
53 $this->db
= wfGetDB( DB_SLAVE
);
58 * Perform a full text search query and return a result set.
59 * If title searches are not supported or disabled, return null.
62 * @param string $term raw search term
63 * @return SearchResultSet|Status|null
65 function searchText( $term ) {
70 * Perform a title-only search query and return a result set.
71 * If title searches are not supported or disabled, return null.
74 * @param string $term raw search term
75 * @return SearchResultSet|null
77 function searchTitle( $term ) {
82 * If this search backend can list/unlist redirects
83 * @deprecated since 1.18 Call supports( 'list-redirects' );
86 function acceptListRedirects() {
87 wfDeprecated( __METHOD__
, '1.18' );
88 return $this->supports( 'list-redirects' );
93 * @param $feature String
96 public function supports( $feature ) {
98 case 'list-redirects':
101 case 'title-suffix-filter':
108 * Way to pass custom data for engines
110 * @param $feature String
114 public function setFeatureData( $feature, $data ) {
115 $this->features
[$feature] = $data;
119 * When overridden in derived class, performs database-specific conversions
120 * on text to be used for searching or updating search index.
121 * Default implementation does nothing (simply returns $string).
123 * @param string $string String to process
126 public function normalizeText( $string ) {
129 // Some languages such as Chinese require word segmentation
130 return $wgContLang->segmentByWord( $string );
134 * Transform search term in cases when parts of the query came as different GET params (when supported)
135 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
137 function transformSearchTerm( $term ) {
142 * If an exact title match can be found, or a very slightly close match,
143 * return the title. If no match, returns NULL.
145 * @param $searchterm String
148 public static function getNearMatch( $searchterm ) {
149 $title = self
::getNearMatchInternal( $searchterm );
151 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
156 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
159 * @param $searchterm string
160 * @return SearchResultSet
162 public static function getNearMatchResultSet( $searchterm ) {
163 return new SearchNearMatchResultSet( self
::getNearMatch( $searchterm ) );
167 * Really find the title match.
170 private static function getNearMatchInternal( $searchterm ) {
171 global $wgContLang, $wgEnableSearchContributorsByIP;
173 $allSearchTerms = array( $searchterm );
175 if ( $wgContLang->hasVariants() ) {
176 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
180 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
184 foreach ( $allSearchTerms as $term ) {
186 # Exact match? No need to look further.
187 $title = Title
::newFromText( $term );
188 if ( is_null( $title ) ) {
192 # Try files if searching in the Media: namespace
193 if ( $title->getNamespace() == NS_MEDIA
) {
194 $title = Title
::makeTitle( NS_FILE
, $title->getText() );
197 if ( $title->isSpecialPage() ||
$title->isExternal() ||
$title->exists() ) {
201 # See if it still otherwise has content is some sane sense
202 $page = WikiPage
::factory( $title );
203 if ( $page->hasViewableContent() ) {
207 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
211 # Now try all lower case (i.e. first letter capitalized)
212 $title = Title
::newFromText( $wgContLang->lc( $term ) );
213 if ( $title && $title->exists() ) {
217 # Now try capitalized string
218 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
219 if ( $title && $title->exists() ) {
223 # Now try all upper case
224 $title = Title
::newFromText( $wgContLang->uc( $term ) );
225 if ( $title && $title->exists() ) {
229 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
230 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
231 if ( $title && $title->exists() ) {
235 // Give hooks a chance at better match variants
237 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
242 $title = Title
::newFromText( $searchterm );
244 # Entering an IP address goes to the contributions page
245 if ( $wgEnableSearchContributorsByIP ) {
246 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
247 || User
::isIP( trim( $searchterm ) ) ) {
248 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 * Set whether the searcher should try to build a suggestion. Note: some searchers
310 * don't support building a suggestion in the first place and others don't respect
313 * @param boolean $showSuggestion should the searcher try to build suggestions
315 function setShowSuggestion( $showSuggestion ) {
316 $this->showSuggestion
= $showSuggestion;
320 * Parse some common prefixes: all (search everything)
323 * @param $query String
326 function replacePrefixes( $query ) {
330 if ( strpos( $query, ':' ) === false ) { // nothing to do
331 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
335 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
336 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
337 $this->namespaces
= null;
338 $parsed = substr( $query, strlen( $allkeyword ) );
339 } elseif ( strpos( $query, ':' ) !== false ) {
340 $prefix = substr( $query, 0, strpos( $query, ':' ) );
341 $index = $wgContLang->getNsIndex( $prefix );
342 if ( $index !== false ) {
343 $this->namespaces
= array( $index );
344 $parsed = substr( $query, strlen( $prefix ) +
1 );
347 if ( trim( $parsed ) == '' ) {
348 $parsed = $query; // prefix was the whole query
351 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
357 * Make a list of searchable namespaces and their canonical names.
360 public static function searchableNamespaces() {
363 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
364 if ( $ns >= NS_MAIN
) {
369 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
374 * Extract default namespaces to search from the given user's
375 * settings, returning a list of index numbers.
380 public static function userNamespaces( $user ) {
381 global $wgSearchEverythingOnlyLoggedIn;
383 $searchableNamespaces = SearchEngine
::searchableNamespaces();
385 // get search everything preference, that can be set to be read for logged-in users
386 // it overrides other options
387 if ( !$wgSearchEverythingOnlyLoggedIn ||
$user->isLoggedIn() ) {
388 if ( $user->getOption( 'searcheverything' ) ) {
389 return array_keys( $searchableNamespaces );
394 foreach ( $searchableNamespaces as $ns => $name ) {
395 if ( $user->getOption( 'searchNs' . $ns ) ) {
404 * Find snippet highlight settings for all users
406 * @return Array contextlines, contextchars
408 public static function userHighlightPrefs() {
409 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
410 $contextchars = 75; // same as above.... :P
411 return array( $contextlines, $contextchars );
415 * An array of namespaces indexes to be searched by default
419 public static function defaultNamespaces() {
420 global $wgNamespacesToBeSearchedDefault;
422 return array_keys( $wgNamespacesToBeSearchedDefault, true );
426 * Get a list of namespace names useful for showing in tooltips
429 * @param $namespaces Array
432 public static function namespacesAsText( $namespaces ) {
435 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
436 foreach ( $formatted as $key => $ns ) {
437 if ( empty( $ns ) ) {
438 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
445 * Return the help namespaces to be shown on Special:Search
449 public static function helpNamespaces() {
450 global $wgNamespacesToBeSearchedHelp;
452 return array_keys( $wgNamespacesToBeSearchedHelp, true );
456 * Return a 'cleaned up' search string
458 * @param $text String
461 function filter( $text ) {
462 $lc = $this->legalSearchChars();
463 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
466 * Load up the appropriate search engine class for the currently
467 * active database backend, and return a configured instance.
469 * @param String $type Type of search backend, if not the default
470 * @return SearchEngine
472 public static function create( $type = null ) {
473 global $wgSearchType;
476 $alternatives = self
::getSearchTypes();
478 if ( $type && in_array( $type, $alternatives ) ) {
480 } elseif ( $wgSearchType !== null ) {
481 $class = $wgSearchType;
483 $dbr = wfGetDB( DB_SLAVE
);
484 $class = $dbr->getSearchEngine();
487 $search = new $class( $dbr );
488 $search->setLimitOffset( 0, 0 );
493 * Return the search engines we support. If only $wgSearchType
494 * is set, it'll be an array of just that one item.
498 public static function getSearchTypes() {
499 global $wgSearchType, $wgSearchTypeAlternatives;
501 $alternatives = $wgSearchTypeAlternatives ?
: array();
502 array_unshift( $alternatives, $wgSearchType );
504 return $alternatives;
508 * Create or update the search index record for the given page.
509 * Title and text should be pre-processed.
513 * @param $title String
514 * @param $text String
516 function update( $id, $title, $text ) {
521 * Update a search index record's title only.
522 * Title should be pre-processed.
526 * @param $title String
528 function updateTitle( $id, $title ) {
533 * Delete an indexed page
534 * Title should be pre-processed.
537 * @param Integer $id Page id that was deleted
538 * @param String $title Title of page that was deleted
540 function delete( $id, $title ) {
545 * Get OpenSearch suggestion template
549 public static function getOpenSearchTemplate() {
550 global $wgOpenSearchTemplate, $wgCanonicalServer;
551 if ( $wgOpenSearchTemplate ) {
552 return $wgOpenSearchTemplate;
554 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
558 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
563 * Get the raw text for updating the index from a content object
564 * Nicer search backends could possibly do something cooler than
565 * just returning raw text
567 * @todo This isn't ideal, we'd really like to have content-specific handling here
568 * @param Title $t Title we're indexing
569 * @param Content $c Content of the page to index
572 public function getTextFromContent( Title
$t, Content
$c = null ) {
573 return $c ?
$c->getTextForSearchIndex() : '';
577 * If an implementation of SearchEngine handles all of its own text processing
578 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
579 * rather silly handling, it should return true here instead.
583 public function textAlreadyUpdatedForIndex() {
591 class SearchResultSet
{
593 * Fetch an array of regular expression fragments for matching
594 * the search terms as parsed by this engine in a text extract.
599 function termMatches() {
608 * Return true if results are included in this result set.
613 function hasResults() {
618 * Some search modes return a total hit count for the query
619 * in the entire article database. This may include pages
620 * in namespaces that would not be matched on the given
623 * Return null if no total hits number is supported.
627 function getTotalHits() {
632 * Some search modes return a suggested alternate term if there are
633 * no exact hits. Returns true if there is one on this set.
637 function hasSuggestion() {
642 * @return String: suggested query, null if none
644 function getSuggestionQuery() {
649 * @return String: HTML highlighted suggested query, '' if none
651 function getSuggestionSnippet() {
656 * Return information about how and from where the results were fetched,
657 * should be useful for diagnostics and debugging
666 * Return a result set of hits on other (multiple) wikis associated with this one
668 * @return SearchResultSet
670 function getInterwikiResults() {
675 * Check if there are results on other wikis
679 function hasInterwikiResults() {
680 return $this->getInterwikiResults() != null;
684 * Fetches next search result, or false.
687 * @return SearchResult
694 * Frees the result set, if applicable.
702 * This class is used for different SQL-based search engines shipped with MediaWiki
704 class SqlSearchResultSet
extends SearchResultSet
{
706 protected $mResultSet;
708 function __construct( $resultSet, $terms ) {
709 $this->mResultSet
= $resultSet;
710 $this->mTerms
= $terms;
713 function termMatches() {
714 return $this->mTerms
;
718 if ( $this->mResultSet
=== false ) {
722 return $this->mResultSet
->numRows();
726 if ( $this->mResultSet
=== false ) {
730 $row = $this->mResultSet
->fetchObject();
731 if ( $row === false ) {
735 return SearchResult
::newFromRow( $row );
739 if ( $this->mResultSet
=== false ) {
743 $this->mResultSet
->free();
750 class SearchResultTooMany
{
751 # # Some search engines may bail out if too many matches are found
755 * @todo FIXME: This class is horribly factored. It would probably be better to
756 * have a useful base class to which you pass some standard information, then
757 * let the fancy self-highlighters extend that.
765 protected $mRevision = null;
770 protected $mImage = null;
783 * Return a new SearchResult and initializes it with a title.
785 * @param $title Title
786 * @return SearchResult
788 public static function newFromTitle( $title ) {
789 $result = new self();
790 $result->initFromTitle( $title );
794 * Return a new SearchResult and initializes it with a row.
797 * @return SearchResult
799 public static function newFromRow( $row ) {
800 $result = new self();
801 $result->initFromRow( $row );
805 public function __construct( $row = null ) {
806 if ( !is_null( $row ) ) {
807 // Backwards compatibility with pre-1.17 callers
808 $this->initFromRow( $row );
813 * Initialize from a database row. Makes a Title and passes that to
818 protected function initFromRow( $row ) {
819 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
823 * Initialize from a Title and if possible initializes a corresponding
826 * @param $title Title
828 protected function initFromTitle( $title ) {
829 $this->mTitle
= $title;
830 if ( !is_null( $this->mTitle
) ) {
832 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
833 $this->mRevision
= Revision
::newFromTitle(
834 $this->mTitle
, $id, Revision
::READ_NORMAL
);
835 if ( $this->mTitle
->getNamespace() === NS_FILE
) {
836 $this->mImage
= wfFindFile( $this->mTitle
);
842 * Check if this is result points to an invalid title
846 function isBrokenTitle() {
847 return is_null( $this->mTitle
);
851 * Check if target page is missing, happens when index is out of date
855 function isMissingRevision() {
856 return !$this->mRevision
&& !$this->mImage
;
862 function getTitle() {
863 return $this->mTitle
;
867 * Get the file for this page, if one exists
871 return $this->mImage
;
875 * @return float|null if not supported
877 function getScore() {
882 * Lazy initialization of article text from DB
884 protected function initText() {
885 if ( !isset( $this->mText
) ) {
886 if ( $this->mRevision
!= null ) {
887 $this->mText
= SearchEngine
::create()
888 ->getTextFromContent( $this->mTitle
, $this->mRevision
->getContent() );
889 } else { // TODO: can we fetch raw wikitext for commons images?
896 * @param array $terms terms to highlight
897 * @return String: highlighted text snippet, null (and not '') if not supported
899 function getTextSnippet( $terms ) {
900 global $wgAdvancedSearchHighlighting;
903 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
904 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs();
905 $h = new SearchHighlighter();
906 if ( $wgAdvancedSearchHighlighting ) {
907 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
909 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
914 * @param array $terms terms to highlight
915 * @return String: highlighted title, '' if not supported
917 function getTitleSnippet( $terms ) {
922 * @param array $terms terms to highlight
923 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
925 function getRedirectSnippet( $terms ) {
930 * @return Title object for the redirect to this page, null if none or not supported
932 function getRedirectTitle() {
937 * @return string highlighted relevant section name, null if none or not supported
939 function getSectionSnippet() {
944 * @return Title object (pagename+fragment) for the section, null if none or not supported
946 function getSectionTitle() {
951 * @return String: timestamp
953 function getTimestamp() {
954 if ( $this->mRevision
) {
955 return $this->mRevision
->getTimestamp();
956 } elseif ( $this->mImage
) {
957 return $this->mImage
->getTimestamp();
963 * @return Integer: number of words
965 function getWordCount() {
967 return str_word_count( $this->mText
);
971 * @return Integer: size in bytes
973 function getByteSize() {
975 return strlen( $this->mText
);
979 * @return Boolean if hit has related articles
981 function hasRelated() {
986 * @return String: interwiki prefix of the title (return iw even if title is broken)
988 function getInterwikiPrefix() {
993 * A SearchResultSet wrapper for SearchEngine::getNearMatch
995 class SearchNearMatchResultSet
extends SearchResultSet
{
996 private $fetched = false;
998 * @param $match mixed Title if matched, else null
1000 public function __construct( $match ) {
1001 $this->result
= $match;
1003 public function hasResult() {
1004 return (bool)$this->result
;
1006 public function numRows() {
1007 return $this->hasResults() ?
1 : 0;
1009 public function next() {
1010 if ( $this->fetched ||
!$this->result
) {
1013 $this->fetched
= true;
1014 return SearchResult
::newFromTitle( $this->result
);
1019 * Highlight bits of wikitext
1023 class SearchHighlighter
{
1024 var $mCleanWikitext = true;
1026 function __construct( $cleanupWikitext = true ) {
1027 $this->mCleanWikitext
= $cleanupWikitext;
1031 * Default implementation of wikitext highlighting
1033 * @param $text String
1034 * @param array $terms terms to highlight (unescaped)
1035 * @param $contextlines Integer
1036 * @param $contextchars Integer
1039 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
1041 global $wgSearchHighlightBoundaries;
1042 $fname = __METHOD__
;
1044 if ( $text == '' ) {
1048 // spli text into text + templates/links/tables
1049 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
1050 // first capture group is for detecting nested templates/links/tables/references
1051 $endPatterns = array(
1052 1 => '/(\{\{)|(\}\})/', // template
1053 2 => '/(\[\[)|(\]\])/', // image
1054 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
1056 // @todo FIXME: This should prolly be a hook or something
1057 if ( function_exists( 'wfCite' ) ) {
1058 $spat .= '|(<ref>)'; // references via cite extension
1059 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
1062 $textExt = array(); // text extracts
1063 $otherExt = array(); // other extracts
1064 wfProfileIn( "$fname-split" );
1066 $textLen = strlen( $text );
1067 $count = 0; // sequence number to maintain ordering
1068 while ( $start < $textLen ) {
1069 // find start of template/image/table
1070 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
1072 foreach ( $matches as $key => $val ) {
1073 if ( $key > 0 && $val[1] != - 1 ) {
1075 // see if this is an image link
1076 $ns = substr( $val[0], 2, - 1 );
1077 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
) {
1082 $epat = $endPatterns[$key];
1083 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1089 // find end (and detect any nested elements)
1091 $offset = $start +
1;
1093 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
1094 if ( array_key_exists( 2, $endMatches ) ) {
1096 if ( $level == 0 ) {
1097 $len = strlen( $endMatches[2][0] );
1098 $off = $endMatches[2][1];
1099 $this->splitAndAdd( $otherExt, $count,
1100 substr( $text, $start, $off +
$len - $start ) );
1101 $start = $off +
$len;
1105 // end of nested element
1112 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
1115 // couldn't find appropriate closing tag, skip
1116 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1117 $start +
= strlen( $matches[0][0] );
1122 // else: add as text extract
1123 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1127 $all = $textExt +
$otherExt; // these have disjunct key sets
1129 wfProfileOut( "$fname-split" );
1132 foreach ( $terms as $index => $term ) {
1133 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1134 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1135 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1137 $terms[$index] = $term;
1140 $anyterm = implode( '|', $terms );
1141 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1143 // @todo FIXME: A hack to scale contextchars, a correct solution
1144 // would be to have contextchars actually be char and not byte
1145 // length, and do proper utf-8 substrings and lengths everywhere,
1146 // but PHP is making that very hard and unclean to implement :(
1147 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1148 $contextchars = intval( $contextchars * $scale );
1150 $patPre = "(^|$wgSearchHighlightBoundaries)";
1151 $patPost = "($wgSearchHighlightBoundaries|$)";
1153 $pat1 = "/(" . $phrase . ")/ui";
1154 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1156 wfProfileIn( "$fname-extract" );
1158 $left = $contextlines;
1160 $snippets = array();
1163 // show beginning only if it contains all words
1166 foreach ( $textExt as $index => $line ) {
1167 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1168 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1175 // check if first text contains all terms
1176 foreach ( $terms as $term ) {
1177 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1183 $snippets[$first] = $firstText;
1184 $offsets[$first] = 0;
1187 if ( ! $snippets ) {
1188 // match whole query on text
1189 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1190 // match whole query on templates/tables/images
1191 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1192 // match any words on text
1193 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1194 // match any words on templates/tables/images
1195 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1200 // add extra chars to each snippet to make snippets constant size
1201 $extended = array();
1202 if ( count( $snippets ) == 0 ) {
1203 // couldn't find the target words, just show beginning of article
1204 if ( array_key_exists( $first, $all ) ) {
1205 $targetchars = $contextchars * $contextlines;
1206 $snippets[$first] = '';
1207 $offsets[$first] = 0;
1210 // if begin of the article contains the whole phrase, show only that !!
1211 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1212 && $offsets[$first] < $contextchars * 2 ) {
1213 $snippets = array( $first => $snippets[$first] );
1216 // calc by how much to extend existing snippets
1217 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1220 foreach ( $snippets as $index => $line ) {
1221 $extended[$index] = $line;
1222 $len = strlen( $line );
1223 if ( $len < $targetchars - 20 ) {
1224 // complete this line
1225 if ( $len < strlen( $all[$index] ) ) {
1226 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1227 $len = strlen( $extended[$index] );
1232 while ( $len < $targetchars - 20
1233 && array_key_exists( $add, $all )
1234 && !array_key_exists( $add, $snippets ) ) {
1236 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1237 $extended[$add] = $tt;
1238 $len +
= strlen( $tt );
1244 // $snippets = array_map( 'htmlspecialchars', $extended );
1245 $snippets = $extended;
1248 foreach ( $snippets as $index => $line ) {
1249 if ( $last == - 1 ) {
1250 $extract .= $line; // first line
1251 } elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) ) {
1252 $extract .= " " . $line; // continous lines
1254 $extract .= '<b> ... </b>' . $line;
1260 $extract .= '<b> ... </b>';
1263 $processed = array();
1264 foreach ( $terms as $term ) {
1265 if ( ! isset( $processed[$term] ) ) {
1266 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1267 $extract = preg_replace( $pat3,
1268 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1269 $processed[$term] = true;
1273 wfProfileOut( "$fname-extract" );
1279 * Split text into lines and add it to extracts array
1281 * @param array $extracts index -> $line
1282 * @param $count Integer
1283 * @param $text String
1285 function splitAndAdd( &$extracts, &$count, $text ) {
1286 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1287 foreach ( $split as $line ) {
1288 $tt = trim( $line );
1290 $extracts[$count++
] = $tt;
1296 * Do manual case conversion for non-ascii chars
1298 * @param $matches Array
1301 function caseCallback( $matches ) {
1303 if ( strlen( $matches[0] ) > 1 ) {
1304 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1311 * Extract part of the text from start to end, but by
1312 * not chopping up words
1313 * @param $text String
1314 * @param $start Integer
1315 * @param $end Integer
1316 * @param $posStart Integer: (out) actual start position
1317 * @param $posEnd Integer: (out) actual end position
1320 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1321 if ( $start != 0 ) {
1322 $start = $this->position( $text, $start, 1 );
1324 if ( $end >= strlen( $text ) ) {
1325 $end = strlen( $text );
1327 $end = $this->position( $text, $end );
1330 if ( !is_null( $posStart ) ) {
1333 if ( !is_null( $posEnd ) ) {
1337 if ( $end > $start ) {
1338 return substr( $text, $start, $end - $start );
1345 * Find a nonletter near a point (index) in the text
1347 * @param $text String
1348 * @param $point Integer
1349 * @param $offset Integer: offset to found index
1350 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1352 function position( $text, $point, $offset = 0 ) {
1354 $s = max( 0, $point - $tolerance );
1355 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1357 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1358 return $m[0][1] +
$s +
$offset;
1360 // check if point is on a valid first UTF8 char
1361 $char = ord( $text[$point] );
1362 while ( $char >= 0x80 && $char < 0xc0 ) {
1363 // skip trailing bytes
1365 if ( $point >= strlen( $text ) ) {
1366 return strlen( $text );
1368 $char = ord( $text[$point] );
1376 * Search extracts for a pattern, and return snippets
1378 * @param string $pattern regexp for matching lines
1379 * @param array $extracts extracts to search
1380 * @param $linesleft Integer: number of extracts to make
1381 * @param $contextchars Integer: length of snippet
1382 * @param array $out map for highlighted snippets
1383 * @param array $offsets map of starting points of snippets
1386 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1387 if ( $linesleft == 0 ) {
1388 return; // nothing to do
1390 foreach ( $extracts as $index => $line ) {
1391 if ( array_key_exists( $index, $out ) ) {
1392 continue; // this line already highlighted
1396 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) ) {
1401 $len = strlen( $m[0][0] );
1402 if ( $offset +
$len < $contextchars ) {
1404 } elseif ( $len > $contextchars ) {
1407 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1410 $end = $begin +
$contextchars;
1413 // basic snippet from this line
1414 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1415 $offsets[$index] = $posBegin;
1417 if ( $linesleft == 0 ) {
1424 * Basic wikitext removal
1428 function removeWiki( $text ) {
1429 $fname = __METHOD__
;
1430 wfProfileIn( $fname );
1432 // $text = preg_replace( "/'{2,5}/", "", $text );
1433 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1434 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1435 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1436 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1437 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1438 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1439 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1440 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1441 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1442 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1443 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1444 $text = preg_replace( "/'''''/", "", $text );
1445 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1446 $text = preg_replace( "/''/", "", $text );
1448 wfProfileOut( $fname );
1453 * callback to replace [[target|caption]] kind of links, if
1454 * the target is category or image, leave it
1456 * @param $matches Array
1458 function linkReplace( $matches ) {
1459 $colon = strpos( $matches[1], ':' );
1460 if ( $colon === false ) {
1461 return $matches[2]; // replace with caption
1464 $ns = substr( $matches[1], 0, $colon );
1465 $index = $wgContLang->getNsIndex( $ns );
1466 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) ) {
1467 return $matches[0]; // return the whole thing
1474 * Simple & fast snippet extraction, but gives completely unrelevant
1477 * @param $text String
1478 * @param $terms Array
1479 * @param $contextlines Integer
1480 * @param $contextchars Integer
1483 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1485 $fname = __METHOD__
;
1487 $lines = explode( "\n", $text );
1489 $terms = implode( '|', $terms );
1490 $max = intval( $contextchars ) +
1;
1491 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1496 wfProfileIn( "$fname-extract" );
1497 foreach ( $lines as $line ) {
1498 if ( 0 == $contextlines ) {
1503 if ( ! preg_match( $pat1, $line, $m ) ) {
1507 // truncate function changes ... to relevant i18n message.
1508 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1510 if ( count( $m ) < 3 ) {
1513 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1518 $line = htmlspecialchars( $pre . $found . $post );
1519 $pat2 = '/(' . $terms . ")/i";
1520 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1522 $extract .= "${line}\n";
1524 wfProfileOut( "$fname-extract" );
1532 * Dummy class to be used when non-supported Database engine is present.
1533 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1534 * such as a LIKE search through titles.
1537 class SearchEngineDummy
extends SearchEngine
{