5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Search Search
29 * Contain a class for special pages
36 var $searchTerms = array();
37 var $namespaces = array( NS_MAIN
);
38 var $showRedirects = false;
41 protected $features = array();
48 function __construct( $db = null ) {
52 $this->db
= wfGetDB( DB_SLAVE
);
57 * Perform a full text search query and return a result set.
58 * If title searches are not supported or disabled, return null.
61 * @param string $term raw search term
62 * @return SearchResultSet|Status|null
64 function searchText( $term ) {
69 * Perform a title-only search query and return a result set.
70 * If title searches are not supported or disabled, return null.
73 * @param string $term raw search term
74 * @return SearchResultSet|null
76 function searchTitle( $term ) {
81 * If this search backend can list/unlist redirects
82 * @deprecated since 1.18 Call supports( 'list-redirects' );
85 function acceptListRedirects() {
86 wfDeprecated( __METHOD__
, '1.18' );
87 return $this->supports( 'list-redirects' );
92 * @param $feature String
95 public function supports( $feature ) {
97 case 'list-redirects':
99 case 'title-suffix-filter':
106 * Way to pass custom data for engines
108 * @param $feature String
112 public function setFeatureData( $feature, $data ) {
113 $this->features
[$feature] = $data;
117 * When overridden in derived class, performs database-specific conversions
118 * on text to be used for searching or updating search index.
119 * Default implementation does nothing (simply returns $string).
121 * @param string $string String to process
124 public function normalizeText( $string ) {
127 // Some languages such as Chinese require word segmentation
128 return $wgContLang->segmentByWord( $string );
132 * Transform search term in cases when parts of the query came as different GET params (when supported)
133 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
135 function transformSearchTerm( $term ) {
140 * If an exact title match can be found, or a very slightly close match,
141 * return the title. If no match, returns NULL.
143 * @param $searchterm String
146 public static function getNearMatch( $searchterm ) {
147 $title = self
::getNearMatchInternal( $searchterm );
149 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
154 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
157 * @param $searchterm string
158 * @return SearchResultSet
160 public static function getNearMatchResultSet( $searchterm ) {
161 return new SearchNearMatchResultSet( self
::getNearMatch( $searchterm ) );
165 * Really find the title match.
168 private static function getNearMatchInternal( $searchterm ) {
169 global $wgContLang, $wgEnableSearchContributorsByIP;
171 $allSearchTerms = array( $searchterm );
173 if ( $wgContLang->hasVariants() ) {
174 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
178 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
182 foreach ( $allSearchTerms as $term ) {
184 # Exact match? No need to look further.
185 $title = Title
::newFromText( $term );
186 if ( is_null( $title ) ) {
190 # Try files if searching in the Media: namespace
191 if ( $title->getNamespace() == NS_MEDIA
) {
192 $title = Title
::makeTitle( NS_FILE
, $title->getText() );
195 if ( $title->isSpecialPage() ||
$title->isExternal() ||
$title->exists() ) {
199 # See if it still otherwise has content is some sane sense
200 $page = WikiPage
::factory( $title );
201 if ( $page->hasViewableContent() ) {
205 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
209 # Now try all lower case (i.e. first letter capitalized)
210 $title = Title
::newFromText( $wgContLang->lc( $term ) );
211 if ( $title && $title->exists() ) {
215 # Now try capitalized string
216 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
217 if ( $title && $title->exists() ) {
221 # Now try all upper case
222 $title = Title
::newFromText( $wgContLang->uc( $term ) );
223 if ( $title && $title->exists() ) {
227 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
228 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
229 if ( $title && $title->exists() ) {
233 // Give hooks a chance at better match variants
235 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
240 $title = Title
::newFromText( $searchterm );
242 # Entering an IP address goes to the contributions page
243 if ( $wgEnableSearchContributorsByIP ) {
244 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
245 || User
::isIP( trim( $searchterm ) ) ) {
246 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
250 # Entering a user goes to the user page whether it's there or not
251 if ( $title->getNamespace() == NS_USER
) {
255 # Go to images that exist even if there's no local page.
256 # There may have been a funny upload, or it may be on a shared
257 # file repository such as Wikimedia Commons.
258 if ( $title->getNamespace() == NS_FILE
) {
259 $image = wfFindFile( $title );
265 # MediaWiki namespace? Page may be "implied" if not customized.
266 # Just return it, with caps forced as the message system likes it.
267 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
268 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
271 # Quoted term? Try without the quotes...
273 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
274 return SearchEngine
::getNearMatch( $matches[1] );
280 public static function legalSearchChars() {
281 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
285 * Set the maximum number of results to return
286 * and how many to skip before returning the first.
288 * @param $limit Integer
289 * @param $offset Integer
291 function setLimitOffset( $limit, $offset = 0 ) {
292 $this->limit
= intval( $limit );
293 $this->offset
= intval( $offset );
297 * Set which namespaces the search should include.
298 * Give an array of namespace index numbers.
300 * @param $namespaces Array
302 function setNamespaces( $namespaces ) {
303 $this->namespaces
= $namespaces;
307 * Parse some common prefixes: all (search everything)
310 * @param $query String
313 function replacePrefixes( $query ) {
317 if ( strpos( $query, ':' ) === false ) { // nothing to do
318 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
322 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
323 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
324 $this->namespaces
= null;
325 $parsed = substr( $query, strlen( $allkeyword ) );
326 } elseif ( strpos( $query, ':' ) !== false ) {
327 $prefix = substr( $query, 0, strpos( $query, ':' ) );
328 $index = $wgContLang->getNsIndex( $prefix );
329 if ( $index !== false ) {
330 $this->namespaces
= array( $index );
331 $parsed = substr( $query, strlen( $prefix ) +
1 );
334 if ( trim( $parsed ) == '' ) {
335 $parsed = $query; // prefix was the whole query
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();
464 $type = $type !== null ?
$type : $wgSearchType;
465 if ( $type && in_array( $type, $alternatives ) ) {
468 $dbr = wfGetDB( DB_SLAVE
);
469 $class = $dbr->getSearchEngine();
471 $search = new $class( $dbr );
472 $search->setLimitOffset( 0, 0 );
477 * Return the search engines we support. If only $wgSearchType
478 * is set, it'll be an array of just that one item.
482 public static function getSearchTypes() {
483 global $wgSearchType, $wgSearchTypeAlternatives;
484 static $alternatives = null;
485 if ( $alternatives === null ) {
486 $alternatives = $wgSearchTypeAlternatives ?
: array();
487 array_unshift( $alternatives, $wgSearchType );
489 return $alternatives;
493 * Create or update the search index record for the given page.
494 * Title and text should be pre-processed.
498 * @param $title String
499 * @param $text String
501 function update( $id, $title, $text ) {
506 * Update a search index record's title only.
507 * Title should be pre-processed.
511 * @param $title String
513 function updateTitle( $id, $title ) {
518 * Delete an indexed page
519 * Title should be pre-processed.
522 * @param Integer $id Page id that was deleted
523 * @param String $title Title of page that was deleted
525 function delete( $id, $title ) {
530 * Get OpenSearch suggestion template
534 public static function getOpenSearchTemplate() {
535 global $wgOpenSearchTemplate, $wgCanonicalServer;
536 if ( $wgOpenSearchTemplate ) {
537 return $wgOpenSearchTemplate;
539 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
543 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
548 * Get the raw text for updating the index from a content object
549 * Nicer search backends could possibly do something cooler than
550 * just returning raw text
552 * @todo This isn't ideal, we'd really like to have content-specific handling here
553 * @param Title $t Title we're indexing
554 * @param Content $c Content of the page to index
557 public function getTextFromContent( Title
$t, Content
$c = null ) {
558 return $c ?
$c->getTextForSearchIndex() : '';
565 class SearchResultSet
{
567 * Fetch an array of regular expression fragments for matching
568 * the search terms as parsed by this engine in a text extract.
573 function termMatches() {
582 * Return true if results are included in this result set.
587 function hasResults() {
592 * Some search modes return a total hit count for the query
593 * in the entire article database. This may include pages
594 * in namespaces that would not be matched on the given
597 * Return null if no total hits number is supported.
601 function getTotalHits() {
606 * Some search modes return a suggested alternate term if there are
607 * no exact hits. Returns true if there is one on this set.
611 function hasSuggestion() {
616 * @return String: suggested query, null if none
618 function getSuggestionQuery() {
623 * @return String: HTML highlighted suggested query, '' if none
625 function getSuggestionSnippet() {
630 * Return information about how and from where the results were fetched,
631 * should be useful for diagnostics and debugging
640 * Return a result set of hits on other (multiple) wikis associated with this one
642 * @return SearchResultSet
644 function getInterwikiResults() {
649 * Check if there are results on other wikis
653 function hasInterwikiResults() {
654 return $this->getInterwikiResults() != null;
658 * Fetches next search result, or false.
661 * @return SearchResult
668 * Frees the result set, if applicable.
676 * This class is used for different SQL-based search engines shipped with MediaWiki
678 class SqlSearchResultSet
extends SearchResultSet
{
680 protected $mResultSet;
682 function __construct( $resultSet, $terms ) {
683 $this->mResultSet
= $resultSet;
684 $this->mTerms
= $terms;
687 function termMatches() {
688 return $this->mTerms
;
692 if ( $this->mResultSet
=== false ) {
696 return $this->mResultSet
->numRows();
700 if ( $this->mResultSet
=== false ) {
704 $row = $this->mResultSet
->fetchObject();
705 if ( $row === false ) {
709 return SearchResult
::newFromRow( $row );
713 if ( $this->mResultSet
=== false ) {
717 $this->mResultSet
->free();
724 class SearchResultTooMany
{
725 # # Some search engines may bail out if too many matches are found
729 * @todo FIXME: This class is horribly factored. It would probably be better to
730 * have a useful base class to which you pass some standard information, then
731 * let the fancy self-highlighters extend that.
739 var $mRevision = null;
753 * Return a new SearchResult and initializes it with a title.
755 * @param $title Title
756 * @return SearchResult
758 public static function newFromTitle( $title ) {
759 $result = new self();
760 $result->initFromTitle( $title );
764 * Return a new SearchResult and initializes it with a row.
767 * @return SearchResult
769 public static function newFromRow( $row ) {
770 $result = new self();
771 $result->initFromRow( $row );
775 public function __construct( $row = null ) {
776 if ( !is_null( $row ) ) {
777 // Backwards compatibility with pre-1.17 callers
778 $this->initFromRow( $row );
783 * Initialize from a database row. Makes a Title and passes that to
788 protected function initFromRow( $row ) {
789 $this->initFromTitle( Title
::makeTitle( $row->page_namespace
, $row->page_title
) );
793 * Initialize from a Title and if possible initializes a corresponding
796 * @param $title Title
798 protected function initFromTitle( $title ) {
799 $this->mTitle
= $title;
800 if ( !is_null( $this->mTitle
) ) {
802 wfRunHooks( 'SearchResultInitFromTitle', array( $title, &$id ) );
803 $this->mRevision
= Revision
::newFromTitle(
804 $this->mTitle
, $id, Revision
::READ_NORMAL
);
805 if ( $this->mTitle
->getNamespace() === NS_FILE
) {
806 $this->mImage
= wfFindFile( $this->mTitle
);
812 * Check if this is result points to an invalid title
816 function isBrokenTitle() {
817 if ( is_null( $this->mTitle
) ) {
824 * Check if target page is missing, happens when index is out of date
828 function isMissingRevision() {
829 return !$this->mRevision
&& !$this->mImage
;
835 function getTitle() {
836 return $this->mTitle
;
840 * @return float|null if not supported
842 function getScore() {
847 * Lazy initialization of article text from DB
849 protected function initText() {
850 if ( !isset( $this->mText
) ) {
851 if ( $this->mRevision
!= null ) {
852 $this->mText
= SearchEngine
::create()
853 ->getTextFromContent( $this->mTitle
, $this->mRevision
->getContent() );
854 } else { // TODO: can we fetch raw wikitext for commons images?
861 * @param array $terms terms to highlight
862 * @return String: highlighted text snippet, null (and not '') if not supported
864 function getTextSnippet( $terms ) {
865 global $wgUser, $wgAdvancedSearchHighlighting;
868 // TODO: make highliter take a content object. Make ContentHandler a factory for SearchHighliter.
869 list( $contextlines, $contextchars ) = SearchEngine
::userHighlightPrefs( $wgUser );
870 $h = new SearchHighlighter();
871 if ( $wgAdvancedSearchHighlighting ) {
872 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
874 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
879 * @param array $terms terms to highlight
880 * @return String: highlighted title, '' if not supported
882 function getTitleSnippet( $terms ) {
887 * @param array $terms terms to highlight
888 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
890 function getRedirectSnippet( $terms ) {
895 * @return Title object for the redirect to this page, null if none or not supported
897 function getRedirectTitle() {
902 * @return string highlighted relevant section name, null if none or not supported
904 function getSectionSnippet() {
909 * @return Title object (pagename+fragment) for the section, null if none or not supported
911 function getSectionTitle() {
916 * @return String: timestamp
918 function getTimestamp() {
919 if ( $this->mRevision
) {
920 return $this->mRevision
->getTimestamp();
921 } elseif ( $this->mImage
) {
922 return $this->mImage
->getTimestamp();
928 * @return Integer: number of words
930 function getWordCount() {
932 return str_word_count( $this->mText
);
936 * @return Integer: size in bytes
938 function getByteSize() {
940 return strlen( $this->mText
);
944 * @return Boolean if hit has related articles
946 function hasRelated() {
951 * @return String: interwiki prefix of the title (return iw even if title is broken)
953 function getInterwikiPrefix() {
958 * A SearchResultSet wrapper for SearchEngine::getNearMatch
960 class SearchNearMatchResultSet
extends SearchResultSet
{
961 private $fetched = false;
963 * @param $match mixed Title if matched, else null
965 public function __construct( $match ) {
966 $this->result
= $match;
968 public function hasResult() {
969 return (bool)$this->result
;
971 public function numRows() {
972 return $this->hasResults() ?
1 : 0;
974 public function next() {
975 if ( $this->fetched ||
!$this->result
) {
978 $this->fetched
= true;
979 return SearchResult
::newFromTitle( $this->result
);
984 * Highlight bits of wikitext
988 class SearchHighlighter
{
989 var $mCleanWikitext = true;
991 function __construct( $cleanupWikitext = true ) {
992 $this->mCleanWikitext
= $cleanupWikitext;
996 * Default implementation of wikitext highlighting
998 * @param $text String
999 * @param array $terms terms to highlight (unescaped)
1000 * @param $contextlines Integer
1001 * @param $contextchars Integer
1004 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
1006 global $wgSearchHighlightBoundaries;
1007 $fname = __METHOD__
;
1009 if ( $text == '' ) {
1013 // spli text into text + templates/links/tables
1014 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
1015 // first capture group is for detecting nested templates/links/tables/references
1016 $endPatterns = array(
1017 1 => '/(\{\{)|(\}\})/', // template
1018 2 => '/(\[\[)|(\]\])/', // image
1019 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
1021 // @todo FIXME: This should prolly be a hook or something
1022 if ( function_exists( 'wfCite' ) ) {
1023 $spat .= '|(<ref>)'; // references via cite extension
1024 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
1027 $textExt = array(); // text extracts
1028 $otherExt = array(); // other extracts
1029 wfProfileIn( "$fname-split" );
1031 $textLen = strlen( $text );
1032 $count = 0; // sequence number to maintain ordering
1033 while ( $start < $textLen ) {
1034 // find start of template/image/table
1035 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ) {
1037 foreach ( $matches as $key => $val ) {
1038 if ( $key > 0 && $val[1] != - 1 ) {
1040 // see if this is an image link
1041 $ns = substr( $val[0], 2, - 1 );
1042 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE
) {
1047 $epat = $endPatterns[$key];
1048 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
1054 // find end (and detect any nested elements)
1056 $offset = $start +
1;
1058 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ) {
1059 if ( array_key_exists( 2, $endMatches ) ) {
1061 if ( $level == 0 ) {
1062 $len = strlen( $endMatches[2][0] );
1063 $off = $endMatches[2][1];
1064 $this->splitAndAdd( $otherExt, $count,
1065 substr( $text, $start, $off +
$len - $start ) );
1066 $start = $off +
$len;
1070 // end of nested element
1077 $offset = $endMatches[0][1] +
strlen( $endMatches[0][0] );
1080 // couldn't find appropriate closing tag, skip
1081 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
1082 $start +
= strlen( $matches[0][0] );
1087 // else: add as text extract
1088 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
1092 $all = $textExt +
$otherExt; // these have disjunct key sets
1094 wfProfileOut( "$fname-split" );
1097 foreach ( $terms as $index => $term ) {
1098 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
1099 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
1100 $terms[$index] = preg_replace_callback( '/./us', array( $this, 'caseCallback' ), $terms[$index] );
1102 $terms[$index] = $term;
1105 $anyterm = implode( '|', $terms );
1106 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
1108 // @todo FIXME: A hack to scale contextchars, a correct solution
1109 // would be to have contextchars actually be char and not byte
1110 // length, and do proper utf-8 substrings and lengths everywhere,
1111 // but PHP is making that very hard and unclean to implement :(
1112 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
1113 $contextchars = intval( $contextchars * $scale );
1115 $patPre = "(^|$wgSearchHighlightBoundaries)";
1116 $patPost = "($wgSearchHighlightBoundaries|$)";
1118 $pat1 = "/(" . $phrase . ")/ui";
1119 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
1121 wfProfileIn( "$fname-extract" );
1123 $left = $contextlines;
1125 $snippets = array();
1128 // show beginning only if it contains all words
1131 foreach ( $textExt as $index => $line ) {
1132 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
1133 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
1140 // check if first text contains all terms
1141 foreach ( $terms as $term ) {
1142 if ( ! preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
1148 $snippets[$first] = $firstText;
1149 $offsets[$first] = 0;
1152 if ( ! $snippets ) {
1153 // match whole query on text
1154 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
1155 // match whole query on templates/tables/images
1156 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
1157 // match any words on text
1158 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
1159 // match any words on templates/tables/images
1160 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
1165 // add extra chars to each snippet to make snippets constant size
1166 $extended = array();
1167 if ( count( $snippets ) == 0 ) {
1168 // couldn't find the target words, just show beginning of article
1169 if ( array_key_exists( $first, $all ) ) {
1170 $targetchars = $contextchars * $contextlines;
1171 $snippets[$first] = '';
1172 $offsets[$first] = 0;
1175 // if begin of the article contains the whole phrase, show only that !!
1176 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
1177 && $offsets[$first] < $contextchars * 2 ) {
1178 $snippets = array( $first => $snippets[$first] );
1181 // calc by how much to extend existing snippets
1182 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
1185 foreach ( $snippets as $index => $line ) {
1186 $extended[$index] = $line;
1187 $len = strlen( $line );
1188 if ( $len < $targetchars - 20 ) {
1189 // complete this line
1190 if ( $len < strlen( $all[$index] ) ) {
1191 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index] +
$targetchars, $offsets[$index] );
1192 $len = strlen( $extended[$index] );
1197 while ( $len < $targetchars - 20
1198 && array_key_exists( $add, $all )
1199 && !array_key_exists( $add, $snippets ) ) {
1201 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
1202 $extended[$add] = $tt;
1203 $len +
= strlen( $tt );
1209 // $snippets = array_map( 'htmlspecialchars', $extended );
1210 $snippets = $extended;
1213 foreach ( $snippets as $index => $line ) {
1214 if ( $last == - 1 ) {
1215 $extract .= $line; // first line
1216 } elseif ( $last +
1 == $index && $offsets[$last] +
strlen( $snippets[$last] ) >= strlen( $all[$last] ) ) {
1217 $extract .= " " . $line; // continous lines
1219 $extract .= '<b> ... </b>' . $line;
1225 $extract .= '<b> ... </b>';
1228 $processed = array();
1229 foreach ( $terms as $term ) {
1230 if ( ! isset( $processed[$term] ) ) {
1231 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
1232 $extract = preg_replace( $pat3,
1233 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1234 $processed[$term] = true;
1238 wfProfileOut( "$fname-extract" );
1244 * Split text into lines and add it to extracts array
1246 * @param array $extracts index -> $line
1247 * @param $count Integer
1248 * @param $text String
1250 function splitAndAdd( &$extracts, &$count, $text ) {
1251 $split = explode( "\n", $this->mCleanWikitext ?
$this->removeWiki( $text ) : $text );
1252 foreach ( $split as $line ) {
1253 $tt = trim( $line );
1255 $extracts[$count++
] = $tt;
1261 * Do manual case conversion for non-ascii chars
1263 * @param $matches Array
1266 function caseCallback( $matches ) {
1268 if ( strlen( $matches[0] ) > 1 ) {
1269 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
1276 * Extract part of the text from start to end, but by
1277 * not chopping up words
1278 * @param $text String
1279 * @param $start Integer
1280 * @param $end Integer
1281 * @param $posStart Integer: (out) actual start position
1282 * @param $posEnd Integer: (out) actual end position
1285 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
1286 if ( $start != 0 ) {
1287 $start = $this->position( $text, $start, 1 );
1289 if ( $end >= strlen( $text ) ) {
1290 $end = strlen( $text );
1292 $end = $this->position( $text, $end );
1295 if ( !is_null( $posStart ) ) {
1298 if ( !is_null( $posEnd ) ) {
1302 if ( $end > $start ) {
1303 return substr( $text, $start, $end - $start );
1310 * Find a nonletter near a point (index) in the text
1312 * @param $text String
1313 * @param $point Integer
1314 * @param $offset Integer: offset to found index
1315 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1317 function position( $text, $point, $offset = 0 ) {
1319 $s = max( 0, $point - $tolerance );
1320 $l = min( strlen( $text ), $point +
$tolerance ) - $s;
1322 if ( preg_match( '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr( $text, $s, $l ), $m, PREG_OFFSET_CAPTURE
) ) {
1323 return $m[0][1] +
$s +
$offset;
1325 // check if point is on a valid first UTF8 char
1326 $char = ord( $text[$point] );
1327 while ( $char >= 0x80 && $char < 0xc0 ) {
1328 // skip trailing bytes
1330 if ( $point >= strlen( $text ) ) {
1331 return strlen( $text );
1333 $char = ord( $text[$point] );
1341 * Search extracts for a pattern, and return snippets
1343 * @param string $pattern regexp for matching lines
1344 * @param array $extracts extracts to search
1345 * @param $linesleft Integer: number of extracts to make
1346 * @param $contextchars Integer: length of snippet
1347 * @param array $out map for highlighted snippets
1348 * @param array $offsets map of starting points of snippets
1351 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
1352 if ( $linesleft == 0 ) {
1353 return; // nothing to do
1355 foreach ( $extracts as $index => $line ) {
1356 if ( array_key_exists( $index, $out ) ) {
1357 continue; // this line already highlighted
1361 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) ) {
1366 $len = strlen( $m[0][0] );
1367 if ( $offset +
$len < $contextchars ) {
1369 } elseif ( $len > $contextchars ) {
1372 $begin = $offset +
intval( ( $len - $contextchars ) / 2 );
1375 $end = $begin +
$contextchars;
1378 // basic snippet from this line
1379 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
1380 $offsets[$index] = $posBegin;
1382 if ( $linesleft == 0 ) {
1389 * Basic wikitext removal
1393 function removeWiki( $text ) {
1394 $fname = __METHOD__
;
1395 wfProfileIn( $fname );
1397 // $text = preg_replace( "/'{2,5}/", "", $text );
1398 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
1399 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
1400 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
1401 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
1402 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
1403 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
1404 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
1405 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
1406 $text = preg_replace_callback( "/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array( $this, 'linkReplace' ), $text );
1407 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1408 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
1409 $text = preg_replace( "/'''''/", "", $text );
1410 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
1411 $text = preg_replace( "/''/", "", $text );
1413 wfProfileOut( $fname );
1418 * callback to replace [[target|caption]] kind of links, if
1419 * the target is category or image, leave it
1421 * @param $matches Array
1423 function linkReplace( $matches ) {
1424 $colon = strpos( $matches[1], ':' );
1425 if ( $colon === false ) {
1426 return $matches[2]; // replace with caption
1429 $ns = substr( $matches[1], 0, $colon );
1430 $index = $wgContLang->getNsIndex( $ns );
1431 if ( $index !== false && ( $index == NS_FILE ||
$index == NS_CATEGORY
) ) {
1432 return $matches[0]; // return the whole thing
1439 * Simple & fast snippet extraction, but gives completely unrelevant
1442 * @param $text String
1443 * @param $terms Array
1444 * @param $contextlines Integer
1445 * @param $contextchars Integer
1448 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1450 $fname = __METHOD__
;
1452 $lines = explode( "\n", $text );
1454 $terms = implode( '|', $terms );
1455 $max = intval( $contextchars ) +
1;
1456 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1461 wfProfileIn( "$fname-extract" );
1462 foreach ( $lines as $line ) {
1463 if ( 0 == $contextlines ) {
1468 if ( ! preg_match( $pat1, $line, $m ) ) {
1472 // truncate function changes ... to relevant i18n message.
1473 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
1475 if ( count( $m ) < 3 ) {
1478 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
1483 $line = htmlspecialchars( $pre . $found . $post );
1484 $pat2 = '/(' . $terms . ")/i";
1485 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
1487 $extract .= "${line}\n";
1489 wfProfileOut( "$fname-extract" );
1497 * Dummy class to be used when non-supported Database engine is present.
1498 * @todo FIXME: Dummy class should probably try something at least mildly useful,
1499 * such as a LIKE search through titles.
1502 class SearchEngineDummy
extends SearchEngine
{