3 * @defgroup Search Search
10 * Contain a class for special pages
17 var $searchTerms = array();
18 var $namespaces = array( NS_MAIN
);
19 var $showRedirects = false;
22 * Perform a full text search query and return a result set.
23 * If title searches are not supported or disabled, return null.
26 * @param $term String: raw search term
27 * @return SearchResultSet
29 function searchText( $term ) {
34 * Perform a title-only search query and return a result set.
35 * If title searches are not supported or disabled, return null.
38 * @param $term String: raw search term
39 * @return SearchResultSet
41 function searchTitle( $term ) {
45 /** If this search backend can list/unlist redirects */
46 function acceptListRedirects() {
51 * When overridden in derived class, performs database-specific conversions
52 * on text to be used for searching or updating search index.
53 * Default implementation does nothing (simply returns $string).
55 * @param $string string: String to process
58 public function normalizeText( $string ) {
61 // Some languages such as Chinese require word segmentation
62 return $wgContLang->segmentByWord( $string );
66 * Transform search term in cases when parts of the query came as different GET params (when supported)
67 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
69 function transformSearchTerm( $term ) {
74 * If an exact title match can be found, or a very slightly close match,
75 * return the title. If no match, returns NULL.
77 * @param $searchterm String
80 public static function getNearMatch( $searchterm ) {
81 $title = self
::getNearMatchInternal( $searchterm );
83 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
88 * Really find the title match.
90 private static function getNearMatchInternal( $searchterm ) {
93 $allSearchTerms = array($searchterm);
95 if ( $wgContLang->hasVariants() ) {
96 $allSearchTerms = array_merge($allSearchTerms,$wgContLang->convertLinkToAllVariants($searchterm));
99 if( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
103 foreach($allSearchTerms as $term) {
105 # Exact match? No need to look further.
106 $title = Title
::newFromText( $term );
110 if ( $title->getNamespace() == NS_SPECIAL ||
$title->isExternal() ||
$title->exists() ) {
114 # See if it still otherwise has content is some sane sense
115 $article = MediaWiki
::articleFromTitle( $title );
116 if( $article->hasViewableContent() ) {
120 # Now try all lower case (i.e. first letter capitalized)
122 $title = Title
::newFromText( $wgContLang->lc( $term ) );
123 if ( $title && $title->exists() ) {
127 # Now try capitalized string
129 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
130 if ( $title && $title->exists() ) {
134 # Now try all upper case
136 $title = Title
::newFromText( $wgContLang->uc( $term ) );
137 if ( $title && $title->exists() ) {
141 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
142 $title = Title
::newFromText( $wgContLang->ucwordbreaks($term) );
143 if ( $title && $title->exists() ) {
147 // Give hooks a chance at better match variants
149 if( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
154 $title = Title
::newFromText( $searchterm );
156 # Entering an IP address goes to the contributions page
157 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP($title->getText() ) )
158 || User
::isIP( trim( $searchterm ) ) ) {
159 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
163 # Entering a user goes to the user page whether it's there or not
164 if ( $title->getNamespace() == NS_USER
) {
168 # Go to images that exist even if there's no local page.
169 # There may have been a funny upload, or it may be on a shared
170 # file repository such as Wikimedia Commons.
171 if( $title->getNamespace() == NS_FILE
) {
172 $image = wfFindFile( $title );
178 # MediaWiki namespace? Page may be "implied" if not customized.
179 # Just return it, with caps forced as the message system likes it.
180 if( $title->getNamespace() == NS_MEDIAWIKI
) {
181 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
184 # Quoted term? Try without the quotes...
186 if( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
187 return SearchEngine
::getNearMatch( $matches[1] );
193 public static function legalSearchChars() {
194 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
198 * Set the maximum number of results to return
199 * and how many to skip before returning the first.
201 * @param $limit Integer
202 * @param $offset Integer
204 function setLimitOffset( $limit, $offset = 0 ) {
205 $this->limit
= intval( $limit );
206 $this->offset
= intval( $offset );
210 * Set which namespaces the search should include.
211 * Give an array of namespace index numbers.
213 * @param $namespaces Array
215 function setNamespaces( $namespaces ) {
216 $this->namespaces
= $namespaces;
220 * Parse some common prefixes: all (search everything)
223 * @param $query String
225 function replacePrefixes( $query ){
229 if( strpos($query,':') === false ) { // nothing to do
230 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
234 $allkeyword = wfMsgForContent('searchall').":";
235 if( strncmp($query, $allkeyword, strlen($allkeyword)) == 0 ){
236 $this->namespaces
= null;
237 $parsed = substr($query,strlen($allkeyword));
238 } else if( strpos($query,':') !== false ) {
239 $prefix = substr($query,0,strpos($query,':'));
240 $index = $wgContLang->getNsIndex($prefix);
241 if($index !== false){
242 $this->namespaces
= array($index);
243 $parsed = substr($query,strlen($prefix)+
1);
246 if(trim($parsed) == '')
247 $parsed = $query; // prefix was the whole query
249 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
255 * Make a list of searchable namespaces and their canonical names.
258 public static function searchableNamespaces() {
261 foreach( $wgContLang->getNamespaces() as $ns => $name ) {
262 if( $ns >= NS_MAIN
) {
267 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
272 * Extract default namespaces to search from the given user's
273 * settings, returning a list of index numbers.
278 public static function userNamespaces( $user ) {
279 global $wgSearchEverythingOnlyLoggedIn;
281 // get search everything preference, that can be set to be read for logged-in users
282 $searcheverything = false;
283 if( ( $wgSearchEverythingOnlyLoggedIn && $user->isLoggedIn() )
284 ||
!$wgSearchEverythingOnlyLoggedIn )
285 $searcheverything = $user->getOption('searcheverything');
287 // searcheverything overrides other options
288 if( $searcheverything )
289 return array_keys(SearchEngine
::searchableNamespaces());
291 $arr = Preferences
::loadOldSearchNs( $user );
292 $searchableNamespaces = SearchEngine
::searchableNamespaces();
294 $arr = array_intersect( $arr, array_keys($searchableNamespaces) ); // Filter
300 * Find snippet highlight settings for a given user
303 * @return Array contextlines, contextchars
305 public static function userHighlightPrefs( &$user ){
306 //$contextlines = $user->getOption( 'contextlines', 5 );
307 //$contextchars = $user->getOption( 'contextchars', 50 );
308 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
309 $contextchars = 75; // same as above.... :P
310 return array($contextlines, $contextchars);
314 * An array of namespaces indexes to be searched by default
318 public static function defaultNamespaces(){
319 global $wgNamespacesToBeSearchedDefault;
321 return array_keys($wgNamespacesToBeSearchedDefault, true);
325 * Get a list of namespace names useful for showing in tooltips
328 * @param $namespaces Array
330 public static function namespacesAsText( $namespaces ){
333 $formatted = array_map( array($wgContLang,'getFormattedNsText'), $namespaces );
334 foreach( $formatted as $key => $ns ){
336 $formatted[$key] = wfMsg( 'blanknamespace' );
342 * Return the help namespaces to be shown on Special:Search
346 public static function helpNamespaces() {
347 global $wgNamespacesToBeSearchedHelp;
349 return array_keys( $wgNamespacesToBeSearchedHelp, true );
353 * Return a 'cleaned up' search string
355 * @param $text String
358 function filter( $text ) {
359 $lc = $this->legalSearchChars();
360 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
363 * Load up the appropriate search engine class for the currently
364 * active database backend, and return a configured instance.
366 * @return SearchEngine
368 public static function create() {
369 global $wgSearchType;
370 $dbr = wfGetDB( DB_SLAVE
);
371 if( $wgSearchType ) {
372 $class = $wgSearchType;
374 $class = $dbr->getSearchEngine();
376 $search = new $class( $dbr );
377 $search->setLimitOffset(0,0);
382 * Create or update the search index record for the given page.
383 * Title and text should be pre-processed.
387 * @param $title String
388 * @param $text String
390 function update( $id, $title, $text ) {
395 * Update a search index record's title only.
396 * Title should be pre-processed.
400 * @param $title String
402 function updateTitle( $id, $title ) {
407 * Get OpenSearch suggestion template
411 public static function getOpenSearchTemplate() {
412 global $wgOpenSearchTemplate, $wgServer, $wgScriptPath;
413 if( $wgOpenSearchTemplate ) {
414 return $wgOpenSearchTemplate;
416 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
417 if( !$ns ) $ns = "0";
418 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace='.$ns;
423 * Get internal MediaWiki Suggest template
427 public static function getMWSuggestTemplate() {
428 global $wgMWSuggestTemplate, $wgServer, $wgScriptPath;
429 if($wgMWSuggestTemplate)
430 return $wgMWSuggestTemplate;
432 return $wgServer . $wgScriptPath . '/api.php?action=opensearch&search={searchTerms}&namespace={namespaces}&suggest';
439 class SearchResultSet
{
441 * Fetch an array of regular expression fragments for matching
442 * the search terms as parsed by this engine in a text extract.
447 function termMatches() {
456 * Return true if results are included in this result set.
461 function hasResults() {
466 * Some search modes return a total hit count for the query
467 * in the entire article database. This may include pages
468 * in namespaces that would not be matched on the given
471 * Return null if no total hits number is supported.
475 function getTotalHits() {
480 * Some search modes return a suggested alternate term if there are
481 * no exact hits. Returns true if there is one on this set.
485 function hasSuggestion() {
490 * @return String: suggested query, null if none
492 function getSuggestionQuery(){
497 * @return String: HTML highlighted suggested query, '' if none
499 function getSuggestionSnippet(){
504 * Return information about how and from where the results were fetched,
505 * should be useful for diagnostics and debugging
514 * Return a result set of hits on other (multiple) wikis associated with this one
516 * @return SearchResultSet
518 function getInterwikiResults() {
523 * Check if there are results on other wikis
527 function hasInterwikiResults() {
528 return $this->getInterwikiResults() != null;
532 * Fetches next search result, or false.
535 * @return SearchResult
542 * Frees the result set, if applicable.
550 * This class is used for different SQL-based search engines shipped with MediaWiki
552 class SqlSearchResultSet
extends SearchResultSet
{
553 function __construct( $resultSet, $terms ) {
554 $this->mResultSet
= $resultSet;
555 $this->mTerms
= $terms;
558 function termMatches() {
559 return $this->mTerms
;
563 if ($this->mResultSet
=== false )
566 return $this->mResultSet
->numRows();
570 if ($this->mResultSet
=== false )
573 $row = $this->mResultSet
->fetchObject();
576 return new SearchResult($row);
580 if ($this->mResultSet
=== false )
583 $this->mResultSet
->free();
590 class SearchResultTooMany
{
591 ## Some search engines may bail out if too many matches are found
596 * @todo Fixme: This class is horribly factored. It would probably be better to
597 * have a useful base class to which you pass some standard information, then
598 * let the fancy self-highlighters extend that.
602 var $mRevision = null;
605 function __construct( $row ) {
606 $this->mTitle
= Title
::makeTitle( $row->page_namespace
, $row->page_title
);
607 if( !is_null($this->mTitle
) ){
608 $this->mRevision
= Revision
::newFromTitle( $this->mTitle
);
609 if( $this->mTitle
->getNamespace() === NS_FILE
)
610 $this->mImage
= wfFindFile( $this->mTitle
);
615 * Check if this is result points to an invalid title
619 function isBrokenTitle(){
620 if( is_null($this->mTitle
) )
626 * Check if target page is missing, happens when index is out of date
630 function isMissingRevision(){
631 return !$this->mRevision
&& !$this->mImage
;
637 function getTitle() {
638 return $this->mTitle
;
642 * @return Double or null if not supported
644 function getScore() {
649 * Lazy initialization of article text from DB
651 protected function initText(){
652 if( !isset($this->mText
) ){
653 if($this->mRevision
!= null)
654 $this->mText
= $this->mRevision
->getText();
655 else // TODO: can we fetch raw wikitext for commons images?
662 * @param $terms Array: terms to highlight
663 * @return String: highlighted text snippet, null (and not '') if not supported
665 function getTextSnippet($terms){
666 global $wgUser, $wgAdvancedSearchHighlighting;
668 list($contextlines,$contextchars) = SearchEngine
::userHighlightPrefs($wgUser);
669 $h = new SearchHighlighter();
670 if( $wgAdvancedSearchHighlighting )
671 return $h->highlightText( $this->mText
, $terms, $contextlines, $contextchars );
673 return $h->highlightSimple( $this->mText
, $terms, $contextlines, $contextchars );
677 * @param $terms Array: terms to highlight
678 * @return String: highlighted title, '' if not supported
680 function getTitleSnippet($terms){
685 * @param $terms Array: terms to highlight
686 * @return String: highlighted redirect name (redirect to this page), '' if none or not supported
688 function getRedirectSnippet($terms){
693 * @return Title object for the redirect to this page, null if none or not supported
695 function getRedirectTitle(){
700 * @return string highlighted relevant section name, null if none or not supported
702 function getSectionSnippet(){
707 * @return Title object (pagename+fragment) for the section, null if none or not supported
709 function getSectionTitle(){
714 * @return String: timestamp
716 function getTimestamp(){
717 if( $this->mRevision
)
718 return $this->mRevision
->getTimestamp();
719 else if( $this->mImage
)
720 return $this->mImage
->getTimestamp();
725 * @return Integer: number of words
727 function getWordCount(){
729 return str_word_count( $this->mText
);
733 * @return Integer: size in bytes
735 function getByteSize(){
737 return strlen( $this->mText
);
741 * @return Boolean if hit has related articles
743 function hasRelated(){
748 * @return String: interwiki prefix of the title (return iw even if title is broken)
750 function getInterwikiPrefix(){
756 * Highlight bits of wikitext
760 class SearchHighlighter
{
761 var $mCleanWikitext = true;
763 function SearchHighlighter($cleanupWikitext = true){
764 $this->mCleanWikitext
= $cleanupWikitext;
768 * Default implementation of wikitext highlighting
770 * @param $text String
771 * @param $terms Array: terms to highlight (unescaped)
772 * @param $contextlines Integer
773 * @param $contextchars Integer
776 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
777 global $wgLang, $wgContLang;
778 global $wgSearchHighlightBoundaries;
784 // spli text into text + templates/links/tables
785 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
786 // first capture group is for detecting nested templates/links/tables/references
787 $endPatterns = array(
788 1 => '/(\{\{)|(\}\})/', // template
789 2 => '/(\[\[)|(\]\])/', // image
790 3 => "/(\n\\{\\|)|(\n\\|\\})/"); // table
792 // FIXME: this should prolly be a hook or something
793 if(function_exists('wfCite')){
794 $spat .= '|(<ref>)'; // references via cite extension
795 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
798 $textExt = array(); // text extracts
799 $otherExt = array(); // other extracts
800 wfProfileIn( "$fname-split" );
802 $textLen = strlen($text);
803 $count = 0; // sequence number to maintain ordering
804 while( $start < $textLen ){
805 // find start of template/image/table
806 if( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE
, $start ) ){
808 foreach($matches as $key => $val){
809 if($key > 0 && $val[1] != -1){
811 // see if this is an image link
812 $ns = substr($val[0],2,-1);
813 if( $wgContLang->getNsIndex($ns) != NS_FILE
)
817 $epat = $endPatterns[$key];
818 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
824 // find end (and detect any nested elements)
826 $offset = $start +
1;
828 while( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE
, $offset ) ){
829 if( array_key_exists(2,$endMatches) ){
832 $len = strlen($endMatches[2][0]);
833 $off = $endMatches[2][1];
834 $this->splitAndAdd( $otherExt, $count,
835 substr( $text, $start, $off +
$len - $start ) );
836 $start = $off +
$len;
840 // end of nested element
847 $offset = $endMatches[0][1] +
strlen($endMatches[0][0]);
850 // couldn't find appropriate closing tag, skip
851 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen($matches[0][0]) ) );
852 $start +
= strlen($matches[0][0]);
857 // else: add as text extract
858 $this->splitAndAdd( $textExt, $count, substr($text,$start) );
862 $all = $textExt +
$otherExt; // these have disjunct key sets
864 wfProfileOut( "$fname-split" );
867 foreach( $terms as $index => $term ) {
868 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
869 if(preg_match('/[\x80-\xff]/', $term) ){
870 $terms[$index] = preg_replace_callback('/./us',array($this,'caseCallback'),$terms[$index]);
872 $terms[$index] = $term;
875 $anyterm = implode( '|', $terms );
876 $phrase = implode("$wgSearchHighlightBoundaries+", $terms );
878 // FIXME: a hack to scale contextchars, a correct solution
879 // would be to have contextchars actually be char and not byte
880 // length, and do proper utf-8 substrings and lengths everywhere,
881 // but PHP is making that very hard and unclean to implement :(
882 $scale = strlen($anyterm) / mb_strlen($anyterm);
883 $contextchars = intval( $contextchars * $scale );
885 $patPre = "(^|$wgSearchHighlightBoundaries)";
886 $patPost = "($wgSearchHighlightBoundaries|$)";
888 $pat1 = "/(".$phrase.")/ui";
889 $pat2 = "/$patPre(".$anyterm.")$patPost/ui";
891 wfProfileIn( "$fname-extract" );
893 $left = $contextlines;
898 // show beginning only if it contains all words
901 foreach($textExt as $index => $line){
902 if(strlen($line)>0 && $line[0] != ';' && $line[0] != ':'){
903 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
910 // check if first text contains all terms
911 foreach($terms as $term){
912 if( ! preg_match("/$patPre".$term."$patPost/ui", $firstText) ){
918 $snippets[$first] = $firstText;
919 $offsets[$first] = 0;
923 // match whole query on text
924 $this->process($pat1, $textExt, $left, $contextchars, $snippets, $offsets);
925 // match whole query on templates/tables/images
926 $this->process($pat1, $otherExt, $left, $contextchars, $snippets, $offsets);
927 // match any words on text
928 $this->process($pat2, $textExt, $left, $contextchars, $snippets, $offsets);
929 // match any words on templates/tables/images
930 $this->process($pat2, $otherExt, $left, $contextchars, $snippets, $offsets);
935 // add extra chars to each snippet to make snippets constant size
937 if( count( $snippets ) == 0 ){
938 // couldn't find the target words, just show beginning of article
939 if ( array_key_exists( $first, $all ) ) {
940 $targetchars = $contextchars * $contextlines;
941 $snippets[$first] = '';
942 $offsets[$first] = 0;
945 // if begin of the article contains the whole phrase, show only that !!
946 if( array_key_exists($first,$snippets) && preg_match($pat1,$snippets[$first])
947 && $offsets[$first] < $contextchars * 2 ){
948 $snippets = array ($first => $snippets[$first]);
951 // calc by how much to extend existing snippets
952 $targetchars = intval( ($contextchars * $contextlines) / count ( $snippets ) );
955 foreach($snippets as $index => $line){
956 $extended[$index] = $line;
957 $len = strlen($line);
958 if( $len < $targetchars - 20 ){
959 // complete this line
960 if($len < strlen( $all[$index] )){
961 $extended[$index] = $this->extract( $all[$index], $offsets[$index], $offsets[$index]+
$targetchars, $offsets[$index]);
962 $len = strlen( $extended[$index] );
967 while( $len < $targetchars - 20
968 && array_key_exists($add,$all)
969 && !array_key_exists($add,$snippets) ){
971 $tt = "\n".$this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
972 $extended[$add] = $tt;
973 $len +
= strlen( $tt );
979 //$snippets = array_map('htmlspecialchars', $extended);
980 $snippets = $extended;
983 foreach($snippets as $index => $line){
985 $extract .= $line; // first line
986 elseif($last+
1 == $index && $offsets[$last]+
strlen($snippets[$last]) >= strlen($all[$last]))
987 $extract .= " ".$line; // continous lines
989 $extract .= '<b> ... </b>' . $line;
994 $extract .= '<b> ... </b>';
996 $processed = array();
997 foreach($terms as $term){
998 if( ! isset($processed[$term]) ){
999 $pat3 = "/$patPre(".$term.")$patPost/ui"; // highlight word
1000 $extract = preg_replace( $pat3,
1001 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
1002 $processed[$term] = true;
1006 wfProfileOut( "$fname-extract" );
1012 * Split text into lines and add it to extracts array
1014 * @param $extracts Array: index -> $line
1015 * @param $count Integer
1016 * @param $text String
1018 function splitAndAdd(&$extracts, &$count, $text){
1019 $split = explode( "\n", $this->mCleanWikitext?
$this->removeWiki($text) : $text );
1020 foreach($split as $line){
1023 $extracts[$count++
] = $tt;
1028 * Do manual case conversion for non-ascii chars
1030 * @param $matches Array
1032 function caseCallback($matches){
1034 if( strlen($matches[0]) > 1 ){
1035 return '['.$wgContLang->lc($matches[0]).$wgContLang->uc($matches[0]).']';
1041 * Extract part of the text from start to end, but by
1042 * not chopping up words
1043 * @param $text String
1044 * @param $start Integer
1045 * @param $end Integer
1046 * @param $posStart Integer: (out) actual start position
1047 * @param $posEnd Integer: (out) actual end position
1050 function extract($text, $start, $end, &$posStart = null, &$posEnd = null ){
1054 $start = $this->position( $text, $start, 1 );
1055 if( $end >= strlen($text) )
1056 $end = strlen($text);
1058 $end = $this->position( $text, $end );
1060 if(!is_null($posStart))
1062 if(!is_null($posEnd))
1066 return substr($text, $start, $end-$start);
1072 * Find a nonletter near a point (index) in the text
1074 * @param $text String
1075 * @param $point Integer
1076 * @param $offset Integer: offset to found index
1077 * @return Integer: nearest nonletter index, or beginning of utf8 char if none
1079 function position($text, $point, $offset=0 ){
1081 $s = max( 0, $point - $tolerance );
1082 $l = min( strlen($text), $point +
$tolerance ) - $s;
1084 if( preg_match('/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/', substr($text,$s,$l), $m, PREG_OFFSET_CAPTURE
) ){
1085 return $m[0][1] +
$s +
$offset;
1087 // check if point is on a valid first UTF8 char
1088 $char = ord( $text[$point] );
1089 while( $char >= 0x80 && $char < 0xc0 ) {
1090 // skip trailing bytes
1092 if($point >= strlen($text))
1093 return strlen($text);
1094 $char = ord( $text[$point] );
1102 * Search extracts for a pattern, and return snippets
1104 * @param $pattern String: regexp for matching lines
1105 * @param $extracts Array: extracts to search
1106 * @param $linesleft Integer: number of extracts to make
1107 * @param $contextchars Integer: length of snippet
1108 * @param $out Array: map for highlighted snippets
1109 * @param $offsets Array: map of starting points of snippets
1112 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ){
1114 return; // nothing to do
1115 foreach($extracts as $index => $line){
1116 if( array_key_exists($index,$out) )
1117 continue; // this line already highlighted
1120 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE
) )
1124 $len = strlen($m[0][0]);
1125 if($offset +
$len < $contextchars)
1127 elseif( $len > $contextchars)
1130 $begin = $offset +
intval( ($len - $contextchars) / 2 );
1132 $end = $begin +
$contextchars;
1135 // basic snippet from this line
1136 $out[$index] = $this->extract($line,$begin,$end,$posBegin);
1137 $offsets[$index] = $posBegin;
1145 * Basic wikitext removal
1148 function removeWiki($text) {
1149 $fname = __METHOD__
;
1150 wfProfileIn( $fname );
1152 //$text = preg_replace("/'{2,5}/", "", $text);
1153 //$text = preg_replace("/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text);
1154 //$text = preg_replace("/\[\[([^]|]+)\]\]/", "\\1", $text);
1155 //$text = preg_replace("/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text);
1156 //$text = preg_replace("/\\{\\|(.*?)\\|\\}/", "", $text);
1157 //$text = preg_replace("/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text);
1158 $text = preg_replace("/\\{\\{([^|]+?)\\}\\}/", "", $text);
1159 $text = preg_replace("/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text);
1160 $text = preg_replace("/\\[\\[([^|]+?)\\]\\]/", "\\1", $text);
1161 $text = preg_replace_callback("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", array($this,'linkReplace'), $text);
1162 //$text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
1163 $text = preg_replace("/<\/?[^>]+>/", "", $text);
1164 $text = preg_replace("/'''''/", "", $text);
1165 $text = preg_replace("/('''|<\/?[iIuUbB]>)/", "", $text);
1166 $text = preg_replace("/''/", "", $text);
1168 wfProfileOut( $fname );
1173 * callback to replace [[target|caption]] kind of links, if
1174 * the target is category or image, leave it
1176 * @param $matches Array
1178 function linkReplace($matches){
1179 $colon = strpos( $matches[1], ':' );
1180 if( $colon === false )
1181 return $matches[2]; // replace with caption
1183 $ns = substr( $matches[1], 0, $colon );
1184 $index = $wgContLang->getNsIndex($ns);
1185 if( $index !== false && ($index == NS_FILE ||
$index == NS_CATEGORY
) )
1186 return $matches[0]; // return the whole thing
1193 * Simple & fast snippet extraction, but gives completely unrelevant
1196 * @param $text String
1197 * @param $terms Array
1198 * @param $contextlines Integer
1199 * @param $contextchars Integer
1202 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
1203 global $wgLang, $wgContLang;
1204 $fname = __METHOD__
;
1206 $lines = explode( "\n", $text );
1208 $terms = implode( '|', $terms );
1209 $max = intval( $contextchars ) +
1;
1210 $pat1 = "/(.*)($terms)(.{0,$max})/i";
1215 wfProfileIn( "$fname-extract" );
1216 foreach ( $lines as $line ) {
1217 if ( 0 == $contextlines ) {
1222 if ( ! preg_match( $pat1, $line, $m ) ) {
1226 $pre = $wgContLang->truncate( $m[1], -$contextchars );
1228 if ( count( $m ) < 3 ) {
1231 $post = $wgContLang->truncate( $m[3], $contextchars );
1236 $line = htmlspecialchars( $pre . $found . $post );
1237 $pat2 = '/(' . $terms . ")/i";
1238 $line = preg_replace( $pat2,
1239 "<span class='searchmatch'>\\1</span>", $line );
1241 $extract .= "${line}\n";
1243 wfProfileOut( "$fname-extract" );
1251 * Dummy class to be used when non-supported Database engine is present.
1252 * @todo Fixme: dummy class should probably try something at least mildly useful,
1253 * such as a LIKE search through titles.
1256 class SearchEngineDummy
extends SearchEngine
{