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();
45 * Perform a full text search query and return a result set.
46 * If title searches are not supported or disabled, return null.
49 * @param string $term raw search term
50 * @return SearchResultSet|Status|null
52 function searchText( $term ) {
57 * Perform a title-only 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|null
64 function searchTitle( $term ) {
69 * If this search backend can list/unlist redirects
70 * @deprecated since 1.18 Call supports( 'list-redirects' );
73 function acceptListRedirects() {
74 wfDeprecated( __METHOD__
, '1.18' );
75 return $this->supports( 'list-redirects' );
80 * @param $feature String
83 public function supports( $feature ) {
85 case 'list-redirects':
88 case 'title-suffix-filter':
95 * Way to pass custom data for engines
97 * @param $feature String
101 public function setFeatureData( $feature, $data ) {
102 $this->features
[$feature] = $data;
106 * When overridden in derived class, performs database-specific conversions
107 * on text to be used for searching or updating search index.
108 * Default implementation does nothing (simply returns $string).
110 * @param string $string String to process
113 public function normalizeText( $string ) {
116 // Some languages such as Chinese require word segmentation
117 return $wgContLang->segmentByWord( $string );
121 * Transform search term in cases when parts of the query came as different GET params (when supported)
122 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
124 function transformSearchTerm( $term ) {
129 * If an exact title match can be found, or a very slightly close match,
130 * return the title. If no match, returns NULL.
132 * @param $searchterm String
135 public static function getNearMatch( $searchterm ) {
136 $title = self
::getNearMatchInternal( $searchterm );
138 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
143 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
146 * @param $searchterm string
147 * @return SearchResultSet
149 public static function getNearMatchResultSet( $searchterm ) {
150 return new SearchNearMatchResultSet( self
::getNearMatch( $searchterm ) );
154 * Really find the title match.
157 private static function getNearMatchInternal( $searchterm ) {
158 global $wgContLang, $wgEnableSearchContributorsByIP;
160 $allSearchTerms = array( $searchterm );
162 if ( $wgContLang->hasVariants() ) {
163 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
167 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
171 foreach ( $allSearchTerms as $term ) {
173 # Exact match? No need to look further.
174 $title = Title
::newFromText( $term );
175 if ( is_null( $title ) ) {
179 # Try files if searching in the Media: namespace
180 if ( $title->getNamespace() == NS_MEDIA
) {
181 $title = Title
::makeTitle( NS_FILE
, $title->getText() );
184 if ( $title->isSpecialPage() ||
$title->isExternal() ||
$title->exists() ) {
188 # See if it still otherwise has content is some sane sense
189 $page = WikiPage
::factory( $title );
190 if ( $page->hasViewableContent() ) {
194 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
198 # Now try all lower case (i.e. first letter capitalized)
199 $title = Title
::newFromText( $wgContLang->lc( $term ) );
200 if ( $title && $title->exists() ) {
204 # Now try capitalized string
205 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
206 if ( $title && $title->exists() ) {
210 # Now try all upper case
211 $title = Title
::newFromText( $wgContLang->uc( $term ) );
212 if ( $title && $title->exists() ) {
216 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
217 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
218 if ( $title && $title->exists() ) {
222 // Give hooks a chance at better match variants
224 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
229 $title = Title
::newFromText( $searchterm );
231 # Entering an IP address goes to the contributions page
232 if ( $wgEnableSearchContributorsByIP ) {
233 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
234 || User
::isIP( trim( $searchterm ) ) ) {
235 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
239 # Entering a user goes to the user page whether it's there or not
240 if ( $title->getNamespace() == NS_USER
) {
244 # Go to images that exist even if there's no local page.
245 # There may have been a funny upload, or it may be on a shared
246 # file repository such as Wikimedia Commons.
247 if ( $title->getNamespace() == NS_FILE
) {
248 $image = wfFindFile( $title );
254 # MediaWiki namespace? Page may be "implied" if not customized.
255 # Just return it, with caps forced as the message system likes it.
256 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
257 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
260 # Quoted term? Try without the quotes...
262 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
263 return SearchEngine
::getNearMatch( $matches[1] );
269 public static function legalSearchChars() {
270 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
274 * Set the maximum number of results to return
275 * and how many to skip before returning the first.
277 * @param $limit Integer
278 * @param $offset Integer
280 function setLimitOffset( $limit, $offset = 0 ) {
281 $this->limit
= intval( $limit );
282 $this->offset
= intval( $offset );
286 * Set which namespaces the search should include.
287 * Give an array of namespace index numbers.
289 * @param $namespaces Array
291 function setNamespaces( $namespaces ) {
292 $this->namespaces
= $namespaces;
296 * Set whether the searcher should try to build a suggestion. Note: some searchers
297 * don't support building a suggestion in the first place and others don't respect
300 * @param boolean $showSuggestion should the searcher try to build suggestions
302 function setShowSuggestion( $showSuggestion ) {
303 $this->showSuggestion
= $showSuggestion;
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
338 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
344 * Make a list of searchable namespaces and their canonical names.
347 public static function searchableNamespaces() {
350 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
351 if ( $ns >= NS_MAIN
) {
356 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
361 * Extract default namespaces to search from the given user's
362 * settings, returning a list of index numbers.
367 public static function userNamespaces( $user ) {
368 global $wgSearchEverythingOnlyLoggedIn;
370 $searchableNamespaces = SearchEngine
::searchableNamespaces();
372 // get search everything preference, that can be set to be read for logged-in users
373 // it overrides other options
374 if ( !$wgSearchEverythingOnlyLoggedIn ||
$user->isLoggedIn() ) {
375 if ( $user->getOption( 'searcheverything' ) ) {
376 return array_keys( $searchableNamespaces );
381 foreach ( $searchableNamespaces as $ns => $name ) {
382 if ( $user->getOption( 'searchNs' . $ns ) ) {
391 * Find snippet highlight settings for all users
393 * @return Array contextlines, contextchars
395 public static function userHighlightPrefs() {
396 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
397 $contextchars = 75; // same as above.... :P
398 return array( $contextlines, $contextchars );
402 * An array of namespaces indexes to be searched by default
406 public static function defaultNamespaces() {
407 global $wgNamespacesToBeSearchedDefault;
409 return array_keys( $wgNamespacesToBeSearchedDefault, true );
413 * Get a list of namespace names useful for showing in tooltips
416 * @param $namespaces Array
419 public static function namespacesAsText( $namespaces ) {
422 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
423 foreach ( $formatted as $key => $ns ) {
424 if ( empty( $ns ) ) {
425 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
432 * Return the help namespaces to be shown on Special:Search
436 public static function helpNamespaces() {
437 global $wgNamespacesToBeSearchedHelp;
439 return array_keys( $wgNamespacesToBeSearchedHelp, true );
443 * Return a 'cleaned up' search string
445 * @param $text String
448 function filter( $text ) {
449 $lc = $this->legalSearchChars();
450 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
453 * Load up the appropriate search engine class for the currently
454 * active database backend, and return a configured instance.
456 * @param String $type Type of search backend, if not the default
457 * @return SearchEngine
459 public static function create( $type = null ) {
460 global $wgSearchType;
463 $alternatives = self
::getSearchTypes();
465 if ( $type && in_array( $type, $alternatives ) ) {
467 } elseif ( $wgSearchType !== null ) {
468 $class = $wgSearchType;
470 $dbr = wfGetDB( DB_SLAVE
);
471 $class = $dbr->getSearchEngine();
474 $search = new $class( $dbr );
479 * Return the search engines we support. If only $wgSearchType
480 * is set, it'll be an array of just that one item.
484 public static function getSearchTypes() {
485 global $wgSearchType, $wgSearchTypeAlternatives;
487 $alternatives = $wgSearchTypeAlternatives ?
: array();
488 array_unshift( $alternatives, $wgSearchType );
490 return $alternatives;
494 * Create or update the search index record for the given page.
495 * Title and text should be pre-processed.
499 * @param $title String
500 * @param $text String
502 function update( $id, $title, $text ) {
507 * Update a search index record's title only.
508 * Title should be pre-processed.
512 * @param $title String
514 function updateTitle( $id, $title ) {
519 * Delete an indexed page
520 * Title should be pre-processed.
523 * @param Integer $id Page id that was deleted
524 * @param String $title Title of page that was deleted
526 function delete( $id, $title ) {
531 * Get OpenSearch suggestion template
535 public static function getOpenSearchTemplate() {
536 global $wgOpenSearchTemplate, $wgCanonicalServer;
537 if ( $wgOpenSearchTemplate ) {
538 return $wgOpenSearchTemplate;
540 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
544 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
549 * Get the raw text for updating the index from a content object
550 * Nicer search backends could possibly do something cooler than
551 * just returning raw text
553 * @todo This isn't ideal, we'd really like to have content-specific handling here
554 * @param Title $t Title we're indexing
555 * @param Content $c Content of the page to index
558 public function getTextFromContent( Title
$t, Content
$c = null ) {
559 return $c ?
$c->getTextForSearchIndex() : '';
563 * If an implementation of SearchEngine handles all of its own text processing
564 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
565 * rather silly handling, it should return true here instead.
569 public function textAlreadyUpdatedForIndex() {
577 class SearchResultSet
{
579 * Fetch an array of regular expression fragments for matching
580 * the search terms as parsed by this engine in a text extract.
585 function termMatches() {
594 * Return true if results are included in this result set.
599 function hasResults() {
604 * Some search modes return a total hit count for the query
605 * in the entire article database. This may include pages
606 * in namespaces that would not be matched on the given
609 * Return null if no total hits number is supported.
613 function getTotalHits() {
618 * Some search modes return a suggested alternate term if there are
619 * no exact hits. Returns true if there is one on this set.
623 function hasSuggestion() {
628 * @return String: suggested query, null if none
630 function getSuggestionQuery() {
635 * @return String: HTML highlighted suggested query, '' if none
637 function getSuggestionSnippet() {
642 * Return information about how and from where the results were fetched,
643 * should be useful for diagnostics and debugging
652 * Return a result set of hits on other (multiple) wikis associated with this one
654 * @return SearchResultSet
656 function getInterwikiResults() {
661 * Check if there are results on other wikis
665 function hasInterwikiResults() {
666 return $this->getInterwikiResults() != null;
670 * Fetches next search result, or false.
673 * @return SearchResult
680 * Frees the result set, if applicable.
688 * This class is used for different SQL-based search engines shipped with MediaWiki
690 class SqlSearchResultSet
extends SearchResultSet
{
692 protected $mResultSet;
694 function __construct( $resultSet, $terms ) {
695 $this->mResultSet
= $resultSet;
696 $this->mTerms
= $terms;
699 function termMatches() {
700 return $this->mTerms
;
704 if ( $this->mResultSet
=== false ) {
708 return $this->mResultSet
->numRows();
712 if ( $this->mResultSet
=== false ) {
716 $row = $this->mResultSet
->fetchObject();
717 if ( $row === false ) {
721 return SearchResult
::newFromRow( $row );
725 if ( $this->mResultSet
=== false ) {
729 $this->mResultSet
->free();
736 class SearchResultTooMany
{
737 # # Some search engines may bail out if too many matches are found
741 * @todo FIXME: This class is horribly factored. It would probably be better to
742 * have a useful base class to which you pass some standard information, then
743 * let the fancy self-highlighters extend that.
751 protected $mRevision = null;
756 protected $mImage = null;
769 * Return a new SearchResult and initializes it with a title.
771 * @param $title Title
772 * @return SearchResult
774 public static function newFromTitle( $title ) {
775 $result = new self();
776 $result->initFromTitle( $title );
780 * Return a new SearchResult and initializes it with a row.
783 * @return SearchResult
785 public static function newFromRow( $row ) {
786 $result = new self();
787 $result->initFromRow( $row );
791 public function __construct( $row = null ) {
792 if ( !is_null( $row ) ) {
793 // Backwards compatibility with pre-1.17 callers
794 $this->initFromRow( $row );
799 * Initialize from a database row. Makes a Title and passes that to
804 protected function initFromRow( $row ) {
805 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
809 * Initialize from a Title and if possible initializes a corresponding
812 * @param $title Title
814 protected function initFromTitle( $title ) {
815 $this->mTitle
= $title;
816 if ( !is_null( $this->mTitle
) ) {
818 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
819 $this->mRevision
= Revision
::newFromTitle(
820 $this->mTitle
, $id, Revision
::READ_NORMAL
);
821 if ( $this->mTitle
->getNamespace() === NS_FILE
) {
822 $this->mImage
= wfFindFile( $this->mTitle
);
828 * Check if this is result points to an invalid title
832 function isBrokenTitle() {
833 return is_null( $this->mTitle
);
837 * Check if target page is missing, happens when index is out of date
841 function isMissingRevision() {
842 return !$this->mRevision
&& !$this->mImage
;
848 function getTitle() {
849 return $this->mTitle
;
853 * Get the file for this page, if one exists
857 return $this->mImage
;
861 * @return float|null if not supported
863 function getScore() {
868 * Lazy initialization of article text from DB
870 protected function initText() {
871 if ( !isset( $this->mText
) ) {
872 if ( $this->mRevision
!= null ) {
873 $this->mText
= SearchEngine
::create()
874 ->getTextFromContent( $this->mTitle
, $this->mRevision
->getContent() );
875 } else { // TODO: can we fetch raw wikitext for commons images?
882 * @param array $terms terms to highlight
883 * @return String: highlighted text snippet, null (and not '') if not supported
885 function getTextSnippet( $terms ) {
886 global $wgAdvancedSearchHighlighting;
889 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
890 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs();
891 $h = new SearchHighlighter();
892 if ( $wgAdvancedSearchHighlighting ) {
893 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
895 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
900 * @param array $terms terms to highlight
901 * @return String: highlighted title, '' if not supported
903 function getTitleSnippet( $terms ) {
908 * @param array $terms terms to highlight
909 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
911 function getRedirectSnippet( $terms ) {
916 * @return Title object for the redirect to this page, null if none or not supported
918 function getRedirectTitle() {
923 * @return string highlighted relevant section name, null if none or not supported
925 function getSectionSnippet() {
930 * @return Title object (pagename+fragment) for the section, null if none or not supported
932 function getSectionTitle() {
937 * @return String: timestamp
939 function getTimestamp() {
940 if ( $this->mRevision
) {
941 return $this->mRevision
->getTimestamp();
942 } elseif ( $this->mImage
) {
943 return $this->mImage
->getTimestamp();
949 * @return Integer: number of words
951 function getWordCount() {
953 return str_word_count( $this->mText
);
957 * @return Integer: size in bytes
959 function getByteSize() {
961 return strlen( $this->mText
);
965 * @return Boolean if hit has related articles
967 function hasRelated() {
972 * @return String: interwiki prefix of the title (return iw even if title is broken)
974 function getInterwikiPrefix() {
979 * Did this match file contents (eg: PDF/DJVU)?
981 function isFileMatch() {
986 * A SearchResultSet wrapper for SearchEngine::getNearMatch
988 class SearchNearMatchResultSet
extends SearchResultSet
{
989 private $fetched = false;
991 * @param $match mixed Title if matched, else null
993 public function __construct( $match ) {
994 $this->result
= $match;
996 public function hasResult() {
997 return (bool)$this->result
;
999 public function numRows() {
1000 return $this->hasResults() ?
1 : 0;
1002 public function next() {
1003 if ( $this->fetched ||
!$this->result
) {
1006 $this->fetched
= true;
1007 return SearchResult
::newFromTitle( $this->result
);
1012 * Highlight bits of wikitext
1016 class SearchHighlighter
{
1017 var $mCleanWikitext = true;
1019 function __construct( $cleanupWikitext = true ) {
1020 $this->mCleanWikitext
= $cleanupWikitext;
1024 * Default implementation of wikitext highlighting
1026 * @param $text String
1027 * @param array $terms terms to highlight (unescaped)
1028 * @param $contextlines Integer
1029 * @param $contextchars Integer
1032 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
1034 global $wgSearchHighlightBoundaries;
1035 $fname = __METHOD__
;
1037 if ( $text == '' ) {
1041 // spli text into text + templates/links/tables
1042 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
1043 // first capture group is for detecting nested templates/links/tables/references
1044 $endPatterns = array(
1045 1 => '/(\{\{)|(\}\})/', // template
1046 2 => '/(\[\[)|(\]\])/', // image
1047 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
1049 // @todo FIXME: This should prolly be a hook or something
1050 if ( function_exists( 'wfCite' ) ) {
1051 $spat .= '|(<ref>)'; // references via cite extension
1052 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
1055 $textExt = array(); // text extracts
1056 $otherExt = array(); // other extracts
1057 wfProfileIn( "$fname-split" );
1059 $textLen = strlen( $text );
1060 $count = 0; // sequence number to maintain ordering
1061 while ( $start < $textLen ) {
1062 // find start of template/image/table
1063 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
1065 foreach ( $matches as $key => $val ) {
1066 if ( $key > 0 && $val[1] != - 1 ) {
1068 // see if this is an image link
1069 $ns = substr( $val[0], 2, - 1 );
1070 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
) {
1075 $epat = $endPatterns[$key];
1076 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1082 // find end (and detect any nested elements)
1084 $offset = $start +
1;
1086 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
1087 if ( array_key_exists( 2, $endMatches ) ) {
1089 if ( $level == 0 ) {
1090 $len = strlen( $endMatches[2][0] );
1091 $off = $endMatches[2][1];
1092 $this->splitAndAdd( $otherExt, $count,
1093 substr( $text, $start, $off +
$len - $start ) );
1094 $start = $off +
$len;
1098 // end of nested element
1105 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
1108 // couldn't find appropriate closing tag, skip
1109 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1110 $start +
= strlen( $matches[0][0] );
1115 // else: add as text extract
1116 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1120 $all = $textExt +
$otherExt; // these have disjunct key sets
1122 wfProfileOut( "$fname-split" );
1125 foreach ( $terms as $index => $term ) {
1126 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1127 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1128 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1130 $terms[$index] = $term;
1133 $anyterm = implode( '|', $terms );
1134 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1136 // @todo FIXME: A hack to scale contextchars, a correct solution
1137 // would be to have contextchars actually be char and not byte
1138 // length, and do proper utf-8 substrings and lengths everywhere,
1139 // but PHP is making that very hard and unclean to implement :(
1140 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1141 $contextchars = intval( $contextchars * $scale );
1143 $patPre = "(^|$wgSearchHighlightBoundaries)";
1144 $patPost = "($wgSearchHighlightBoundaries|$)";
1146 $pat1 = "/(" . $phrase . ")/ui";
1147 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1149 wfProfileIn( "$fname-extract" );
1151 $left = $contextlines;
1153 $snippets = array();
1156 // show beginning only if it contains all words
1159 foreach ( $textExt as $index => $line ) {
1160 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1161 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1168 // check if first text contains all terms
1169 foreach ( $terms as $term ) {
1170 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1176 $snippets[$first] = $firstText;
1177 $offsets[$first] = 0;
1180 if ( ! $snippets ) {
1181 // match whole query on text
1182 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1183 // match whole query on templates/tables/images
1184 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1185 // match any words on text
1186 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1187 // match any words on templates/tables/images
1188 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1193 // add extra chars to each snippet to make snippets constant size
1194 $extended = array();
1195 if ( count( $snippets ) == 0 ) {
1196 // couldn't find the target words, just show beginning of article
1197 if ( array_key_exists( $first, $all ) ) {
1198 $targetchars = $contextchars * $contextlines;
1199 $snippets[$first] = '';
1200 $offsets[$first] = 0;
1203 // if begin of the article contains the whole phrase, show only that !!
1204 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1205 && $offsets[$first] < $contextchars * 2 ) {
1206 $snippets = array( $first => $snippets[$first] );
1209 // calc by how much to extend existing snippets
1210 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1213 foreach ( $snippets as $index => $line ) {
1214 $extended[$index] = $line;
1215 $len = strlen( $line );
1216 if ( $len < $targetchars - 20 ) {
1217 // complete this line
1218 if ( $len < strlen( $all[$index] ) ) {
1219 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1220 $len = strlen( $extended[$index] );
1225 while ( $len < $targetchars - 20
1226 && array_key_exists( $add, $all )
1227 && !array_key_exists( $add, $snippets ) ) {
1229 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1230 $extended[$add] = $tt;
1231 $len +
= strlen( $tt );
1237 // $snippets = array_map( 'htmlspecialchars', $extended );
1238 $snippets = $extended;
1241 foreach ( $snippets as $index => $line ) {
1242 if ( $last == - 1 ) {
1243 $extract .= $line; // first line
1244 } elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) ) {
1245 $extract .= " " . $line; // continous lines
1247 $extract .= '<b> ... </b>' . $line;
1253 $extract .= '<b> ... </b>';
1256 $processed = array();
1257 foreach ( $terms as $term ) {
1258 if ( ! isset( $processed[$term] ) ) {
1259 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1260 $extract = preg_replace( $pat3,
1261 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1262 $processed[$term] = true;
1266 wfProfileOut( "$fname-extract" );
1272 * Split text into lines and add it to extracts array
1274 * @param array $extracts index -> $line
1275 * @param $count Integer
1276 * @param $text String
1278 function splitAndAdd( &$extracts, &$count, $text ) {
1279 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1280 foreach ( $split as $line ) {
1281 $tt = trim( $line );
1283 $extracts[$count++
] = $tt;
1289 * Do manual case conversion for non-ascii chars
1291 * @param $matches Array
1294 function caseCallback( $matches ) {
1296 if ( strlen( $matches[0] ) > 1 ) {
1297 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1304 * Extract part of the text from start to end, but by
1305 * not chopping up words
1306 * @param $text String
1307 * @param $start Integer
1308 * @param $end Integer
1309 * @param $posStart Integer: (out) actual start position
1310 * @param $posEnd Integer: (out) actual end position
1313 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1314 if ( $start != 0 ) {
1315 $start = $this->position( $text, $start, 1 );
1317 if ( $end >= strlen( $text ) ) {
1318 $end = strlen( $text );
1320 $end = $this->position( $text, $end );
1323 if ( !is_null( $posStart ) ) {
1326 if ( !is_null( $posEnd ) ) {
1330 if ( $end > $start ) {
1331 return substr( $text, $start, $end - $start );
1338 * Find a nonletter near a point (index) in the text
1340 * @param $text String
1341 * @param $point Integer
1342 * @param $offset Integer: offset to found index
1343 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1345 function position( $text, $point, $offset = 0 ) {
1347 $s = max( 0, $point - $tolerance );
1348 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1350 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1351 return $m[0][1] +
$s +
$offset;
1353 // check if point is on a valid first UTF8 char
1354 $char = ord( $text[$point] );
1355 while ( $char >= 0x80 && $char < 0xc0 ) {
1356 // skip trailing bytes
1358 if ( $point >= strlen( $text ) ) {
1359 return strlen( $text );
1361 $char = ord( $text[$point] );
1369 * Search extracts for a pattern, and return snippets
1371 * @param string $pattern regexp for matching lines
1372 * @param array $extracts extracts to search
1373 * @param $linesleft Integer: number of extracts to make
1374 * @param $contextchars Integer: length of snippet
1375 * @param array $out map for highlighted snippets
1376 * @param array $offsets map of starting points of snippets
1379 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1380 if ( $linesleft == 0 ) {
1381 return; // nothing to do
1383 foreach ( $extracts as $index => $line ) {
1384 if ( array_key_exists( $index, $out ) ) {
1385 continue; // this line already highlighted
1389 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) ) {
1394 $len = strlen( $m[0][0] );
1395 if ( $offset +
$len < $contextchars ) {
1397 } elseif ( $len > $contextchars ) {
1400 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1403 $end = $begin +
$contextchars;
1406 // basic snippet from this line
1407 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1408 $offsets[$index] = $posBegin;
1410 if ( $linesleft == 0 ) {
1417 * Basic wikitext removal
1421 function removeWiki( $text ) {
1422 $fname = __METHOD__
;
1423 wfProfileIn( $fname );
1425 // $text = preg_replace( "/'{2,5}/", "", $text );
1426 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1427 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1428 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1429 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1430 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1431 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1432 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1433 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1434 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1435 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1436 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1437 $text = preg_replace( "/'''''/", "", $text );
1438 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1439 $text = preg_replace( "/''/", "", $text );
1441 wfProfileOut( $fname );
1446 * callback to replace [[target|caption]] kind of links, if
1447 * the target is category or image, leave it
1449 * @param $matches Array
1451 function linkReplace( $matches ) {
1452 $colon = strpos( $matches[1], ':' );
1453 if ( $colon === false ) {
1454 return $matches[2]; // replace with caption
1457 $ns = substr( $matches[1], 0, $colon );
1458 $index = $wgContLang->getNsIndex( $ns );
1459 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) ) {
1460 return $matches[0]; // return the whole thing
1467 * Simple & fast snippet extraction, but gives completely unrelevant
1470 * @param $text String
1471 * @param $terms Array
1472 * @param $contextlines Integer
1473 * @param $contextchars Integer
1476 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1478 $fname = __METHOD__
;
1480 $lines = explode( "\n", $text );
1482 $terms = implode( '|', $terms );
1483 $max = intval( $contextchars ) +
1;
1484 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1489 wfProfileIn( "$fname-extract" );
1490 foreach ( $lines as $line ) {
1491 if ( 0 == $contextlines ) {
1496 if ( ! preg_match( $pat1, $line, $m ) ) {
1500 // truncate function changes ... to relevant i18n message.
1501 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1503 if ( count( $m ) < 3 ) {
1506 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1511 $line = htmlspecialchars( $pre . $found . $post );
1512 $pat2 = '/(' . $terms . ")/i";
1513 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1515 $extract .= "${line}\n";
1517 wfProfileOut( "$fname-extract" );
1525 * Dummy class to be used when non-supported Database engine is present.
1526 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1527 * such as a LIKE search through titles.
1530 class SearchEngineDummy
extends SearchEngine
{