5b642bfaca5faa08d0550af53a9d981c410f0848
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
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
21 * Run text & title search and display the output
22 * @addtogroup SpecialPage
28 * @param $par String: (default '')
30 function wfSpecialSearch( $par = '' ) {
31 global $wgRequest, $wgUser;
33 $search = str_replace( "\n", " ", $wgRequest->getText( 'search', $par ) );
34 $searchPage = new SpecialSearch( $wgRequest, $wgUser );
35 if( $wgRequest->getVal( 'fulltext' ) ||
36 !is_null( $wgRequest->getVal( 'offset' ) ) ||
37 !is_null ($wgRequest->getVal( 'searchx' ) ) ) {
38 $searchPage->showResults( $search );
40 $searchPage->goResult( $search );
45 * implements Special:Search - Run text & title search and display the output
46 * @addtogroup SpecialPage
51 * Set up basic search parameters from the request and user settings.
52 * Typically you'll pass $wgRequest and $wgUser.
54 * @param WebRequest $request
58 function SpecialSearch( &$request, &$user ) {
59 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, 'searchlimit' );
61 $this->namespaces
= $this->powerSearch( $request );
62 if( empty( $this->namespaces
) ) {
63 $this->namespaces
= $this->userNamespaces( $user );
66 $this->searchRedirects
= $request->getcheck( 'redirs' ) ?
true : false;
70 * If an exact title match can be found, jump straight ahead to it.
74 function goResult( $term ) {
78 $this->setupPage( $term );
80 # Try to go to page as entered.
81 $t = Title
::newFromText( $term );
83 # If the string cannot be used to create a title
85 return $this->showResults( $term );
88 # If there's an exact or very near match, jump right there.
89 $t = SearchEngine
::getNearMatch( $term );
90 if( !is_null( $t ) ) {
91 $wgOut->redirect( $t->getFullURL() );
95 # No match, generate an edit URL
96 $t = Title
::newFromText( $term );
97 if( ! is_null( $t ) ) {
98 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
99 # If the feature is enabled, go straight to the edit page
101 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
105 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
106 $wgOut->addWikiMsg( 'noexactmatch', wfEscapeWikiText( $term ) );
108 $wgOut->addWikiMsg( 'noexactmatch-nocreate', wfEscapeWikiText( $term ) );
111 return $this->showResults( $term );
115 * @param string $term
118 function showResults( $term ) {
119 $fname = 'SpecialSearch::showResults';
120 wfProfileIn( $fname );
122 $this->setupPage( $term );
125 $wgOut->addWikiMsg( 'searchresulttext' );
127 if( '' === trim( $term ) ) {
128 // Empty query -- straight view of search form
129 $wgOut->setSubtitle( '' );
130 $wgOut->addHTML( $this->powerSearchBox( $term ) );
131 $wgOut->addHTML( $this->powerSearchFocus() );
132 wfProfileOut( $fname );
136 global $wgDisableTextSearch;
137 if ( $wgDisableTextSearch ) {
138 global $wgForwardSearchUrl;
139 if( $wgForwardSearchUrl ) {
140 $url = str_replace( '$1', urlencode( $term ), $wgForwardSearchUrl );
141 $wgOut->redirect( $url );
144 global $wgInputEncoding;
146 Xml
::openElement( 'fieldset' ) .
147 Xml
::element( 'legend', null, wfMsg( 'search-external' ) ) .
148 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
149 wfMsg( 'googlesearch',
150 htmlspecialchars( $term ),
151 htmlspecialchars( $wgInputEncoding ),
152 htmlspecialchars( wfMsg( 'searchbutton' ) )
154 Xml
::closeElement( 'fieldset' )
156 wfProfileOut( $fname );
160 $wgOut->addHTML( $this->shortDialog( $term ) );
162 $search = SearchEngine
::create();
163 $search->setLimitOffset( $this->limit
, $this->offset
);
164 $search->setNamespaces( $this->namespaces
);
165 $search->showRedirects
= $this->searchRedirects
;
166 $rewritten = $search->replacePrefixes($term);
168 $titleMatches = $search->searchTitle( $rewritten );
170 // Sometimes the search engine knows there are too many hits
171 if ($titleMatches instanceof SearchResultTooMany
) {
172 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
173 $wgOut->addHTML( $this->powerSearchBox( $term ) );
174 $wgOut->addHTML( $this->powerSearchFocus() );
175 wfProfileOut( $fname );
178 $textMatches = $search->searchText( $rewritten );
181 if($textMatches && $textMatches->hasSuggestion()){
183 $fulltext = htmlspecialchars(wfMsg('search'));
184 $suggestLink = '<a href="'.$wgScript.'?title=Special:Search&search='.
185 urlencode($textMatches->getSuggestionQuery()).'&fulltext='.$fulltext.'">'
186 .$textMatches->getSuggestionSnippet().'</a>';
187 $wgOut->addHTML('<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>');
191 $num = ( $titleMatches ?
$titleMatches->numRows() : 0 )
192 +
( $textMatches ?
$textMatches->numRows() : 0);
194 if($titleMatches && !is_null($titleMatches->getTotalHits()))
195 $totalNum +
= $titleMatches->getTotalHits();
196 if($textMatches && !is_null($textMatches->getTotalHits()))
197 $totalNum +
= $textMatches->getTotalHits();
199 if ( $totalNum > 0 ){
200 $top = wfMsgExt('showingresultstotal',array( 'parseinline' ), $this->offset+
1, $this->offset+
$num, $totalNum);
201 } elseif ( $num >= $this->limit
) {
202 $top = wfShowingResults( $this->offset
, $this->limit
);
204 $top = wfShowingResultsNum( $this->offset
, $this->limit
, $num );
206 $wgOut->addHTML( "<p>{$top}</p>\n" );
209 if( $num ||
$this->offset
) {
210 $prevnext = wfViewPrevNext( $this->offset
, $this->limit
,
211 SpecialPage
::getTitleFor( 'Search' ),
213 $this->powerSearchOptions(),
214 array( 'search' => $term ) ),
215 ($num < $this->limit
) );
216 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
217 wfRunHooks( 'SpecialSearchResults', array( $term, $titleMatches, $textMatches ) );
219 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
222 if( $titleMatches ) {
223 if( $titleMatches->numRows() ) {
224 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
225 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
227 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
229 $titleMatches->free();
233 if( $textMatches->numRows() ) {
235 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
236 else // if no title matches the heading is redundant
237 $wgOut->addHTML("<hr/>");
238 $wgOut->addHTML( $this->showMatches( $textMatches ) );
239 } elseif( $num == 0 ) {
240 # Don't show the 'no text matches' if we received title matches
241 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
243 $textMatches->free();
247 $wgOut->addWikiMsg( 'nonefound' );
249 if( $num ||
$this->offset
) {
250 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
252 $wgOut->addHTML( $this->powerSearchBox( $term ) );
253 wfProfileOut( $fname );
256 #------------------------------------------------------------------
257 # Private methods below this line
262 function setupPage( $term ) {
264 if( !empty( $term ) )
265 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
266 $subtitlemsg = ( Title
::newFromText( $term ) ?
'searchsubtitle' : 'searchsubtitleinvalid' );
267 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
268 $wgOut->setArticleRelated( false );
269 $wgOut->setRobotpolicy( 'noindex,nofollow' );
273 * Extract default namespaces to search from the given user's
274 * settings, returning a list of index numbers.
280 function userNamespaces( &$user ) {
282 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
283 if( $user->getOption( 'searchNs' . $ns ) ) {
291 * Extract "power search" namespace settings from the request object,
292 * returning a list of index numbers to search.
294 * @param WebRequest $request
298 function powerSearch( &$request ) {
300 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
301 if( $request->getCheck( 'ns' . $ns ) ) {
309 * Reconstruct the 'power search' options for links
313 function powerSearchOptions() {
315 foreach( $this->namespaces
as $n ) {
318 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
325 * @param SearchResultSet $matches
326 * @param string $terms partial regexp for highlighting terms
328 function showMatches( &$matches ) {
329 $fname = 'SpecialSearch::showMatches';
330 wfProfileIn( $fname );
333 $tm = $wgContLang->convertForSearchResult( $matches->termMatches() );
334 $terms = implode( '|', $tm );
336 $off = $this->offset +
1;
337 $out = "<ul start='{$off}' class='mw-search-results'>\n";
339 while( $result = $matches->next() ) {
340 $out .= $this->showHit( $result, $terms );
344 // convert the whole thing to desired language variant
346 $out = $wgContLang->convert( $out );
347 wfProfileOut( $fname );
352 * Format a single hit result
353 * @param SearchResult $result
354 * @param string $terms partial regexp for highlighting terms
356 function showHit( $result, $terms ) {
357 $fname = 'SpecialSearch::showHit';
358 wfProfileIn( $fname );
359 global $wgUser, $wgContLang, $wgLang;
361 $t = $result->getTitle();
362 if( is_null( $t ) ) {
363 wfProfileOut( $fname );
364 return "<!-- Broken link in search result -->\n";
366 $sk = $wgUser->getSkin();
368 //$contextlines = $wgUser->getOption( 'contextlines', 5 );
369 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
370 $contextchars = $wgUser->getOption( 'contextchars', 50 );
372 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet());
374 //If page content is not readable, just return the title.
375 //This is not quite safe, but better than showing excerpts from non-readable pages
376 //Note that hiding the entry entirely would screw up paging.
377 if (!$t->userCanRead()) {
378 return "<li>{$link}</li>\n";
381 $revision = Revision
::newFromTitle( $t );
382 // If the page doesn't *exist*... our search index is out of date.
383 // The least confusing at this point is to drop the result.
384 // You may get less results, but... oh well. :P
386 return "<!-- missing page " .
387 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
390 if( is_null( $result->getScore() ) ) {
391 // Search engine doesn't report scoring info
394 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
395 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
399 // try to fetch everything from the search engine backend
400 // then fill-in what couldn't be fetched
401 $extract = $result->getTextSnippet();
402 $byteSize = $result->getByteSize();
403 $wordCount = $result->getWordCount();
404 $timestamp = $result->getTimestamp();
405 $redirectTitle = $result->getRedirectTitle();
406 $redirectText = $result->getRedirectSnippet();
407 $sectionTitle = $result->getSectionTitle();
408 $sectionText = $result->getSectionSnippet();
411 if( is_null($extract) ||
is_null($wordCount) ||
is_null($byteSize) ){
412 $text = $revision->getText();
413 if( is_null($extract) )
414 $extract = $this->extractText( $text, $terms, $contextlines, $contextchars );
415 if( is_null($byteSize) )
416 $byteSize = strlen( $text );
417 if( is_null($wordCount) )
418 $wordCount = str_word_count( $text );
420 if( is_null($timestamp) ){
421 $timestamp = $revision->getTimestamp();
424 // format description
425 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
426 $sk->formatSize( $byteSize ),
428 $date = $wgLang->timeanddate( $timestamp );
430 // format redirects / sections
432 if( !is_null($redirectTitle) )
433 $redirect = "<span class='searchalttitle'>"
434 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
437 if( !is_null($sectionTitle) )
438 $section = "<span class='searchalttitle'>"
439 .wfMsg('search-section', $sk->makeKnownLinkObj( $sectionTitle, $sectionText))
442 $extract = "<div class='searchresult'>".$extract."</div>";
444 // Include a thumbnail for media files...
445 if( $t->getNamespace() == NS_IMAGE
) {
446 $img = wfFindFile( $t );
448 $thumb = $img->getThumbnail( 120, 120 );
450 $desc = $img->getShortDesc();
451 wfProfileOut( $fname );
453 // Float doesn't seem to interact well with the bullets.
454 // Table messes up vertical alignment of the bullet, but I'm
455 // not sure what more I can do about that. :(
457 '<table class="searchResultImage">' .
459 '<td width="120" align="center">' .
460 $thumb->toHtml( array( 'desc-link' => true ) ) .
462 '<td valign="top">' .
465 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}</div>" .
474 wfProfileOut( $fname );
475 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
476 "<div class='mw-search-result-data'>{$score}{$size} - {$date}</div>" .
481 private function extractText( $text, $terms, $contextlines, $contextchars ) {
482 global $wgLang, $wgContLang;
485 $lines = explode( "\n", $text );
487 $max = intval( $contextchars ) +
1;
488 $pat1 = "/(.*)($terms)(.{0,$max})/i";
493 wfProfileIn( "$fname-extract" );
494 foreach ( $lines as $line ) {
495 if ( 0 == $contextlines ) {
500 if ( ! preg_match( $pat1, $line, $m ) ) {
504 $pre = $wgContLang->truncate( $m[1], -$contextchars, ' ... ' );
506 if ( count( $m ) < 3 ) {
509 $post = $wgContLang->truncate( $m[3], $contextchars, ' ... ' );
514 $line = htmlspecialchars( $pre . $found . $post );
515 $pat2 = '/(' . $terms . ")/i";
516 $line = preg_replace( $pat2,
517 "<span class='searchmatch'>\\1</span>", $line );
519 $extract .= "${line}\n";
521 wfProfileOut( "$fname-extract" );
527 * Generates the power search box at bottom of [[Special:Search]]
528 * @param $term string: search term
529 * @return $out string: HTML form
531 function powerSearchBox( $term ) {
535 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
536 $name = str_replace( '_', ' ', $name );
538 $name = wfMsg( 'blanknamespace' );
540 $namespaces .= Xml
::openElement( 'span', array( 'style' => 'white-space: nowrap' ) ) .
541 Xml
::checkLabel( $name, "ns{$ns}", $name, in_array( $ns, $this->namespaces
) ) .
542 Xml
::closeElement( 'span' ) . "\n";
545 $redirect = Xml
::check( 'redirs', $this->searchRedirects
, array( 'value' => '1' ) );
546 $searchField = Xml
::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
547 $searchButton = Xml
::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'fulltext' ) ) . "\n";
549 $out = Xml
::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
550 Xml
::openElement( 'fieldset' ) .
551 Xml
::element( 'legend', array( ), wfMsg( 'powersearch-legend' ) ) .
552 Xml
::hidden( 'title', 'Special:Search' ) .
553 wfMsgExt( 'powersearchtext', array( 'parse', 'replaceafter' ),
554 $namespaces, $redirect, $searchField,
555 '', '', '', '', '', # Dummy placeholders
557 Xml
::closeElement( 'fieldset' ) .
558 Xml
::closeElement( 'form' );
563 function powerSearchFocus() {
564 return "<script type='text/javascript'>" .
565 "document.getElementById('powerSearchText').focus();" .
569 function shortDialog($term) {
572 $out = Xml
::openElement( 'form', array(
575 'action' => $wgScript
577 $out .= Xml
::hidden( 'title', 'Special:Search' );
578 $out .= Xml
::input( 'search', 50, $term ) . ' ';
579 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
580 if( in_array( $ns, $this->namespaces
) ) {
581 $out .= Xml
::hidden( "ns{$ns}", '1' );
584 $out .= Xml
::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
585 $out .= Xml
::closeElement( 'form' );