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 );
475 $search->setLimitOffset( 0, 0 );
480 * Return the search engines we support. If only $wgSearchType
481 * is set, it'll be an array of just that one item.
485 public static function getSearchTypes() {
486 global $wgSearchType, $wgSearchTypeAlternatives;
488 $alternatives = $wgSearchTypeAlternatives ?
: array();
489 array_unshift( $alternatives, $wgSearchType );
491 return $alternatives;
495 * Create or update the search index record for the given page.
496 * Title and text should be pre-processed.
500 * @param $title String
501 * @param $text String
503 function update( $id, $title, $text ) {
508 * Update a search index record's title only.
509 * Title should be pre-processed.
513 * @param $title String
515 function updateTitle( $id, $title ) {
520 * Delete an indexed page
521 * Title should be pre-processed.
524 * @param Integer $id Page id that was deleted
525 * @param String $title Title of page that was deleted
527 function delete( $id, $title ) {
532 * Get OpenSearch suggestion template
536 public static function getOpenSearchTemplate() {
537 global $wgOpenSearchTemplate, $wgCanonicalServer;
538 if ( $wgOpenSearchTemplate ) {
539 return $wgOpenSearchTemplate;
541 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
545 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
550 * Get the raw text for updating the index from a content object
551 * Nicer search backends could possibly do something cooler than
552 * just returning raw text
554 * @todo This isn't ideal, we'd really like to have content-specific handling here
555 * @param Title $t Title we're indexing
556 * @param Content $c Content of the page to index
559 public function getTextFromContent( Title
$t, Content
$c = null ) {
560 return $c ?
$c->getTextForSearchIndex() : '';
564 * If an implementation of SearchEngine handles all of its own text processing
565 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
566 * rather silly handling, it should return true here instead.
570 public function textAlreadyUpdatedForIndex() {
578 class SearchResultSet
{
580 * Fetch an array of regular expression fragments for matching
581 * the search terms as parsed by this engine in a text extract.
586 function termMatches() {
595 * Return true if results are included in this result set.
600 function hasResults() {
605 * Some search modes return a total hit count for the query
606 * in the entire article database. This may include pages
607 * in namespaces that would not be matched on the given
610 * Return null if no total hits number is supported.
614 function getTotalHits() {
619 * Some search modes return a suggested alternate term if there are
620 * no exact hits. Returns true if there is one on this set.
624 function hasSuggestion() {
629 * @return String: suggested query, null if none
631 function getSuggestionQuery() {
636 * @return String: HTML highlighted suggested query, '' if none
638 function getSuggestionSnippet() {
643 * Return information about how and from where the results were fetched,
644 * should be useful for diagnostics and debugging
653 * Return a result set of hits on other (multiple) wikis associated with this one
655 * @return SearchResultSet
657 function getInterwikiResults() {
662 * Check if there are results on other wikis
666 function hasInterwikiResults() {
667 return $this->getInterwikiResults() != null;
671 * Fetches next search result, or false.
674 * @return SearchResult
681 * Frees the result set, if applicable.
689 * This class is used for different SQL-based search engines shipped with MediaWiki
691 class SqlSearchResultSet
extends SearchResultSet
{
693 protected $mResultSet;
695 function __construct( $resultSet, $terms ) {
696 $this->mResultSet
= $resultSet;
697 $this->mTerms
= $terms;
700 function termMatches() {
701 return $this->mTerms
;
705 if ( $this->mResultSet
=== false ) {
709 return $this->mResultSet
->numRows();
713 if ( $this->mResultSet
=== false ) {
717 $row = $this->mResultSet
->fetchObject();
718 if ( $row === false ) {
722 return SearchResult
::newFromRow( $row );
726 if ( $this->mResultSet
=== false ) {
730 $this->mResultSet
->free();
737 class SearchResultTooMany
{
738 # # Some search engines may bail out if too many matches are found
742 * @todo FIXME: This class is horribly factored. It would probably be better to
743 * have a useful base class to which you pass some standard information, then
744 * let the fancy self-highlighters extend that.
752 protected $mRevision = null;
757 protected $mImage = null;
770 * Return a new SearchResult and initializes it with a title.
772 * @param $title Title
773 * @return SearchResult
775 public static function newFromTitle( $title ) {
776 $result = new self();
777 $result->initFromTitle( $title );
781 * Return a new SearchResult and initializes it with a row.
784 * @return SearchResult
786 public static function newFromRow( $row ) {
787 $result = new self();
788 $result->initFromRow( $row );
792 public function __construct( $row = null ) {
793 if ( !is_null( $row ) ) {
794 // Backwards compatibility with pre-1.17 callers
795 $this->initFromRow( $row );
800 * Initialize from a database row. Makes a Title and passes that to
805 protected function initFromRow( $row ) {
806 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
810 * Initialize from a Title and if possible initializes a corresponding
813 * @param $title Title
815 protected function initFromTitle( $title ) {
816 $this->mTitle
= $title;
817 if ( !is_null( $this->mTitle
) ) {
819 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
820 $this->mRevision
= Revision
::newFromTitle(
821 $this->mTitle
, $id, Revision
::READ_NORMAL
);
822 if ( $this->mTitle
->getNamespace() === NS_FILE
) {
823 $this->mImage
= wfFindFile( $this->mTitle
);
829 * Check if this is result points to an invalid title
833 function isBrokenTitle() {
834 return is_null( $this->mTitle
);
838 * Check if target page is missing, happens when index is out of date
842 function isMissingRevision() {
843 return !$this->mRevision
&& !$this->mImage
;
849 function getTitle() {
850 return $this->mTitle
;
854 * Get the file for this page, if one exists
858 return $this->mImage
;
862 * @return float|null if not supported
864 function getScore() {
869 * Lazy initialization of article text from DB
871 protected function initText() {
872 if ( !isset( $this->mText
) ) {
873 if ( $this->mRevision
!= null ) {
874 $this->mText
= SearchEngine
::create()
875 ->getTextFromContent( $this->mTitle
, $this->mRevision
->getContent() );
876 } else { // TODO: can we fetch raw wikitext for commons images?
883 * @param array $terms terms to highlight
884 * @return String: highlighted text snippet, null (and not '') if not supported
886 function getTextSnippet( $terms ) {
887 global $wgAdvancedSearchHighlighting;
890 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
891 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs();
892 $h = new SearchHighlighter();
893 if ( $wgAdvancedSearchHighlighting ) {
894 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
896 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
901 * @param array $terms terms to highlight
902 * @return String: highlighted title, '' if not supported
904 function getTitleSnippet( $terms ) {
909 * @param array $terms terms to highlight
910 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
912 function getRedirectSnippet( $terms ) {
917 * @return Title object for the redirect to this page, null if none or not supported
919 function getRedirectTitle() {
924 * @return string highlighted relevant section name, null if none or not supported
926 function getSectionSnippet() {
931 * @return Title object (pagename+fragment) for the section, null if none or not supported
933 function getSectionTitle() {
938 * @return String: timestamp
940 function getTimestamp() {
941 if ( $this->mRevision
) {
942 return $this->mRevision
->getTimestamp();
943 } elseif ( $this->mImage
) {
944 return $this->mImage
->getTimestamp();
950 * @return Integer: number of words
952 function getWordCount() {
954 return str_word_count( $this->mText
);
958 * @return Integer: size in bytes
960 function getByteSize() {
962 return strlen( $this->mText
);
966 * @return Boolean if hit has related articles
968 function hasRelated() {
973 * @return String: interwiki prefix of the title (return iw even if title is broken)
975 function getInterwikiPrefix() {
980 * Did this match file contents (eg: PDF/DJVU)?
982 function isFileMatch() {
987 * A SearchResultSet wrapper for SearchEngine::getNearMatch
989 class SearchNearMatchResultSet
extends SearchResultSet
{
990 private $fetched = false;
992 * @param $match mixed Title if matched, else null
994 public function __construct( $match ) {
995 $this->result
= $match;
997 public function hasResult() {
998 return (bool)$this->result
;
1000 public function numRows() {
1001 return $this->hasResults() ?
1 : 0;
1003 public function next() {
1004 if ( $this->fetched ||
!$this->result
) {
1007 $this->fetched
= true;
1008 return SearchResult
::newFromTitle( $this->result
);
1013 * Highlight bits of wikitext
1017 class SearchHighlighter
{
1018 var $mCleanWikitext = true;
1020 function __construct( $cleanupWikitext = true ) {
1021 $this->mCleanWikitext
= $cleanupWikitext;
1025 * Default implementation of wikitext highlighting
1027 * @param $text String
1028 * @param array $terms terms to highlight (unescaped)
1029 * @param $contextlines Integer
1030 * @param $contextchars Integer
1033 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
1035 global $wgSearchHighlightBoundaries;
1036 $fname = __METHOD__
;
1038 if ( $text == '' ) {
1042 // spli text into text + templates/links/tables
1043 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
1044 // first capture group is for detecting nested templates/links/tables/references
1045 $endPatterns = array(
1046 1 => '/(\{\{)|(\}\})/', // template
1047 2 => '/(\[\[)|(\]\])/', // image
1048 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
1050 // @todo FIXME: This should prolly be a hook or something
1051 if ( function_exists( 'wfCite' ) ) {
1052 $spat .= '|(<ref>)'; // references via cite extension
1053 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
1056 $textExt = array(); // text extracts
1057 $otherExt = array(); // other extracts
1058 wfProfileIn( "$fname-split" );
1060 $textLen = strlen( $text );
1061 $count = 0; // sequence number to maintain ordering
1062 while ( $start < $textLen ) {
1063 // find start of template/image/table
1064 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
1066 foreach ( $matches as $key => $val ) {
1067 if ( $key > 0 && $val[1] != - 1 ) {
1069 // see if this is an image link
1070 $ns = substr( $val[0], 2, - 1 );
1071 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
) {
1076 $epat = $endPatterns[$key];
1077 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1083 // find end (and detect any nested elements)
1085 $offset = $start +
1;
1087 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
1088 if ( array_key_exists( 2, $endMatches ) ) {
1090 if ( $level == 0 ) {
1091 $len = strlen( $endMatches[2][0] );
1092 $off = $endMatches[2][1];
1093 $this->splitAndAdd( $otherExt, $count,
1094 substr( $text, $start, $off +
$len - $start ) );
1095 $start = $off +
$len;
1099 // end of nested element
1106 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
1109 // couldn't find appropriate closing tag, skip
1110 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1111 $start +
= strlen( $matches[0][0] );
1116 // else: add as text extract
1117 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1121 $all = $textExt +
$otherExt; // these have disjunct key sets
1123 wfProfileOut( "$fname-split" );
1126 foreach ( $terms as $index => $term ) {
1127 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1128 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1129 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1131 $terms[$index] = $term;
1134 $anyterm = implode( '|', $terms );
1135 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1137 // @todo FIXME: A hack to scale contextchars, a correct solution
1138 // would be to have contextchars actually be char and not byte
1139 // length, and do proper utf-8 substrings and lengths everywhere,
1140 // but PHP is making that very hard and unclean to implement :(
1141 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1142 $contextchars = intval( $contextchars * $scale );
1144 $patPre = "(^|$wgSearchHighlightBoundaries)";
1145 $patPost = "($wgSearchHighlightBoundaries|$)";
1147 $pat1 = "/(" . $phrase . ")/ui";
1148 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1150 wfProfileIn( "$fname-extract" );
1152 $left = $contextlines;
1154 $snippets = array();
1157 // show beginning only if it contains all words
1160 foreach ( $textExt as $index => $line ) {
1161 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1162 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1169 // check if first text contains all terms
1170 foreach ( $terms as $term ) {
1171 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1177 $snippets[$first] = $firstText;
1178 $offsets[$first] = 0;
1181 if ( ! $snippets ) {
1182 // match whole query on text
1183 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1184 // match whole query on templates/tables/images
1185 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1186 // match any words on text
1187 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1188 // match any words on templates/tables/images
1189 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1194 // add extra chars to each snippet to make snippets constant size
1195 $extended = array();
1196 if ( count( $snippets ) == 0 ) {
1197 // couldn't find the target words, just show beginning of article
1198 if ( array_key_exists( $first, $all ) ) {
1199 $targetchars = $contextchars * $contextlines;
1200 $snippets[$first] = '';
1201 $offsets[$first] = 0;
1204 // if begin of the article contains the whole phrase, show only that !!
1205 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1206 && $offsets[$first] < $contextchars * 2 ) {
1207 $snippets = array( $first => $snippets[$first] );
1210 // calc by how much to extend existing snippets
1211 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1214 foreach ( $snippets as $index => $line ) {
1215 $extended[$index] = $line;
1216 $len = strlen( $line );
1217 if ( $len < $targetchars - 20 ) {
1218 // complete this line
1219 if ( $len < strlen( $all[$index] ) ) {
1220 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1221 $len = strlen( $extended[$index] );
1226 while ( $len < $targetchars - 20
1227 && array_key_exists( $add, $all )
1228 && !array_key_exists( $add, $snippets ) ) {
1230 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1231 $extended[$add] = $tt;
1232 $len +
= strlen( $tt );
1238 // $snippets = array_map( 'htmlspecialchars', $extended );
1239 $snippets = $extended;
1242 foreach ( $snippets as $index => $line ) {
1243 if ( $last == - 1 ) {
1244 $extract .= $line; // first line
1245 } elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) ) {
1246 $extract .= " " . $line; // continous lines
1248 $extract .= '<b> ... </b>' . $line;
1254 $extract .= '<b> ... </b>';
1257 $processed = array();
1258 foreach ( $terms as $term ) {
1259 if ( ! isset( $processed[$term] ) ) {
1260 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1261 $extract = preg_replace( $pat3,
1262 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1263 $processed[$term] = true;
1267 wfProfileOut( "$fname-extract" );
1273 * Split text into lines and add it to extracts array
1275 * @param array $extracts index -> $line
1276 * @param $count Integer
1277 * @param $text String
1279 function splitAndAdd( &$extracts, &$count, $text ) {
1280 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1281 foreach ( $split as $line ) {
1282 $tt = trim( $line );
1284 $extracts[$count++
] = $tt;
1290 * Do manual case conversion for non-ascii chars
1292 * @param $matches Array
1295 function caseCallback( $matches ) {
1297 if ( strlen( $matches[0] ) > 1 ) {
1298 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1305 * Extract part of the text from start to end, but by
1306 * not chopping up words
1307 * @param $text String
1308 * @param $start Integer
1309 * @param $end Integer
1310 * @param $posStart Integer: (out) actual start position
1311 * @param $posEnd Integer: (out) actual end position
1314 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1315 if ( $start != 0 ) {
1316 $start = $this->position( $text, $start, 1 );
1318 if ( $end >= strlen( $text ) ) {
1319 $end = strlen( $text );
1321 $end = $this->position( $text, $end );
1324 if ( !is_null( $posStart ) ) {
1327 if ( !is_null( $posEnd ) ) {
1331 if ( $end > $start ) {
1332 return substr( $text, $start, $end - $start );
1339 * Find a nonletter near a point (index) in the text
1341 * @param $text String
1342 * @param $point Integer
1343 * @param $offset Integer: offset to found index
1344 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1346 function position( $text, $point, $offset = 0 ) {
1348 $s = max( 0, $point - $tolerance );
1349 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1351 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1352 return $m[0][1] +
$s +
$offset;
1354 // check if point is on a valid first UTF8 char
1355 $char = ord( $text[$point] );
1356 while ( $char >= 0x80 && $char < 0xc0 ) {
1357 // skip trailing bytes
1359 if ( $point >= strlen( $text ) ) {
1360 return strlen( $text );
1362 $char = ord( $text[$point] );
1370 * Search extracts for a pattern, and return snippets
1372 * @param string $pattern regexp for matching lines
1373 * @param array $extracts extracts to search
1374 * @param $linesleft Integer: number of extracts to make
1375 * @param $contextchars Integer: length of snippet
1376 * @param array $out map for highlighted snippets
1377 * @param array $offsets map of starting points of snippets
1380 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1381 if ( $linesleft == 0 ) {
1382 return; // nothing to do
1384 foreach ( $extracts as $index => $line ) {
1385 if ( array_key_exists( $index, $out ) ) {
1386 continue; // this line already highlighted
1390 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) ) {
1395 $len = strlen( $m[0][0] );
1396 if ( $offset +
$len < $contextchars ) {
1398 } elseif ( $len > $contextchars ) {
1401 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1404 $end = $begin +
$contextchars;
1407 // basic snippet from this line
1408 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1409 $offsets[$index] = $posBegin;
1411 if ( $linesleft == 0 ) {
1418 * Basic wikitext removal
1422 function removeWiki( $text ) {
1423 $fname = __METHOD__
;
1424 wfProfileIn( $fname );
1426 // $text = preg_replace( "/'{2,5}/", "", $text );
1427 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1428 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1429 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1430 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1431 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1432 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1433 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1434 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1435 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1436 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1437 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1438 $text = preg_replace( "/'''''/", "", $text );
1439 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1440 $text = preg_replace( "/''/", "", $text );
1442 wfProfileOut( $fname );
1447 * callback to replace [[target|caption]] kind of links, if
1448 * the target is category or image, leave it
1450 * @param $matches Array
1452 function linkReplace( $matches ) {
1453 $colon = strpos( $matches[1], ':' );
1454 if ( $colon === false ) {
1455 return $matches[2]; // replace with caption
1458 $ns = substr( $matches[1], 0, $colon );
1459 $index = $wgContLang->getNsIndex( $ns );
1460 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) ) {
1461 return $matches[0]; // return the whole thing
1468 * Simple & fast snippet extraction, but gives completely unrelevant
1471 * @param $text String
1472 * @param $terms Array
1473 * @param $contextlines Integer
1474 * @param $contextchars Integer
1477 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1479 $fname = __METHOD__
;
1481 $lines = explode( "\n", $text );
1483 $terms = implode( '|', $terms );
1484 $max = intval( $contextchars ) +
1;
1485 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1490 wfProfileIn( "$fname-extract" );
1491 foreach ( $lines as $line ) {
1492 if ( 0 == $contextlines ) {
1497 if ( ! preg_match( $pat1, $line, $m ) ) {
1501 // truncate function changes ... to relevant i18n message.
1502 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1504 if ( count( $m ) < 3 ) {
1507 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1512 $line = htmlspecialchars( $pre . $found . $post );
1513 $pat2 = '/(' . $terms . ")/i";
1514 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1516 $extract .= "${line}\n";
1518 wfProfileOut( "$fname-extract" );
1526 * Dummy class to be used when non-supported Database engine is present.
1527 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1528 * such as a LIKE search through titles.
1531 class SearchEngineDummy
extends SearchEngine
{