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 $wgOut->addHTML( '<div id="searchHeader">' );
178 $num = ( $titleMatches ?
$titleMatches->numRows() : 0 )
179 +
( $textMatches ?
$textMatches->numRows() : 0);
181 if ( $num >= $this->limit
) {
182 $top = wfShowingResults( $this->offset
, $this->limit
);
184 $top = wfShowingResultsNum( $this->offset
, $this->limit
, $num );
186 $wgOut->addHTML( "<p>{$top}</p>\n" );
189 if( $num ||
$this->offset
) {
190 $prevnext = wfViewPrevNext( $this->offset
, $this->limit
,
191 SpecialPage
::getTitleFor( 'Search' ),
193 $this->powerSearchOptions(),
194 array( 'search' => $term ) ),
195 ($num < $this->limit
) );
196 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
199 $wgOut->addHTML( "</div>\n" );
201 if( $titleMatches ) {
202 if( $titleMatches->numRows() ) {
203 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
204 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
206 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
208 $titleMatches->free();
212 if( $textMatches->numRows() ) {
213 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
214 $wgOut->addHTML( $this->showMatches( $textMatches ) );
215 } elseif( $num == 0 ) {
216 # Don't show the 'no text matches' if we received title matches
217 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
219 $textMatches->free();
223 $wgOut->addWikiMsg( 'nonefound' );
225 if( $num ||
$this->offset
) {
226 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
228 $wgOut->addHTML( $this->powerSearchBox( $term ) );
229 wfProfileOut( $fname );
232 #------------------------------------------------------------------
233 # Private methods below this line
238 function setupPage( $term ) {
240 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
241 $subtitlemsg = ( Title
::newFromText($term) ?
'searchsubtitle' : 'searchsubtitleinvalid' );
242 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
243 $wgOut->setArticleRelated( false );
244 $wgOut->setRobotpolicy( 'noindex,nofollow' );
248 * Extract default namespaces to search from the given user's
249 * settings, returning a list of index numbers.
255 function userNamespaces( &$user ) {
257 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
258 if( $user->getOption( 'searchNs' . $ns ) ) {
266 * Extract "power search" namespace settings from the request object,
267 * returning a list of index numbers to search.
269 * @param WebRequest $request
273 function powerSearch( &$request ) {
275 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
276 if( $request->getCheck( 'ns' . $ns ) ) {
284 * Reconstruct the 'power search' options for links
288 function powerSearchOptions() {
290 foreach( $this->namespaces
as $n ) {
293 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
301 * @param SearchResultSet $matches
302 * @param string $terms partial regexp for highlighting terms
304 function showMatches( &$matches ) {
305 $fname = 'SpecialSearch::showMatches';
306 wfProfileIn( $fname );
309 $tm = $wgContLang->convertForSearchResult( $matches->termMatches() );
310 $terms = implode( '|', $tm );
312 $off = $this->offset +
1;
313 $out = "<ul start='{$off}' class='mw-search-results'>\n";
315 while( $result = $matches->next() ) {
316 $out .= $this->showHit( $result, $terms );
320 // convert the whole thing to desired language variant
322 $out = $wgContLang->convert( $out );
323 wfProfileOut( $fname );
328 * Format a single hit result
329 * @param SearchResult $result
330 * @param string $terms partial regexp for highlighting terms
332 function showHit( $result, $terms ) {
333 $fname = 'SpecialSearch::showHit';
334 wfProfileIn( $fname );
335 global $wgUser, $wgContLang, $wgLang;
337 $t = $result->getTitle();
338 if( is_null( $t ) ) {
339 wfProfileOut( $fname );
340 return "<!-- Broken link in search result -->\n";
342 $sk = $wgUser->getSkin();
344 //$contextlines = $wgUser->getOption( 'contextlines', 5 );
345 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
346 $contextchars = $wgUser->getOption( 'contextchars', 50 );
348 $link = $sk->makeKnownLinkObj( $t );
350 //If page content is not readable, just return the title.
351 //This is not quite safe, but better than showing excerpts from non-readable pages
352 //Note that hiding the entry entirely would screw up paging.
353 if (!$t->userCanRead()) {
354 return "<li>{$link}</li>\n";
357 $revision = Revision
::newFromTitle( $t );
358 // If the page doesn't *exist*... our search index is out of date.
359 // The least confusing at this point is to drop the result.
360 // You may get less results, but... oh well. :P
362 return "<!-- missing page " .
363 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
366 $text = $revision->getText();
367 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
368 $sk->formatSize( strlen( $text ) ),
369 str_word_count( $text ) );
370 $date = $wgLang->timeanddate( $revision->getTimestamp() );
372 if( is_null( $result->getScore() ) ) {
373 // Search engine doesn't report scoring info
376 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
377 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
381 $extract = $this->extractText( $text, $terms, $contextlines, $contextchars );
383 // Include a thumbnail for media files...
384 if( $t->getNamespace() == NS_IMAGE
) {
385 $img = wfFindFile( $t );
387 $thumb = $img->getThumbnail( 120, 120 );
389 $desc = $img->getShortDesc();
390 wfProfileOut( $fname );
392 // Float doesn't seem to interact well with the bullets.
393 // Table messes up vertical alignment of the bullet, but I'm
394 // not sure what more I can do about that. :(
396 '<table class="searchResultImage">' .
398 '<td width="120" align="center">' .
399 $thumb->toHtml( array( 'desc-link' => true ) ) .
401 '<td valign="top">' .
404 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}</div>" .
413 wfProfileOut( $fname );
414 return "<li>{$link} {$extract}\n" .
415 "<div class='mw-search-result-data'>{$score}{$size} - {$date}</div>" .
420 private function extractText( $text, $terms, $contextlines, $contextchars ) {
421 global $wgLang, $wgContLang;
424 $lines = explode( "\n", $text );
426 $max = intval( $contextchars ) +
1;
427 $pat1 = "/(.*)($terms)(.{0,$max})/i";
432 wfProfileIn( "$fname-extract" );
433 foreach ( $lines as $line ) {
434 if ( 0 == $contextlines ) {
439 if ( ! preg_match( $pat1, $line, $m ) ) {
443 $pre = $wgContLang->truncate( $m[1], -$contextchars, '...' );
445 if ( count( $m ) < 3 ) {
448 $post = $wgContLang->truncate( $m[3], $contextchars, '...' );
453 $line = htmlspecialchars( $pre . $found . $post );
454 $pat2 = '/(' . $terms . ")/i";
455 $line = preg_replace( $pat2,
456 "<span class='searchmatch'>\\1</span>", $line );
458 $extract .= "<br /><small>{$line}</small>\n";
460 wfProfileOut( "$fname-extract" );
466 * Generates the power search box at bottom of [[Special:Search]]
467 * @param $term string: search term
468 * @return $out string: HTML form
470 function powerSearchBox( $term ) {
474 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
475 $name = str_replace( '_', ' ', $name );
477 $name = wfMsg( 'blanknamespace' );
479 $namespaces .= Xml
::openElement( 'span', array( 'style' => 'white-space: nowrap' ) ) .
480 Xml
::checkLabel( $name, "ns{$ns}", $name, in_array( $ns, $this->namespaces
) ) .
481 Xml
::closeElement( 'span' ) . "\n";
484 $redirect = Xml
::check( 'redirs', $this->searchRedirects
, array( 'value' => '1' ) );
485 $searchField = Xml
::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
486 $searchButton = Xml
::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'searchx' ) ) . "\n";
488 $out = Xml
::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
489 Xml
::openElement( 'fieldset' ) .
490 Xml
::element( 'legend', array( ), wfMsg( 'searchbutton' ) ) .
491 Xml
::hidden( 'title', 'Special:Search' ) .
492 wfMsgExt( 'powersearchtext', array( 'parse', 'replaceafter' ),
493 $namespaces, $redirect, $searchField,
494 '', '', '', '', '', # Dummy placeholders
496 Xml
::closeElement( 'fieldset' ) .
497 Xml
::closeElement( 'form' );
502 function powerSearchFocus() {
503 return "<script type='text/javascript'>" .
504 "document.getElementById('powerSearchText').focus();" .
508 function shortDialog($term) {
511 $form = Xml
::hidden( 'title', 'Special:Search' );
512 $form .= Xml
::input( 'search', 50, $term,
513 array( 'id' => 'searchBox' ) ).' ';
514 $form .= Xml
::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
516 $out = Xml
::openElement( 'form', array(
519 'action' => $wgScript
521 $out .= wfMsgExt( 'searchtext', array( 'parse', 'replaceafter' ), $form );
522 $out .= Xml
::closeElement( 'form' );