0a483af52f8a7287d03d46fc2647c72da07d4ab2
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
23 * @ingroup SpecialPage
29 * @param $par String: (default '')
31 function wfSpecialSearch( $par = '' ) {
32 global $wgRequest, $wgUser;
34 $search = str_replace( "\n", " ", $wgRequest->getText( 'search', $par ) );
35 $searchPage = new SpecialSearch( $wgRequest, $wgUser );
36 if( $wgRequest->getVal( 'fulltext' )
37 ||
!is_null( $wgRequest->getVal( 'offset' ))
38 ||
!is_null( $wgRequest->getVal( 'searchx' ))) {
39 $searchPage->showResults( $search, 'search' );
41 $searchPage->goResult( $search );
46 * implements Special:Search - Run text & title search and display the output
47 * @ingroup SpecialPage
52 * Set up basic search parameters from the request and user settings.
53 * Typically you'll pass $wgRequest and $wgUser.
55 * @param WebRequest $request
59 function SpecialSearch( &$request, &$user ) {
60 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, 'searchlimit' );
62 $this->namespaces
= $this->powerSearch( $request );
63 if( empty( $this->namespaces
) ) {
64 $this->namespaces
= SearchEngine
::userNamespaces( $user );
67 $this->searchRedirects
= $request->getcheck( 'redirs' ) ?
true : false;
71 * If an exact title match can be found, jump straight ahead to it.
75 function goResult( $term ) {
79 $this->setupPage( $term );
81 # Try to go to page as entered.
82 $t = Title
::newFromText( $term );
84 # If the string cannot be used to create a title
86 return $this->showResults( $term );
89 # If there's an exact or very near match, jump right there.
90 $t = SearchEngine
::getNearMatch( $term );
91 if( !is_null( $t ) ) {
92 $wgOut->redirect( $t->getFullURL() );
96 # No match, generate an edit URL
97 $t = Title
::newFromText( $term );
98 if( ! is_null( $t ) ) {
99 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
100 # If the feature is enabled, go straight to the edit page
102 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
107 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
108 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
109 $wgOut->addWikiMsg( 'noexactmatch', wfEscapeWikiText( $term ) );
111 $wgOut->addWikiMsg( 'noexactmatch-nocreate', wfEscapeWikiText( $term ) );
114 return $this->showResults( $term );
118 * @param string $term
121 function showResults( $term ) {
122 $fname = 'SpecialSearch::showResults';
123 wfProfileIn( $fname );
124 global $wgOut, $wgUser;
125 $sk = $wgUser->getSkin();
127 $this->setupPage( $term );
129 $wgOut->addWikiMsg( 'searchresulttext' );
131 if( '' === trim( $term ) ) {
132 // Empty query -- straight view of search form
133 $wgOut->setSubtitle( '' );
134 $wgOut->addHTML( $this->powerSearchBox( $term ) );
135 $wgOut->addHTML( $this->powerSearchFocus() );
136 wfProfileOut( $fname );
140 global $wgDisableTextSearch;
141 if ( $wgDisableTextSearch ) {
142 global $wgForwardSearchUrl;
143 if( $wgForwardSearchUrl ) {
144 $url = str_replace( '$1', urlencode( $term ), $wgForwardSearchUrl );
145 $wgOut->redirect( $url );
148 global $wgInputEncoding;
150 Xml
::openElement( 'fieldset' ) .
151 Xml
::element( 'legend', null, wfMsg( 'search-external' ) ) .
152 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
153 wfMsg( 'googlesearch',
154 htmlspecialchars( $term ),
155 htmlspecialchars( $wgInputEncoding ),
156 htmlspecialchars( wfMsg( 'searchbutton' ) )
158 Xml
::closeElement( 'fieldset' )
160 wfProfileOut( $fname );
164 $wgOut->addHTML( $this->shortDialog( $term ) );
166 $search = SearchEngine
::create();
167 $search->setLimitOffset( $this->limit
, $this->offset
);
168 $search->setNamespaces( $this->namespaces
);
169 $search->showRedirects
= $this->searchRedirects
;
170 $rewritten = $search->replacePrefixes($term);
172 $titleMatches = $search->searchTitle( $rewritten );
174 // Sometimes the search engine knows there are too many hits
175 if ($titleMatches instanceof SearchResultTooMany
) {
176 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
177 $wgOut->addHTML( $this->powerSearchBox( $term ) );
178 $wgOut->addHTML( $this->powerSearchFocus() );
179 wfProfileOut( $fname );
183 $textMatches = $search->searchText( $rewritten );
185 // did you mean... suggestions
186 if($textMatches && $textMatches->hasSuggestion()){
187 $st = SpecialPage
::getTitleFor( 'Search' );
188 $stParams = wfArrayToCGI( array(
189 'search' => $textMatches->getSuggestionQuery(),
190 'fulltext' => wfMsg('search')),
191 $this->powerSearchOptions());
193 $suggestLink = '<a href="'.$st->escapeLocalURL($stParams).'">'.
194 $textMatches->getSuggestionSnippet().'</a>';
196 $wgOut->addHTML('<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>');
199 // show number of results
200 $num = ( $titleMatches ?
$titleMatches->numRows() : 0 )
201 +
( $textMatches ?
$textMatches->numRows() : 0);
203 if($titleMatches && !is_null($titleMatches->getTotalHits()))
204 $totalNum +
= $titleMatches->getTotalHits();
205 if($textMatches && !is_null($textMatches->getTotalHits()))
206 $totalNum +
= $textMatches->getTotalHits();
208 if ( $totalNum > 0 ){
209 $top = wfMsgExt('showingresultstotal', array( 'parseinline' ),
210 $this->offset+
1, $this->offset+
$num, $totalNum );
211 } elseif ( $num >= $this->limit
) {
212 $top = wfShowingResults( $this->offset
, $this->limit
);
214 $top = wfShowingResultsNum( $this->offset
, $this->limit
, $num );
216 $wgOut->addHTML( "<p class='mw-search-numberresults'>{$top}</p>\n" );
220 if( $num ||
$this->offset
) {
221 $prevnext = wfViewPrevNext( $this->offset
, $this->limit
,
222 SpecialPage
::getTitleFor( 'Search' ),
224 $this->powerSearchOptions(),
225 array( 'search' => $term ) ),
226 ($num < $this->limit
) );
227 $wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
228 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
230 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
233 if( $titleMatches ) {
234 if( $titleMatches->numRows() ) {
235 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
236 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
238 $titleMatches->free();
242 // output appropriate heading
243 if( $textMatches->numRows() ) {
245 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
246 else // if no title matches the heading is redundant
247 $wgOut->addHTML("<hr/>");
248 } elseif( $num == 0 ) {
249 # Don't show the 'no text matches' if we received title matches
250 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
252 // show interwiki results if any
253 if( $textMatches->hasInterwikiResults() )
254 $wgOut->addHtml( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ));
256 if( $textMatches->numRows() )
257 $wgOut->addHTML( $this->showMatches( $textMatches ) );
259 $textMatches->free();
263 $wgOut->addWikiMsg( 'nonefound' );
265 if( $num ||
$this->offset
) {
266 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
268 $wgOut->addHTML( $this->powerSearchBox( $term ) );
269 wfProfileOut( $fname );
272 #------------------------------------------------------------------
273 # Private methods below this line
278 function setupPage( $term ) {
280 if( !empty( $term ) )
281 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
282 $subtitlemsg = ( Title
::newFromText( $term ) ?
'searchsubtitle' : 'searchsubtitleinvalid' );
283 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
284 $wgOut->setArticleRelated( false );
285 $wgOut->setRobotpolicy( 'noindex,nofollow' );
289 * Extract "power search" namespace settings from the request object,
290 * returning a list of index numbers to search.
292 * @param WebRequest $request
296 function powerSearch( &$request ) {
298 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
299 if( $request->getCheck( 'ns' . $ns ) ) {
307 * Reconstruct the 'power search' options for links
311 function powerSearchOptions() {
313 foreach( $this->namespaces
as $n ) {
316 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
321 * Show whole set of results
323 * @param SearchResultSet $matches
325 function showMatches( &$matches ) {
326 $fname = 'SpecialSearch::showMatches';
327 wfProfileIn( $fname );
330 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
334 $infoLine = $matches->getInfo();
335 if( !is_null($infoLine) )
336 $out .= "\n<!-- {$infoLine} -->\n";
339 $off = $this->offset +
1;
340 $out .= "<ul class='mw-search-results'>\n";
342 while( $result = $matches->next() ) {
343 $out .= $this->showHit( $result, $terms );
347 // convert the whole thing to desired language variant
349 $out = $wgContLang->convert( $out );
350 wfProfileOut( $fname );
355 * Format a single hit result
356 * @param SearchResult $result
357 * @param array $terms terms to highlight
359 function showHit( $result, $terms ) {
360 $fname = 'SpecialSearch::showHit';
361 wfProfileIn( $fname );
362 global $wgUser, $wgContLang, $wgLang;
364 if( $result->isBrokenTitle() ) {
365 wfProfileOut( $fname );
366 return "<!-- Broken link in search result -->\n";
369 $t = $result->getTitle();
370 $sk = $wgUser->getSkin();
372 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
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 wfProfileOut( $fname );
379 return "<li>{$link}</li>\n";
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
385 if( $result->isMissingRevision() ) {
386 wfProfileOut( $fname );
387 return "<!-- missing page " .
388 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
391 // format redirects / relevant sections
392 $redirectTitle = $result->getRedirectTitle();
393 $redirectText = $result->getRedirectSnippet($terms);
394 $sectionTitle = $result->getSectionTitle();
395 $sectionText = $result->getSectionSnippet($terms);
397 if( !is_null($redirectTitle) )
398 $redirect = "<span class='searchalttitle'>"
399 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
402 if( !is_null($sectionTitle) )
403 $section = "<span class='searchalttitle'>"
404 .wfMsg('search-section', $sk->makeKnownLinkObj( $sectionTitle, $sectionText))
407 // format text extract
408 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
411 if( is_null( $result->getScore() ) ) {
412 // Search engine doesn't report scoring info
415 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
416 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
420 // format description
421 $byteSize = $result->getByteSize();
422 $wordCount = $result->getWordCount();
423 $timestamp = $result->getTimestamp();
424 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
425 $sk->formatSize( $byteSize ),
427 $date = $wgLang->timeanddate( $timestamp );
429 // link to related articles if supported
431 if( $result->hasRelated() ){
432 $st = SpecialPage
::getTitleFor( 'Search' );
433 $stParams = wfArrayToCGI( $this->powerSearchOptions(),
434 array('search' => wfMsgForContent('searchrelated').':'.$t->getPrefixedText(),
435 'fulltext' => wfMsg('search') ));
437 $related = ' -- <a href="'.$st->escapeLocalURL($stParams).'">'.
438 wfMsg('search-relatedarticle').'</a>';
441 // Include a thumbnail for media files...
442 if( $t->getNamespace() == NS_IMAGE
) {
443 $img = wfFindFile( $t );
445 $thumb = $img->getThumbnail( 120, 120 );
447 $desc = $img->getShortDesc();
448 wfProfileOut( $fname );
450 // Float doesn't seem to interact well with the bullets.
451 // Table messes up vertical alignment of the bullet, but I'm
452 // not sure what more I can do about that. :(
454 '<table class="searchResultImage">' .
456 '<td width="120" align="center">' .
457 $thumb->toHtml( array( 'desc-link' => true ) ) .
459 '<td valign="top">' .
462 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
471 wfProfileOut( $fname );
472 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
473 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
479 * Show results from other wikis
481 * @param SearchResultSet $matches
483 function showInterwiki( &$matches, $query ) {
484 $fname = 'SpecialSearch::showInterwiki';
485 wfProfileIn( $fname );
488 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
490 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".wfMsg('search-interwiki-caption')."</div>\n";
491 $off = $this->offset +
1;
492 $out .= "<ul start='{$off}' class='mw-search-iwresults'>\n";
494 // work out custom project captions
495 $customCaptions = array();
496 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
497 foreach($customLines as $line){
498 $parts = explode(":",$line,2);
499 if(count($parts) == 2) // validate line
500 $customCaptions[$parts[0]] = $parts[1];
505 while( $result = $matches->next() ) {
506 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
507 $prev = $result->getInterwikiPrefix();
509 // FIXME: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
510 $out .= "</ul></div>\n";
512 // convert the whole thing to desired language variant
514 $out = $wgContLang->convert( $out );
515 wfProfileOut( $fname );
520 * Show single interwiki link
522 * @param SearchResult $result
523 * @param string $lastInterwiki
524 * @param array $terms
525 * @param string $query
526 * @param array $customCaptions iw prefix -> caption
528 function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions){
529 $fname = 'SpecialSearch::showInterwikiHit';
530 wfProfileIn( $fname );
531 global $wgUser, $wgContLang, $wgLang;
533 if( $result->isBrokenTitle() ) {
534 wfProfileOut( $fname );
535 return "<!-- Broken link in search result -->\n";
538 $t = $result->getTitle();
539 $sk = $wgUser->getSkin();
541 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
543 // format redirect if any
544 $redirectTitle = $result->getRedirectTitle();
545 $redirectText = $result->getRedirectSnippet($terms);
547 if( !is_null($redirectTitle) )
548 $redirect = "<span class='searchalttitle'>"
549 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
553 // display project name
554 if(is_null($lastInterwiki) ||
$lastInterwiki != $t->getInterwiki()){
555 if( key_exists($t->getInterwiki(),$customCaptions) )
556 // captions from 'search-interwiki-custom'
557 $caption = $customCaptions[$t->getInterwiki()];
559 // default is to show the hostname of the other wiki which might suck
560 // if there are many wikis on one hostname
561 $parsed = parse_url($t->getFullURL());
562 $caption = wfMsg('search-interwiki-default', $parsed['host']);
564 // "more results" link (special page stuff could be localized, but we might not know target lang)
565 $searchTitle = Title
::newFromText($t->getInterwiki().":Special:Search");
566 $searchLink = $sk->makeKnownLinkObj( $searchTitle, wfMsg('search-interwiki-more'),
567 wfArrayToCGI(array('search' => $query, 'fulltext' => 'Search')));
568 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>{$searchLink}</span>{$caption}</div>\n<ul>";
571 $out .= "<li>{$link} {$redirect}</li>\n";
572 wfProfileOut( $fname );
578 * Generates the power search box at bottom of [[Special:Search]]
579 * @param $term string: search term
580 * @return $out string: HTML form
582 function powerSearchBox( $term ) {
586 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
587 $name = str_replace( '_', ' ', $name );
589 $name = wfMsg( 'blanknamespace' );
591 $namespaces .= Xml
::openElement( 'span', array( 'style' => 'white-space: nowrap' ) ) .
592 Xml
::checkLabel( $name, "ns{$ns}", "mw-search-ns{$ns}", in_array( $ns, $this->namespaces
) ) .
593 Xml
::closeElement( 'span' ) . "\n";
596 $redirect = Xml
::check( 'redirs', $this->searchRedirects
, array( 'value' => '1', 'id' => 'redirs' ) );
597 $redirectLabel = Xml
::label( wfMsg( 'powersearch-redir' ), 'redirs' );
598 $searchField = Xml
::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
599 $searchButton = Xml
::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'fulltext' ) ) . "\n";
601 $out = Xml
::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
602 Xml
::fieldset( wfMsg( 'powersearch-legend' ),
603 Xml
::hidden( 'title', 'Special:Search' ) .
605 wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) .
610 $redirect . " " . $redirectLabel .
612 wfMsgExt( 'powersearch-field', array( 'parseinline' ) ) .
622 function powerSearchFocus() {
623 global $wgJsMimeType;
624 return "<script type=\"$wgJsMimeType\">" .
625 "hookEvent(\"load\", function(){" .
626 "document.getElementById('powerSearchText').focus();" .
631 function shortDialog($term) {
634 $out = Xml
::openElement( 'form', array(
637 'action' => $wgScript
639 $out .= Xml
::hidden( 'title', 'Special:Search' );
640 $out .= Xml
::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . ' ';
641 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
642 if( in_array( $ns, $this->namespaces
) ) {
643 $out .= Xml
::hidden( "ns{$ns}", '1' );
646 $out .= Xml
::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
647 $out .= Xml
::closeElement( 'form' );