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;
145 $wgOut->addHTML( wfMsg( 'searchdisabled' ) );
147 wfMsg( 'googlesearch',
148 htmlspecialchars( $term ),
149 htmlspecialchars( $wgInputEncoding ),
150 htmlspecialchars( wfMsg( 'searchbutton' ) )
153 wfProfileOut( $fname );
157 $wgOut->addHTML( $this->shortDialog( $term ) );
159 $search = SearchEngine
::create();
160 $search->setLimitOffset( $this->limit
, $this->offset
);
161 $search->setNamespaces( $this->namespaces
);
162 $search->showRedirects
= $this->searchRedirects
;
163 $titleMatches = $search->searchTitle( $term );
165 // Sometimes the search engine knows there are too many hits
166 if ($titleMatches instanceof SearchResultTooMany
) {
167 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
168 $wgOut->addHTML( $this->powerSearchBox( $term ) );
169 $wgOut->addHTML( $this->powerSearchFocus() );
170 wfProfileOut( $fname );
173 $textMatches = $search->searchText( $term );
175 $num = ( $titleMatches ?
$titleMatches->numRows() : 0 )
176 +
( $textMatches ?
$textMatches->numRows() : 0);
178 if ( $num >= $this->limit
) {
179 $top = wfShowingResults( $this->offset
, $this->limit
);
181 $top = wfShowingResultsNum( $this->offset
, $this->limit
, $num );
183 $wgOut->addHTML( "<p>{$top}</p>\n" );
186 if( $num ||
$this->offset
) {
187 $prevnext = wfViewPrevNext( $this->offset
, $this->limit
,
188 SpecialPage
::getTitleFor( 'Search' ),
190 $this->powerSearchOptions(),
191 array( 'search' => $term ) ),
192 ($num < $this->limit
) );
193 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
196 if( $titleMatches ) {
197 if( $titleMatches->numRows() ) {
198 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
199 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
201 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
203 $titleMatches->free();
207 if( $textMatches->numRows() ) {
208 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
209 $wgOut->addHTML( $this->showMatches( $textMatches ) );
210 } elseif( $num == 0 ) {
211 # Don't show the 'no text matches' if we received title matches
212 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
214 $textMatches->free();
218 $wgOut->addWikiMsg( 'nonefound' );
220 if( $num ||
$this->offset
) {
221 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
223 $wgOut->addHTML( $this->powerSearchBox( $term ) );
224 wfProfileOut( $fname );
227 #------------------------------------------------------------------
228 # Private methods below this line
233 function setupPage( $term ) {
235 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
236 $subtitlemsg = ( Title
::newFromText($term) ?
'searchsubtitle' : 'searchsubtitleinvalid' );
237 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
238 $wgOut->setArticleRelated( false );
239 $wgOut->setRobotpolicy( 'noindex,nofollow' );
243 * Extract default namespaces to search from the given user's
244 * settings, returning a list of index numbers.
250 function userNamespaces( &$user ) {
252 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
253 if( $user->getOption( 'searchNs' . $ns ) ) {
261 * Extract "power search" namespace settings from the request object,
262 * returning a list of index numbers to search.
264 * @param WebRequest $request
268 function powerSearch( &$request ) {
270 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
271 if( $request->getCheck( 'ns' . $ns ) ) {
279 * Reconstruct the 'power search' options for links
283 function powerSearchOptions() {
285 foreach( $this->namespaces
as $n ) {
288 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
295 * @param SearchResultSet $matches
296 * @param string $terms partial regexp for highlighting terms
298 function showMatches( &$matches ) {
299 $fname = 'SpecialSearch::showMatches';
300 wfProfileIn( $fname );
303 $tm = $wgContLang->convertForSearchResult( $matches->termMatches() );
304 $terms = implode( '|', $tm );
306 $off = $this->offset +
1;
307 $out = "<ul start='{$off}' class='mw-search-results'>\n";
309 while( $result = $matches->next() ) {
310 $out .= $this->showHit( $result, $terms );
314 // convert the whole thing to desired language variant
316 $out = $wgContLang->convert( $out );
317 wfProfileOut( $fname );
322 * Format a single hit result
323 * @param SearchResult $result
324 * @param string $terms partial regexp for highlighting terms
326 function showHit( $result, $terms ) {
327 $fname = 'SpecialSearch::showHit';
328 wfProfileIn( $fname );
329 global $wgUser, $wgContLang, $wgLang;
331 $t = $result->getTitle();
332 if( is_null( $t ) ) {
333 wfProfileOut( $fname );
334 return "<!-- Broken link in search result -->\n";
336 $sk = $wgUser->getSkin();
338 //$contextlines = $wgUser->getOption( 'contextlines', 5 );
339 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
340 $contextchars = $wgUser->getOption( 'contextchars', 50 );
342 $link = $sk->makeKnownLinkObj( $t );
344 //If page content is not readable, just return the title.
345 //This is not quite safe, but better than showing excerpts from non-readable pages
346 //Note that hiding the entry entirely would screw up paging.
347 if (!$t->userCanRead()) {
348 return "<li>{$link}</li>\n";
351 $revision = Revision
::newFromTitle( $t );
352 // If the page doesn't *exist*... our search index is out of date.
353 // The least confusing at this point is to drop the result.
354 // You may get less results, but... oh well. :P
356 return "<!-- missing page " .
357 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
360 $text = $revision->getText();
361 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
362 $sk->formatSize( strlen( $text ) ),
363 str_word_count( $text ) );
364 $date = $wgLang->timeanddate( $revision->getTimestamp() );
366 if( is_null( $result->getScore() ) ) {
367 // Search engine doesn't report scoring info
370 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
371 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
375 $extract = $this->extractText( $text, $terms, $contextlines, $contextchars );
377 // Include a thumbnail for media files...
378 if( $t->getNamespace() == NS_IMAGE
) {
379 $img = wfFindFile( $t );
381 $thumb = $img->getThumbnail( 120, 120 );
383 $desc = $img->getShortDesc();
384 wfProfileOut( $fname );
386 // Float doesn't seem to interact well with the bullets.
387 // Table messes up vertical alignment of the bullet, but I'm
388 // not sure what more I can do about that. :(
390 '<table class="searchResultImage">' .
392 '<td width="120" align="center">' .
393 $thumb->toHtml( array( 'desc-link' => true ) ) .
395 '<td valign="top">' .
398 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}</div>" .
407 wfProfileOut( $fname );
408 return "<li>{$link} {$extract}\n" .
409 "<div class='mw-search-result-data'>{$score}{$size} - {$date}</div>" .
414 private function extractText( $text, $terms, $contextlines, $contextchars ) {
415 global $wgLang, $wgContLang;
418 $lines = explode( "\n", $text );
420 $max = intval( $contextchars ) +
1;
421 $pat1 = "/(.*)($terms)(.{0,$max})/i";
426 wfProfileIn( "$fname-extract" );
427 foreach ( $lines as $line ) {
428 if ( 0 == $contextlines ) {
433 if ( ! preg_match( $pat1, $line, $m ) ) {
437 $pre = $wgContLang->truncate( $m[1], -$contextchars, '...' );
439 if ( count( $m ) < 3 ) {
442 $post = $wgContLang->truncate( $m[3], $contextchars, '...' );
447 $line = htmlspecialchars( $pre . $found . $post );
448 $pat2 = '/(' . $terms . ")/i";
449 $line = preg_replace( $pat2,
450 "<span class='searchmatch'>\\1</span>", $line );
452 $extract .= "<br /><small>{$line}</small>\n";
454 wfProfileOut( "$fname-extract" );
460 * Generates the power search box at bottom of [[Special:Search]]
461 * @param $term string: search term
462 * @return $out string: HTML form
464 function powerSearchBox( $term ) {
468 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
469 $name = str_replace( '_', ' ', $name );
471 $name = wfMsg( 'blanknamespace' );
473 $namespaces .= Xml
::openElement( 'span', array( 'style' => 'white-space: nowrap' ) ) .
474 Xml
::checkLabel( $name, "ns{$ns}", $name, in_array( $ns, $this->namespaces
) ) .
475 Xml
::closeElement( 'span' ) . "\n";
478 $redirect = Xml
::check( 'redirs', $this->searchRedirects
, array( 'value' => '1' ) );
479 $searchField = Xml
::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
480 $searchButton = Xml
::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'fulltext' ) ) . "\n";
482 $out = Xml
::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
483 Xml
::openElement( 'fieldset' ) .
484 Xml
::element( 'legend', array( ), wfMsg( 'powersearch-legend' ) ) .
485 Xml
::hidden( 'title', 'Special:Search' ) .
486 wfMsgExt( 'powersearchtext', array( 'parse', 'replaceafter' ),
487 $namespaces, $redirect, $searchField,
488 '', '', '', '', '', # Dummy placeholders
490 Xml
::closeElement( 'fieldset' ) .
491 Xml
::closeElement( 'form' );
496 function powerSearchFocus() {
497 return "<script type='text/javascript'>" .
498 "document.getElementById('powerSearchText').focus();" .
502 function shortDialog($term) {
505 $out = Xml
::openElement( 'form', array(
508 'action' => $wgScript
510 $out .= Xml
::hidden( 'title', 'Special:Search' );
511 $out .= Xml
::input( 'search', 50, $term ) . ' ';
512 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
513 if( in_array( $ns, $this->namespaces
) ) {
514 $out .= Xml
::hidden( "ns{$ns}", '1' );
517 $out .= Xml
::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
518 $out .= Xml
::closeElement( 'form' );