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 ) {
70 * @param $feature String
73 public function supports( $feature ) {
75 case 'list-redirects':
78 case 'title-suffix-filter':
85 * Way to pass custom data for engines
87 * @param $feature String
91 public function setFeatureData( $feature, $data ) {
92 $this->features
[$feature] = $data;
96 * When overridden in derived class, performs database-specific conversions
97 * on text to be used for searching or updating search index.
98 * Default implementation does nothing (simply returns $string).
100 * @param string $string String to process
103 public function normalizeText( $string ) {
106 // Some languages such as Chinese require word segmentation
107 return $wgContLang->segmentByWord( $string );
111 * Transform search term in cases when parts of the query came as different GET params (when supported)
112 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
114 function transformSearchTerm( $term ) {
119 * If an exact title match can be found, or a very slightly close match,
120 * return the title. If no match, returns NULL.
122 * @param $searchterm String
125 public static function getNearMatch( $searchterm ) {
126 $title = self
::getNearMatchInternal( $searchterm );
128 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
133 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
136 * @param $searchterm string
137 * @return SearchResultSet
139 public static function getNearMatchResultSet( $searchterm ) {
140 return new SearchNearMatchResultSet( self
::getNearMatch( $searchterm ) );
144 * Really find the title match.
147 private static function getNearMatchInternal( $searchterm ) {
148 global $wgContLang, $wgEnableSearchContributorsByIP;
150 $allSearchTerms = array( $searchterm );
152 if ( $wgContLang->hasVariants() ) {
153 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
157 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
161 foreach ( $allSearchTerms as $term ) {
163 # Exact match? No need to look further.
164 $title = Title
::newFromText( $term );
165 if ( is_null( $title ) ) {
169 # Try files if searching in the Media: namespace
170 if ( $title->getNamespace() == NS_MEDIA
) {
171 $title = Title
::makeTitle( NS_FILE
, $title->getText() );
174 if ( $title->isSpecialPage() ||
$title->isExternal() ||
$title->exists() ) {
178 # See if it still otherwise has content is some sane sense
179 $page = WikiPage
::factory( $title );
180 if ( $page->hasViewableContent() ) {
184 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
188 # Now try all lower case (i.e. first letter capitalized)
189 $title = Title
::newFromText( $wgContLang->lc( $term ) );
190 if ( $title && $title->exists() ) {
194 # Now try capitalized string
195 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
196 if ( $title && $title->exists() ) {
200 # Now try all upper case
201 $title = Title
::newFromText( $wgContLang->uc( $term ) );
202 if ( $title && $title->exists() ) {
206 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
207 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
208 if ( $title && $title->exists() ) {
212 // Give hooks a chance at better match variants
214 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
219 $title = Title
::newFromText( $searchterm );
221 # Entering an IP address goes to the contributions page
222 if ( $wgEnableSearchContributorsByIP ) {
223 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
224 || User
::isIP( trim( $searchterm ) ) ) {
225 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
229 # Entering a user goes to the user page whether it's there or not
230 if ( $title->getNamespace() == NS_USER
) {
234 # Go to images that exist even if there's no local page.
235 # There may have been a funny upload, or it may be on a shared
236 # file repository such as Wikimedia Commons.
237 if ( $title->getNamespace() == NS_FILE
) {
238 $image = wfFindFile( $title );
244 # MediaWiki namespace? Page may be "implied" if not customized.
245 # Just return it, with caps forced as the message system likes it.
246 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
247 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
250 # Quoted term? Try without the quotes...
252 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
253 return SearchEngine
::getNearMatch( $matches[1] );
259 public static function legalSearchChars() {
260 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
264 * Set the maximum number of results to return
265 * and how many to skip before returning the first.
267 * @param $limit Integer
268 * @param $offset Integer
270 function setLimitOffset( $limit, $offset = 0 ) {
271 $this->limit
= intval( $limit );
272 $this->offset
= intval( $offset );
276 * Set which namespaces the search should include.
277 * Give an array of namespace index numbers.
279 * @param $namespaces Array
281 function setNamespaces( $namespaces ) {
282 $this->namespaces
= $namespaces;
286 * Set whether the searcher should try to build a suggestion. Note: some searchers
287 * don't support building a suggestion in the first place and others don't respect
290 * @param boolean $showSuggestion should the searcher try to build suggestions
292 function setShowSuggestion( $showSuggestion ) {
293 $this->showSuggestion
= $showSuggestion;
297 * Parse some common prefixes: all (search everything)
300 * @param $query String
303 function replacePrefixes( $query ) {
307 if ( strpos( $query, ':' ) === false ) { // nothing to do
308 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
312 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
313 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
314 $this->namespaces
= null;
315 $parsed = substr( $query, strlen( $allkeyword ) );
316 } elseif ( strpos( $query, ':' ) !== false ) {
317 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
318 $index = $wgContLang->getNsIndex( $prefix );
319 if ( $index !== false ) {
320 $this->namespaces
= array( $index );
321 $parsed = substr( $query, strlen( $prefix ) +
1 );
324 if ( trim( $parsed ) == '' ) {
325 $parsed = $query; // prefix was the whole query
328 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
334 * Make a list of searchable namespaces and their canonical names.
337 public static function searchableNamespaces() {
340 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
341 if ( $ns >= NS_MAIN
) {
346 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
351 * Extract default namespaces to search from the given user's
352 * settings, returning a list of index numbers.
357 public static function userNamespaces( $user ) {
358 global $wgSearchEverythingOnlyLoggedIn;
360 $searchableNamespaces = SearchEngine
::searchableNamespaces();
362 // get search everything preference, that can be set to be read for logged-in users
363 // it overrides other options
364 if ( !$wgSearchEverythingOnlyLoggedIn ||
$user->isLoggedIn() ) {
365 if ( $user->getOption( 'searcheverything' ) ) {
366 return array_keys( $searchableNamespaces );
371 foreach ( $searchableNamespaces as $ns => $name ) {
372 if ( $user->getOption( 'searchNs' . $ns ) ) {
381 * Find snippet highlight settings for all users
383 * @return Array contextlines, contextchars
385 public static function userHighlightPrefs() {
386 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
387 $contextchars = 75; // same as above.... :P
388 return array( $contextlines, $contextchars );
392 * An array of namespaces indexes to be searched by default
396 public static function defaultNamespaces() {
397 global $wgNamespacesToBeSearchedDefault;
399 return array_keys( $wgNamespacesToBeSearchedDefault, true );
403 * Get a list of namespace names useful for showing in tooltips
406 * @param $namespaces Array
409 public static function namespacesAsText( $namespaces ) {
412 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
413 foreach ( $formatted as $key => $ns ) {
414 if ( empty( $ns ) ) {
415 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
422 * Return the help namespaces to be shown on Special:Search
426 public static function helpNamespaces() {
427 global $wgNamespacesToBeSearchedHelp;
429 return array_keys( $wgNamespacesToBeSearchedHelp, true );
433 * Return a 'cleaned up' search string
435 * @param $text String
438 function filter( $text ) {
439 $lc = $this->legalSearchChars();
440 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
443 * Load up the appropriate search engine class for the currently
444 * active database backend, and return a configured instance.
446 * @param String $type Type of search backend, if not the default
447 * @return SearchEngine
449 public static function create( $type = null ) {
450 global $wgSearchType;
453 $alternatives = self
::getSearchTypes();
455 if ( $type && in_array( $type, $alternatives ) ) {
457 } elseif ( $wgSearchType !== null ) {
458 $class = $wgSearchType;
460 $dbr = wfGetDB( DB_SLAVE
);
461 $class = $dbr->getSearchEngine();
464 $search = new $class( $dbr );
469 * Return the search engines we support. If only $wgSearchType
470 * is set, it'll be an array of just that one item.
474 public static function getSearchTypes() {
475 global $wgSearchType, $wgSearchTypeAlternatives;
477 $alternatives = $wgSearchTypeAlternatives ?
: array();
478 array_unshift( $alternatives, $wgSearchType );
480 return $alternatives;
484 * Create or update the search index record for the given page.
485 * Title and text should be pre-processed.
489 * @param $title String
490 * @param $text String
492 function update( $id, $title, $text ) {
497 * Update a search index record's title only.
498 * Title should be pre-processed.
502 * @param $title String
504 function updateTitle( $id, $title ) {
509 * Delete an indexed page
510 * Title should be pre-processed.
513 * @param Integer $id Page id that was deleted
514 * @param String $title Title of page that was deleted
516 function delete( $id, $title ) {
521 * Get OpenSearch suggestion template
525 public static function getOpenSearchTemplate() {
526 global $wgOpenSearchTemplate, $wgCanonicalServer;
527 if ( $wgOpenSearchTemplate ) {
528 return $wgOpenSearchTemplate;
530 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
534 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
539 * Get the raw text for updating the index from a content object
540 * Nicer search backends could possibly do something cooler than
541 * just returning raw text
543 * @todo This isn't ideal, we'd really like to have content-specific handling here
544 * @param Title $t Title we're indexing
545 * @param Content $c Content of the page to index
548 public function getTextFromContent( Title
$t, Content
$c = null ) {
549 return $c ?
$c->getTextForSearchIndex() : '';
553 * If an implementation of SearchEngine handles all of its own text processing
554 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
555 * rather silly handling, it should return true here instead.
559 public function textAlreadyUpdatedForIndex() {
567 class SearchResultSet
{
569 * Fetch an array of regular expression fragments for matching
570 * the search terms as parsed by this engine in a text extract.
575 function termMatches() {
584 * Return true if results are included in this result set.
589 function hasResults() {
594 * Some search modes return a total hit count for the query
595 * in the entire article database. This may include pages
596 * in namespaces that would not be matched on the given
599 * Return null if no total hits number is supported.
603 function getTotalHits() {
608 * Some search modes return a suggested alternate term if there are
609 * no exact hits. Returns true if there is one on this set.
613 function hasSuggestion() {
618 * @return String: suggested query, null if none
620 function getSuggestionQuery() {
625 * @return String: HTML highlighted suggested query, '' if none
627 function getSuggestionSnippet() {
632 * Return information about how and from where the results were fetched,
633 * should be useful for diagnostics and debugging
642 * Return a result set of hits on other (multiple) wikis associated with this one
644 * @return SearchResultSet
646 function getInterwikiResults() {
651 * Check if there are results on other wikis
655 function hasInterwikiResults() {
656 return $this->getInterwikiResults() != null;
660 * Fetches next search result, or false.
663 * @return SearchResult
670 * Frees the result set, if applicable.
677 * Did the search contain search syntax? If so, Special:Search won't offer
678 * the user a link to a create a page named by the search string because the
679 * name would contain the search syntax.
681 public function searchContainedSyntax() {
687 * This class is used for different SQL-based search engines shipped with MediaWiki
689 class SqlSearchResultSet
extends SearchResultSet
{
691 protected $mResultSet;
693 function __construct( $resultSet, $terms ) {
694 $this->mResultSet
= $resultSet;
695 $this->mTerms
= $terms;
698 function termMatches() {
699 return $this->mTerms
;
703 if ( $this->mResultSet
=== false ) {
707 return $this->mResultSet
->numRows();
711 if ( $this->mResultSet
=== false ) {
715 $row = $this->mResultSet
->fetchObject();
716 if ( $row === false ) {
720 return SearchResult
::newFromRow( $row );
724 if ( $this->mResultSet
=== false ) {
728 $this->mResultSet
->free();
735 class SearchResultTooMany
{
736 # # Some search engines may bail out if too many matches are found
740 * @todo FIXME: This class is horribly factored. It would probably be better to
741 * have a useful base class to which you pass some standard information, then
742 * let the fancy self-highlighters extend that.
750 protected $mRevision = null;
755 protected $mImage = null;
768 * Return a new SearchResult and initializes it with a title.
770 * @param $title Title
771 * @return SearchResult
773 public static function newFromTitle( $title ) {
774 $result = new self();
775 $result->initFromTitle( $title );
779 * Return a new SearchResult and initializes it with a row.
782 * @return SearchResult
784 public static function newFromRow( $row ) {
785 $result = new self();
786 $result->initFromRow( $row );
790 public function __construct( $row = null ) {
791 if ( !is_null( $row ) ) {
792 // Backwards compatibility with pre-1.17 callers
793 $this->initFromRow( $row );
798 * Initialize from a database row. Makes a Title and passes that to
803 protected function initFromRow( $row ) {
804 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
808 * Initialize from a Title and if possible initializes a corresponding
811 * @param $title Title
813 protected function initFromTitle( $title ) {
814 $this->mTitle
= $title;
815 if ( !is_null( $this->mTitle
) ) {
817 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
818 $this->mRevision
= Revision
::newFromTitle(
819 $this->mTitle
, $id, Revision
::READ_NORMAL
);
820 if ( $this->mTitle
->getNamespace() === NS_FILE
) {
821 $this->mImage
= wfFindFile( $this->mTitle
);
827 * Check if this is result points to an invalid title
831 function isBrokenTitle() {
832 return is_null( $this->mTitle
);
836 * Check if target page is missing, happens when index is out of date
840 function isMissingRevision() {
841 return !$this->mRevision
&& !$this->mImage
;
847 function getTitle() {
848 return $this->mTitle
;
852 * Get the file for this page, if one exists
856 return $this->mImage
;
860 * @return float|null if not supported
862 function getScore() {
867 * Lazy initialization of article text from DB
869 protected function initText() {
870 if ( !isset( $this->mText
) ) {
871 if ( $this->mRevision
!= null ) {
872 $this->mText
= SearchEngine
::create()
873 ->getTextFromContent( $this->mTitle
, $this->mRevision
->getContent() );
874 } else { // TODO: can we fetch raw wikitext for commons images?
881 * @param array $terms terms to highlight
882 * @return String: highlighted text snippet, null (and not '') if not supported
884 function getTextSnippet( $terms ) {
885 global $wgAdvancedSearchHighlighting;
888 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
889 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs();
890 $h = new SearchHighlighter();
891 if ( $wgAdvancedSearchHighlighting ) {
892 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
894 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
899 * @param array $terms terms to highlight
900 * @return String: highlighted title, '' if not supported
902 function getTitleSnippet( $terms ) {
907 * @param array $terms terms to highlight
908 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
910 function getRedirectSnippet( $terms ) {
915 * @return Title object for the redirect to this page, null if none or not supported
917 function getRedirectTitle() {
922 * @return string highlighted relevant section name, null if none or not supported
924 function getSectionSnippet() {
929 * @return Title object (pagename+fragment) for the section, null if none or not supported
931 function getSectionTitle() {
936 * @return String: timestamp
938 function getTimestamp() {
939 if ( $this->mRevision
) {
940 return $this->mRevision
->getTimestamp();
941 } elseif ( $this->mImage
) {
942 return $this->mImage
->getTimestamp();
948 * @return Integer: number of words
950 function getWordCount() {
952 return str_word_count( $this->mText
);
956 * @return Integer: size in bytes
958 function getByteSize() {
960 return strlen( $this->mText
);
964 * @return Boolean if hit has related articles
966 function hasRelated() {
971 * @return String: interwiki prefix of the title (return iw even if title is broken)
973 function getInterwikiPrefix() {
978 * Did this match file contents (eg: PDF/DJVU)?
980 function isFileMatch() {
985 * A SearchResultSet wrapper for SearchEngine::getNearMatch
987 class SearchNearMatchResultSet
extends SearchResultSet
{
988 private $fetched = false;
990 * @param $match mixed Title if matched, else null
992 public function __construct( $match ) {
993 $this->result
= $match;
995 public function hasResult() {
996 return (bool)$this->result
;
998 public function numRows() {
999 return $this->hasResults() ?
1 : 0;
1001 public function next() {
1002 if ( $this->fetched ||
!$this->result
) {
1005 $this->fetched
= true;
1006 return SearchResult
::newFromTitle( $this->result
);
1011 * Highlight bits of wikitext
1015 class SearchHighlighter
{
1016 var $mCleanWikitext = true;
1018 function __construct( $cleanupWikitext = true ) {
1019 $this->mCleanWikitext
= $cleanupWikitext;
1023 * Default implementation of wikitext highlighting
1025 * @param $text String
1026 * @param array $terms terms to highlight (unescaped)
1027 * @param $contextlines Integer
1028 * @param $contextchars Integer
1031 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
1033 global $wgSearchHighlightBoundaries;
1034 $fname = __METHOD__
;
1036 if ( $text == '' ) {
1040 // spli text into text + templates/links/tables
1041 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
1042 // first capture group is for detecting nested templates/links/tables/references
1043 $endPatterns = array(
1044 1 => '/(\{\{)|(\}\})/', // template
1045 2 => '/(\[\[)|(\]\])/', // image
1046 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
1048 // @todo FIXME: This should prolly be a hook or something
1049 if ( function_exists( 'wfCite' ) ) {
1050 $spat .= '|(<ref>)'; // references via cite extension
1051 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
1054 $textExt = array(); // text extracts
1055 $otherExt = array(); // other extracts
1056 wfProfileIn( "$fname-split" );
1058 $textLen = strlen( $text );
1059 $count = 0; // sequence number to maintain ordering
1060 while ( $start < $textLen ) {
1061 // find start of template/image/table
1062 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
1064 foreach ( $matches as $key => $val ) {
1065 if ( $key > 0 && $val[1] != - 1 ) {
1067 // see if this is an image link
1068 $ns = substr( $val[0], 2, - 1 );
1069 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
) {
1074 $epat = $endPatterns[$key];
1075 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1081 // find end (and detect any nested elements)
1083 $offset = $start +
1;
1085 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
1086 if ( array_key_exists( 2, $endMatches ) ) {
1088 if ( $level == 0 ) {
1089 $len = strlen( $endMatches[2][0] );
1090 $off = $endMatches[2][1];
1091 $this->splitAndAdd( $otherExt, $count,
1092 substr( $text, $start, $off +
$len - $start ) );
1093 $start = $off +
$len;
1097 // end of nested element
1104 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
1107 // couldn't find appropriate closing tag, skip
1108 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1109 $start +
= strlen( $matches[0][0] );
1114 // else: add as text extract
1115 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1119 $all = $textExt +
$otherExt; // these have disjunct key sets
1121 wfProfileOut( "$fname-split" );
1124 foreach ( $terms as $index => $term ) {
1125 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1126 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1127 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1129 $terms[$index] = $term;
1132 $anyterm = implode( '|', $terms );
1133 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1135 // @todo FIXME: A hack to scale contextchars, a correct solution
1136 // would be to have contextchars actually be char and not byte
1137 // length, and do proper utf-8 substrings and lengths everywhere,
1138 // but PHP is making that very hard and unclean to implement :(
1139 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1140 $contextchars = intval( $contextchars * $scale );
1142 $patPre = "(^|$wgSearchHighlightBoundaries)";
1143 $patPost = "($wgSearchHighlightBoundaries|$)";
1145 $pat1 = "/(" . $phrase . ")/ui";
1146 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1148 wfProfileIn( "$fname-extract" );
1150 $left = $contextlines;
1152 $snippets = array();
1155 // show beginning only if it contains all words
1158 foreach ( $textExt as $index => $line ) {
1159 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1160 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1167 // check if first text contains all terms
1168 foreach ( $terms as $term ) {
1169 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1175 $snippets[$first] = $firstText;
1176 $offsets[$first] = 0;
1179 if ( ! $snippets ) {
1180 // match whole query on text
1181 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1182 // match whole query on templates/tables/images
1183 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1184 // match any words on text
1185 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1186 // match any words on templates/tables/images
1187 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1192 // add extra chars to each snippet to make snippets constant size
1193 $extended = array();
1194 if ( count( $snippets ) == 0 ) {
1195 // couldn't find the target words, just show beginning of article
1196 if ( array_key_exists( $first, $all ) ) {
1197 $targetchars = $contextchars * $contextlines;
1198 $snippets[$first] = '';
1199 $offsets[$first] = 0;
1202 // if begin of the article contains the whole phrase, show only that !!
1203 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1204 && $offsets[$first] < $contextchars * 2 ) {
1205 $snippets = array( $first => $snippets[$first] );
1208 // calc by how much to extend existing snippets
1209 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1212 foreach ( $snippets as $index => $line ) {
1213 $extended[$index] = $line;
1214 $len = strlen( $line );
1215 if ( $len < $targetchars - 20 ) {
1216 // complete this line
1217 if ( $len < strlen( $all[$index] ) ) {
1218 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1219 $len = strlen( $extended[$index] );
1224 while ( $len < $targetchars - 20
1225 && array_key_exists( $add, $all )
1226 && !array_key_exists( $add, $snippets ) ) {
1228 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1229 $extended[$add] = $tt;
1230 $len +
= strlen( $tt );
1236 // $snippets = array_map( 'htmlspecialchars', $extended );
1237 $snippets = $extended;
1240 foreach ( $snippets as $index => $line ) {
1241 if ( $last == - 1 ) {
1242 $extract .= $line; // first line
1243 } elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) ) {
1244 $extract .= " " . $line; // continous lines
1246 $extract .= '<b> ... </b>' . $line;
1252 $extract .= '<b> ... </b>';
1255 $processed = array();
1256 foreach ( $terms as $term ) {
1257 if ( ! isset( $processed[$term] ) ) {
1258 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1259 $extract = preg_replace( $pat3,
1260 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1261 $processed[$term] = true;
1265 wfProfileOut( "$fname-extract" );
1271 * Split text into lines and add it to extracts array
1273 * @param array $extracts index -> $line
1274 * @param $count Integer
1275 * @param $text String
1277 function splitAndAdd( &$extracts, &$count, $text ) {
1278 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1279 foreach ( $split as $line ) {
1280 $tt = trim( $line );
1282 $extracts[$count++
] = $tt;
1288 * Do manual case conversion for non-ascii chars
1290 * @param $matches Array
1293 function caseCallback( $matches ) {
1295 if ( strlen( $matches[0] ) > 1 ) {
1296 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1303 * Extract part of the text from start to end, but by
1304 * not chopping up words
1305 * @param $text String
1306 * @param $start Integer
1307 * @param $end Integer
1308 * @param $posStart Integer: (out) actual start position
1309 * @param $posEnd Integer: (out) actual end position
1312 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1313 if ( $start != 0 ) {
1314 $start = $this->position( $text, $start, 1 );
1316 if ( $end >= strlen( $text ) ) {
1317 $end = strlen( $text );
1319 $end = $this->position( $text, $end );
1322 if ( !is_null( $posStart ) ) {
1325 if ( !is_null( $posEnd ) ) {
1329 if ( $end > $start ) {
1330 return substr( $text, $start, $end - $start );
1337 * Find a nonletter near a point (index) in the text
1339 * @param $text String
1340 * @param $point Integer
1341 * @param $offset Integer: offset to found index
1342 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1344 function position( $text, $point, $offset = 0 ) {
1346 $s = max( 0, $point - $tolerance );
1347 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1349 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1350 return $m[0][1] +
$s +
$offset;
1352 // check if point is on a valid first UTF8 char
1353 $char = ord( $text[$point] );
1354 while ( $char >= 0x80 && $char < 0xc0 ) {
1355 // skip trailing bytes
1357 if ( $point >= strlen( $text ) ) {
1358 return strlen( $text );
1360 $char = ord( $text[$point] );
1368 * Search extracts for a pattern, and return snippets
1370 * @param string $pattern regexp for matching lines
1371 * @param array $extracts extracts to search
1372 * @param $linesleft Integer: number of extracts to make
1373 * @param $contextchars Integer: length of snippet
1374 * @param array $out map for highlighted snippets
1375 * @param array $offsets map of starting points of snippets
1378 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1379 if ( $linesleft == 0 ) {
1380 return; // nothing to do
1382 foreach ( $extracts as $index => $line ) {
1383 if ( array_key_exists( $index, $out ) ) {
1384 continue; // this line already highlighted
1388 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) ) {
1393 $len = strlen( $m[0][0] );
1394 if ( $offset +
$len < $contextchars ) {
1396 } elseif ( $len > $contextchars ) {
1399 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1402 $end = $begin +
$contextchars;
1405 // basic snippet from this line
1406 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1407 $offsets[$index] = $posBegin;
1409 if ( $linesleft == 0 ) {
1416 * Basic wikitext removal
1420 function removeWiki( $text ) {
1421 $fname = __METHOD__
;
1422 wfProfileIn( $fname );
1424 // $text = preg_replace( "/'{2,5}/", "", $text );
1425 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1426 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1427 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1428 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1429 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1430 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1431 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1432 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1433 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1434 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1435 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1436 $text = preg_replace( "/'''''/", "", $text );
1437 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1438 $text = preg_replace( "/''/", "", $text );
1440 wfProfileOut( $fname );
1445 * callback to replace [[target|caption]] kind of links, if
1446 * the target is category or image, leave it
1448 * @param $matches Array
1450 function linkReplace( $matches ) {
1451 $colon = strpos( $matches[1], ':' );
1452 if ( $colon === false ) {
1453 return $matches[2]; // replace with caption
1456 $ns = substr( $matches[1], 0, $colon );
1457 $index = $wgContLang->getNsIndex( $ns );
1458 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) ) {
1459 return $matches[0]; // return the whole thing
1466 * Simple & fast snippet extraction, but gives completely unrelevant
1469 * @param $text String
1470 * @param $terms Array
1471 * @param $contextlines Integer
1472 * @param $contextchars Integer
1475 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1477 $fname = __METHOD__
;
1479 $lines = explode( "\n", $text );
1481 $terms = implode( '|', $terms );
1482 $max = intval( $contextchars ) +
1;
1483 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1488 wfProfileIn( "$fname-extract" );
1489 foreach ( $lines as $line ) {
1490 if ( 0 == $contextlines ) {
1495 if ( ! preg_match( $pat1, $line, $m ) ) {
1499 // truncate function changes ... to relevant i18n message.
1500 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1502 if ( count( $m ) < 3 ) {
1505 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1510 $line = htmlspecialchars( $pre . $found . $post );
1511 $pat2 = '/(' . $terms . ")/i";
1512 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1514 $extract .= "${line}\n";
1516 wfProfileOut( "$fname-extract" );
1524 * Dummy class to be used when non-supported Database engine is present.
1525 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1526 * such as a LIKE search through titles.
1529 class SearchEngineDummy
extends SearchEngine
{