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 = $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 if( $request->getCheck( 'searchx' ) ) {
62 $this->namespaces
= $this->powerSearch( $request );
64 $this->namespaces
= $this->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' ) );
106 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
107 $wgOut->addWikiMsg( 'noexactmatch', wfEscapeWikiText( $term ) );
109 $wgOut->addWikiMsg( 'noexactmatch-nocreate', wfEscapeWikiText( $term ) );
112 return $this->showResults( $term );
116 * @param string $term
119 function showResults( $term ) {
120 $fname = 'SpecialSearch::showResults';
121 wfProfileIn( $fname );
123 $this->setupPage( $term );
126 $wgOut->addWikiMsg( 'searchresulttext' );
128 if( '' === trim( $term ) ) {
129 // Empty query -- straight view of search form
130 $wgOut->setSubtitle( '' );
131 $wgOut->addHTML( $this->powerSearchBox( $term ) );
132 $wgOut->addHTML( $this->powerSearchFocus() );
133 wfProfileOut( $fname );
137 global $wgDisableTextSearch;
138 if ( $wgDisableTextSearch ) {
139 global $wgForwardSearchUrl;
140 if( $wgForwardSearchUrl ) {
141 $url = str_replace( '$1', urlencode( $term ), $wgForwardSearchUrl );
142 $wgOut->redirect( $url );
145 global $wgInputEncoding;
146 $wgOut->addHTML( wfMsg( 'searchdisabled' ) );
148 wfMsg( 'googlesearch',
149 htmlspecialchars( $term ),
150 htmlspecialchars( $wgInputEncoding ),
151 htmlspecialchars( wfMsg( 'searchbutton' ) )
154 wfProfileOut( $fname );
158 $wgOut->addHTML( $this->shortDialog( $term ) );
160 $search = SearchEngine
::create();
161 $search->setLimitOffset( $this->limit
, $this->offset
);
162 $search->setNamespaces( $this->namespaces
);
163 $search->showRedirects
= $this->searchRedirects
;
164 $titleMatches = $search->searchTitle( $term );
166 // Sometimes the search engine knows there are too many hits
167 if ($titleMatches instanceof SearchResultTooMany
) {
168 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
169 $wgOut->addHTML( $this->powerSearchBox( $term ) );
170 $wgOut->addHTML( $this->powerSearchFocus() );
171 wfProfileOut( $fname );
174 $textMatches = $search->searchText( $term );
176 $num = ( $titleMatches ?
$titleMatches->numRows() : 0 )
177 +
( $textMatches ?
$textMatches->numRows() : 0);
179 if ( $num >= $this->limit
) {
180 $top = wfShowingResults( $this->offset
, $this->limit
);
182 $top = wfShowingResultsNum( $this->offset
, $this->limit
, $num );
184 $wgOut->addHTML( "<p>{$top}</p>\n" );
187 if( $num ||
$this->offset
) {
188 $prevnext = wfViewPrevNext( $this->offset
, $this->limit
,
189 SpecialPage
::getTitleFor( 'Search' ),
191 $this->powerSearchOptions(),
192 array( 'search' => $term ) ),
193 ($num < $this->limit
) );
194 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
197 if( $titleMatches ) {
198 if( $titleMatches->numRows() ) {
199 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
200 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
202 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
204 $titleMatches->free();
208 if( $textMatches->numRows() ) {
209 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
210 $wgOut->addHTML( $this->showMatches( $textMatches ) );
211 } elseif( $num == 0 ) {
212 # Don't show the 'no text matches' if we received title matches
213 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
215 $textMatches->free();
219 $wgOut->addWikiMsg( 'nonefound' );
221 if( $num ||
$this->offset
) {
222 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
224 $wgOut->addHTML( $this->powerSearchBox( $term ) );
225 wfProfileOut( $fname );
228 #------------------------------------------------------------------
229 # Private methods below this line
234 function setupPage( $term ) {
236 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
237 $subtitlemsg = ( Title
::newFromText($term) ?
'searchsubtitle' : 'searchsubtitleinvalid' );
238 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
239 $wgOut->setArticleRelated( false );
240 $wgOut->setRobotpolicy( 'noindex,nofollow' );
244 * Extract default namespaces to search from the given user's
245 * settings, returning a list of index numbers.
251 function userNamespaces( &$user ) {
253 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
254 if( $user->getOption( 'searchNs' . $ns ) ) {
262 * Extract "power search" namespace settings from the request object,
263 * returning a list of index numbers to search.
265 * @param WebRequest $request
269 function powerSearch( &$request ) {
271 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
272 if( $request->getCheck( 'ns' . $ns ) ) {
280 * Reconstruct the 'power search' options for links
284 function powerSearchOptions() {
286 foreach( $this->namespaces
as $n ) {
289 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
297 * @param SearchResultSet $matches
298 * @param string $terms partial regexp for highlighting terms
300 function showMatches( &$matches ) {
301 $fname = 'SpecialSearch::showMatches';
302 wfProfileIn( $fname );
305 $tm = $wgContLang->convertForSearchResult( $matches->termMatches() );
306 $terms = implode( '|', $tm );
308 $off = $this->offset +
1;
309 $out = "<ul start='{$off}' class='mw-search-results'>\n";
311 while( $result = $matches->next() ) {
312 $out .= $this->showHit( $result, $terms );
316 // convert the whole thing to desired language variant
318 $out = $wgContLang->convert( $out );
319 wfProfileOut( $fname );
324 * Format a single hit result
325 * @param SearchResult $result
326 * @param string $terms partial regexp for highlighting terms
328 function showHit( $result, $terms ) {
329 $fname = 'SpecialSearch::showHit';
330 wfProfileIn( $fname );
331 global $wgUser, $wgContLang, $wgLang;
333 $t = $result->getTitle();
334 if( is_null( $t ) ) {
335 wfProfileOut( $fname );
336 return "<!-- Broken link in search result -->\n";
338 $sk = $wgUser->getSkin();
340 //$contextlines = $wgUser->getOption( 'contextlines', 5 );
341 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
342 $contextchars = $wgUser->getOption( 'contextchars', 50 );
344 $link = $sk->makeKnownLinkObj( $t );
346 //If page content is not readable, just return the title.
347 //This is not quite safe, but better than showing excerpts from non-readable pages
348 //Note that hiding the entry entirely would screw up paging.
349 if (!$t->userCanRead()) {
350 return "<li>{$link}</li>\n";
353 $revision = Revision
::newFromTitle( $t );
354 // If the page doesn't *exist*... our search index is out of date.
355 // The least confusing at this point is to drop the result.
356 // You may get less results, but... oh well. :P
358 return "<!-- missing page " .
359 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
362 $text = $revision->getText();
363 $size = wfMsgHtml( 'search-result-size',
364 $sk->formatSize( strlen( $text ) ),
365 str_word_count( $text ) );
366 $date = $wgLang->timeanddate( $revision->getTimestamp() );
368 if( is_null( $result->getScore() ) ) {
369 // Search engine doesn't report scoring info
372 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
373 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
377 $extract = $this->extractText( $text, $terms, $contextlines, $contextchars );
379 // Include a thumbnail for media files...
380 if( $t->getNamespace() == NS_IMAGE
) {
381 $img = wfFindFile( $t );
383 $thumb = $img->getThumbnail( 120, 120 );
385 $desc = $img->getShortDesc();
386 wfProfileOut( $fname );
388 // Float doesn't seem to interact well with the bullets.
389 // Table messes up vertical alignment of the bullet, but I'm
390 // not sure what more I can do about that. :(
392 '<table class="searchResultImage">' .
394 '<td width="120" align="center">' .
395 $thumb->toHtml( array( 'desc-link' => true ) ) .
397 '<td valign="top">' .
400 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}</div>" .
409 wfProfileOut( $fname );
410 return "<li>{$link} {$extract}\n" .
411 "<div class='mw-search-result-data'>{$score}{$size} - {$date}</div>" .
416 private function extractText( $text, $terms, $contextlines, $contextchars ) {
417 global $wgLang, $wgContLang;
420 $lines = explode( "\n", $text );
422 $max = intval( $contextchars ) +
1;
423 $pat1 = "/(.*)($terms)(.{0,$max})/i";
428 wfProfileIn( "$fname-extract" );
429 foreach ( $lines as $line ) {
430 if ( 0 == $contextlines ) {
435 if ( ! preg_match( $pat1, $line, $m ) ) {
439 $pre = $wgContLang->truncate( $m[1], -$contextchars, '...' );
441 if ( count( $m ) < 3 ) {
444 $post = $wgContLang->truncate( $m[3], $contextchars, '...' );
449 $line = htmlspecialchars( $pre . $found . $post );
450 $pat2 = '/(' . $terms . ")/i";
451 $line = preg_replace( $pat2,
452 "<span class='searchmatch'>\\1</span>", $line );
454 $extract .= "<br /><small>{$line}</small>\n";
456 wfProfileOut( "$fname-extract" );
461 function powerSearchBox( $term ) {
465 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
466 $name = str_replace( '_', ' ', $name );
468 $name = wfMsg( 'blanknamespace' );
470 $encName = htmlspecialchars( $name );
471 $namespaces .= '<label>' .
472 Xml
::check( "ns{$ns}", in_array( $ns, $this->namespaces
),
473 array( 'value' => '1' ) ) .
474 "{$encName}</label> ";
477 $redirect = Xml
::check( 'redirs', $this->searchRedirects
,
478 array( 'value' => '1' ) );
480 $searchField = Xml
::input( 'search', 50, $term, array(
481 'type' => 'text', 'id' => 'powerSearchText' ) );
483 $searchButton = Xml
::element( 'input', array(
486 'value' => wfMsg('powersearch')
489 $out = Xml
::openElement( 'form', array(
490 'id' => 'powersearch',
492 'action' => $wgScript ) );
493 $out .= Xml
::openElement( 'fieldset' );
494 $out .= Xml
::element( 'legend', array( ), wfMsg( 'powersearch' ));
495 $out .= Xml
::hidden( 'title', 'Special:Search' );
496 $out .= wfMsgExt( 'powersearchtext', array( 'parse', 'replaceafter' ),
497 $namespaces, $redirect, $searchField,
498 '', '', '', '', '', # Dummy placeholders
500 $out .= Xml
::closeElement( 'fieldset' );
501 $out .= Xml
::closeElement( 'form' );
506 function powerSearchFocus() {
507 return "<script type='text/javascript'>" .
508 "document.getElementById('powerSearchText').focus();" .
512 function shortDialog($term) {
515 $out = Xml
::openElement( 'form', array(
518 'action' => $wgScript
520 $out .= Xml
::hidden( 'title', 'Special:Search' );
521 $out .= Xml
::input( 'search', 50, $term ) . ' ';
522 $out .= Xml
::submitButton( wfMsg( 'searchbutton' ) );
523 $out .= Xml
::closeElement( 'form' );