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 $wgSearchForwardUrl;
143 if( $wgSearchForwardUrl ) {
144 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
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 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term) ) );
284 $subtitlemsg = ( Title
::newFromText( $term ) ?
'searchsubtitle' : 'searchsubtitleinvalid' );
285 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
286 $wgOut->setArticleRelated( false );
287 $wgOut->setRobotPolicy( 'noindex,nofollow' );
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;
323 * Show whole set of results
325 * @param SearchResultSet $matches
327 function showMatches( &$matches ) {
328 $fname = 'SpecialSearch::showMatches';
329 wfProfileIn( $fname );
332 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
336 $infoLine = $matches->getInfo();
337 if( !is_null($infoLine) )
338 $out .= "\n<!-- {$infoLine} -->\n";
341 $off = $this->offset +
1;
342 $out .= "<ul class='mw-search-results'>\n";
344 while( $result = $matches->next() ) {
345 $out .= $this->showHit( $result, $terms );
349 // convert the whole thing to desired language variant
351 $out = $wgContLang->convert( $out );
352 wfProfileOut( $fname );
357 * Format a single hit result
358 * @param SearchResult $result
359 * @param array $terms terms to highlight
361 function showHit( $result, $terms ) {
362 $fname = 'SpecialSearch::showHit';
363 wfProfileIn( $fname );
364 global $wgUser, $wgContLang, $wgLang;
366 if( $result->isBrokenTitle() ) {
367 wfProfileOut( $fname );
368 return "<!-- Broken link in search result -->\n";
371 $t = $result->getTitle();
372 $sk = $wgUser->getSkin();
374 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
376 //If page content is not readable, just return the title.
377 //This is not quite safe, but better than showing excerpts from non-readable pages
378 //Note that hiding the entry entirely would screw up paging.
379 if (!$t->userCanRead()) {
380 wfProfileOut( $fname );
381 return "<li>{$link}</li>\n";
384 // If the page doesn't *exist*... our search index is out of date.
385 // The least confusing at this point is to drop the result.
386 // You may get less results, but... oh well. :P
387 if( $result->isMissingRevision() ) {
388 wfProfileOut( $fname );
389 return "<!-- missing page " .
390 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
393 // format redirects / relevant sections
394 $redirectTitle = $result->getRedirectTitle();
395 $redirectText = $result->getRedirectSnippet($terms);
396 $sectionTitle = $result->getSectionTitle();
397 $sectionText = $result->getSectionSnippet($terms);
399 if( !is_null($redirectTitle) )
400 $redirect = "<span class='searchalttitle'>"
401 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
404 if( !is_null($sectionTitle) )
405 $section = "<span class='searchalttitle'>"
406 .wfMsg('search-section', $sk->makeKnownLinkObj( $sectionTitle, $sectionText))
409 // format text extract
410 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
413 if( is_null( $result->getScore() ) ) {
414 // Search engine doesn't report scoring info
417 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
418 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
422 // format description
423 $byteSize = $result->getByteSize();
424 $wordCount = $result->getWordCount();
425 $timestamp = $result->getTimestamp();
426 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
427 $sk->formatSize( $byteSize ),
429 $date = $wgLang->timeanddate( $timestamp );
431 // link to related articles if supported
433 if( $result->hasRelated() ){
434 $st = SpecialPage
::getTitleFor( 'Search' );
435 $stParams = wfArrayToCGI( $this->powerSearchOptions(),
436 array('search' => wfMsgForContent('searchrelated').':'.$t->getPrefixedText(),
437 'fulltext' => wfMsg('search') ));
439 $related = ' -- <a href="'.$st->escapeLocalURL($stParams).'">'.
440 wfMsg('search-relatedarticle').'</a>';
443 // Include a thumbnail for media files...
444 if( $t->getNamespace() == NS_IMAGE
) {
445 $img = wfFindFile( $t );
447 $thumb = $img->getThumbnail( 120, 120 );
449 $desc = $img->getShortDesc();
450 wfProfileOut( $fname );
452 // Float doesn't seem to interact well with the bullets.
453 // Table messes up vertical alignment of the bullet, but I'm
454 // not sure what more I can do about that. :(
456 '<table class="searchResultImage">' .
458 '<td width="120" align="center">' .
459 $thumb->toHtml( array( 'desc-link' => true ) ) .
461 '<td valign="top">' .
464 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
473 wfProfileOut( $fname );
474 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
475 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
481 * Show results from other wikis
483 * @param SearchResultSet $matches
485 function showInterwiki( &$matches, $query ) {
486 $fname = 'SpecialSearch::showInterwiki';
487 wfProfileIn( $fname );
490 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
492 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".wfMsg('search-interwiki-caption')."</div>\n";
493 $off = $this->offset +
1;
494 $out .= "<ul start='{$off}' class='mw-search-iwresults'>\n";
496 // work out custom project captions
497 $customCaptions = array();
498 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
499 foreach($customLines as $line){
500 $parts = explode(":",$line,2);
501 if(count($parts) == 2) // validate line
502 $customCaptions[$parts[0]] = $parts[1];
507 while( $result = $matches->next() ) {
508 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
509 $prev = $result->getInterwikiPrefix();
511 // FIXME: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
512 $out .= "</ul></div>\n";
514 // convert the whole thing to desired language variant
516 $out = $wgContLang->convert( $out );
517 wfProfileOut( $fname );
522 * Show single interwiki link
524 * @param SearchResult $result
525 * @param string $lastInterwiki
526 * @param array $terms
527 * @param string $query
528 * @param array $customCaptions iw prefix -> caption
530 function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions){
531 $fname = 'SpecialSearch::showInterwikiHit';
532 wfProfileIn( $fname );
533 global $wgUser, $wgContLang, $wgLang;
535 if( $result->isBrokenTitle() ) {
536 wfProfileOut( $fname );
537 return "<!-- Broken link in search result -->\n";
540 $t = $result->getTitle();
541 $sk = $wgUser->getSkin();
543 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
545 // format redirect if any
546 $redirectTitle = $result->getRedirectTitle();
547 $redirectText = $result->getRedirectSnippet($terms);
549 if( !is_null($redirectTitle) )
550 $redirect = "<span class='searchalttitle'>"
551 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
555 // display project name
556 if(is_null($lastInterwiki) ||
$lastInterwiki != $t->getInterwiki()){
557 if( key_exists($t->getInterwiki(),$customCaptions) )
558 // captions from 'search-interwiki-custom'
559 $caption = $customCaptions[$t->getInterwiki()];
561 // default is to show the hostname of the other wiki which might suck
562 // if there are many wikis on one hostname
563 $parsed = parse_url($t->getFullURL());
564 $caption = wfMsg('search-interwiki-default', $parsed['host']);
566 // "more results" link (special page stuff could be localized, but we might not know target lang)
567 $searchTitle = Title
::newFromText($t->getInterwiki().":Special:Search");
568 $searchLink = $sk->makeKnownLinkObj( $searchTitle, wfMsg('search-interwiki-more'),
569 wfArrayToCGI(array('search' => $query, 'fulltext' => 'Search')));
570 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>{$searchLink}</span>{$caption}</div>\n<ul>";
573 $out .= "<li>{$link} {$redirect}</li>\n";
574 wfProfileOut( $fname );
580 * Generates the power search box at bottom of [[Special:Search]]
581 * @param $term string: search term
582 * @return $out string: HTML form
584 function powerSearchBox( $term ) {
588 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
589 $name = str_replace( '_', ' ', $name );
591 $name = wfMsg( 'blanknamespace' );
593 $namespaces .= Xml
::openElement( 'span', array( 'style' => 'white-space: nowrap' ) ) .
594 Xml
::checkLabel( $name, "ns{$ns}", "mw-search-ns{$ns}", in_array( $ns, $this->namespaces
) ) .
595 Xml
::closeElement( 'span' ) . "\n";
598 $redirect = Xml
::check( 'redirs', $this->searchRedirects
, array( 'value' => '1', 'id' => 'redirs' ) );
599 $redirectLabel = Xml
::label( wfMsg( 'powersearch-redir' ), 'redirs' );
600 $searchField = Xml
::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
601 $searchButton = Xml
::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'fulltext' ) ) . "\n";
602 $searchTitle = SpecialPage
::getTitleFor( 'Search' );
604 $out = Xml
::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
605 Xml
::fieldset( wfMsg( 'powersearch-legend' ),
606 Xml
::hidden( 'title', $searchTitle->getPrefixedText() ) .
608 wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) .
613 $redirect . " " . $redirectLabel .
615 wfMsgExt( 'powersearch-field', array( 'parseinline' ) ) .
625 function powerSearchFocus() {
626 global $wgJsMimeType;
627 return "<script type=\"$wgJsMimeType\">" .
628 "hookEvent(\"load\", function(){" .
629 "document.getElementById('powerSearchText').focus();" .
634 function shortDialog($term) {
637 $out = Xml
::openElement( 'form', array(
640 'action' => $wgScript
642 $searchTitle = SpecialPage
::getTitleFor( 'Search' );
643 $out .= Xml
::hidden( 'title', $searchTitle->getPrefixedText() );
644 $out .= Xml
::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . ' ';
645 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
646 if( in_array( $ns, $this->namespaces
) ) {
647 $out .= Xml
::hidden( "ns{$ns}", '1' );
650 $out .= Xml
::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
651 $out .= Xml
::closeElement( 'form' );