Add a nice fieldset around the external search input form
[lhc/web/wiklou.git] / includes / SpecialSearch.php
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
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.
9 #
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.
14 #
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
19
20 /**
21 * Run text & title search and display the output
22 * @addtogroup SpecialPage
23 */
24
25 /**
26 * Entry point
27 *
28 * @param $par String: (default '')
29 */
30 function wfSpecialSearch( $par = '' ) {
31 global $wgRequest, $wgUser;
32
33 $search = str_replace( array('_', "\n"), " ",
34 $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 );
40 } else {
41 $searchPage->goResult( $search );
42 }
43 }
44
45 /**
46 * implements Special:Search - Run text & title search and display the output
47 * @addtogroup SpecialPage
48 */
49 class SpecialSearch {
50
51 /**
52 * Set up basic search parameters from the request and user settings.
53 * Typically you'll pass $wgRequest and $wgUser.
54 *
55 * @param WebRequest $request
56 * @param User $user
57 * @public
58 */
59 function SpecialSearch( &$request, &$user ) {
60 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
61
62 $this->namespaces = $this->powerSearch( $request );
63 if( empty( $this->namespaces ) ) {
64 $this->namespaces = $this->userNamespaces( $user );
65 }
66
67 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
68 }
69
70 /**
71 * If an exact title match can be found, jump straight ahead to it.
72 * @param string $term
73 * @public
74 */
75 function goResult( $term ) {
76 global $wgOut;
77 global $wgGoToEdit;
78
79 $this->setupPage( $term );
80
81 # Try to go to page as entered.
82 $t = Title::newFromText( $term );
83
84 # If the string cannot be used to create a title
85 if( is_null( $t ) ){
86 return $this->showResults( $term );
87 }
88
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() );
93 return;
94 }
95
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
101 if ( $wgGoToEdit ) {
102 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
103 return;
104 }
105 }
106 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
107 $wgOut->addWikiMsg( 'noexactmatch', wfEscapeWikiText( $term ) );
108 } else {
109 $wgOut->addWikiMsg( 'noexactmatch-nocreate', wfEscapeWikiText( $term ) );
110 }
111
112 return $this->showResults( $term );
113 }
114
115 /**
116 * @param string $term
117 * @public
118 */
119 function showResults( $term ) {
120 $fname = 'SpecialSearch::showResults';
121 wfProfileIn( $fname );
122
123 $this->setupPage( $term );
124
125 global $wgOut;
126 $wgOut->addWikiMsg( 'searchresulttext' );
127
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 );
134 return;
135 }
136
137 global $wgDisableTextSearch;
138 if ( $wgDisableTextSearch ) {
139 global $wgForwardSearchUrl;
140 if( $wgForwardSearchUrl ) {
141 $url = str_replace( '$1', urlencode( $term ), $wgForwardSearchUrl );
142 $wgOut->redirect( $url );
143 return;
144 }
145 global $wgInputEncoding;
146 $wgOut->addHTML(
147 Xml::openElement( 'fieldset' ) .
148 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
149 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
150 wfMsg( 'googlesearch',
151 htmlspecialchars( $term ),
152 htmlspecialchars( $wgInputEncoding ),
153 htmlspecialchars( wfMsg( 'searchbutton' ) )
154 ) .
155 Xml::closeElement( 'fieldset' )
156 );
157 wfProfileOut( $fname );
158 return;
159 }
160
161 $wgOut->addHTML( $this->shortDialog( $term ) );
162
163 $search = SearchEngine::create();
164 $search->setLimitOffset( $this->limit, $this->offset );
165 $search->setNamespaces( $this->namespaces );
166 $search->showRedirects = $this->searchRedirects;
167 $rewritten = $search->replacePrefixes($term);
168
169 $titleMatches = $search->searchTitle( $rewritten );
170
171 // Sometimes the search engine knows there are too many hits
172 if ($titleMatches instanceof SearchResultTooMany) {
173 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
174 $wgOut->addHTML( $this->powerSearchBox( $term ) );
175 $wgOut->addHTML( $this->powerSearchFocus() );
176 wfProfileOut( $fname );
177 return;
178 }
179 $textMatches = $search->searchText( $rewritten );
180
181 // did you mean...
182 if($textMatches && $textMatches->hasSuggestion()){
183 global $wgScript;
184 $fulltext = htmlspecialchars(wfMsg('search'));
185 $suggestLink = '<a href="'.$wgScript.'?title=Special:Search&amp;search='.
186 urlencode($textMatches->getSuggestionQuery()).'&amp;fulltext='.$fulltext.'">'
187 .$textMatches->getSuggestionSnippet().'</a>';
188 $wgOut->addHTML('<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>');
189 }
190
191
192 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
193 + ( $textMatches ? $textMatches->numRows() : 0);
194 $totalNum = 0;
195 if($titleMatches && !is_null($titleMatches->getTotalHits()))
196 $totalNum += $titleMatches->getTotalHits();
197 if($textMatches && !is_null($textMatches->getTotalHits()))
198 $totalNum += $textMatches->getTotalHits();
199 if ( $num > 0 ) {
200 if ( $totalNum > 0 ){
201 $top = wfMsgExt('showingresultstotal',array( 'parseinline' ), $this->offset+1, $this->offset+$num, $totalNum);
202 } elseif ( $num >= $this->limit ) {
203 $top = wfShowingResults( $this->offset, $this->limit );
204 } else {
205 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
206 }
207 $wgOut->addHTML( "<p>{$top}</p>\n" );
208 }
209
210 if( $num || $this->offset ) {
211 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
212 SpecialPage::getTitleFor( 'Search' ),
213 wfArrayToCGI(
214 $this->powerSearchOptions(),
215 array( 'search' => $term ) ),
216 ($num < $this->limit) );
217 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
218 wfRunHooks( 'SpecialSearchResults', array( $term, $titleMatches, $textMatches ) );
219 } else {
220 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
221 }
222
223 if( $titleMatches ) {
224 if( $titleMatches->numRows() ) {
225 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
226 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
227 } else {
228 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
229 }
230 $titleMatches->free();
231 }
232
233 if( $textMatches ) {
234 if( $textMatches->numRows() ) {
235 if($titleMatches)
236 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
237 else // if no title matches the heading is redundant
238 $wgOut->addHTML("<hr/>");
239 $wgOut->addHTML( $this->showMatches( $textMatches ) );
240 } elseif( $num == 0 ) {
241 # Don't show the 'no text matches' if we received title matches
242 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
243 }
244 $textMatches->free();
245 }
246
247 if ( $num == 0 ) {
248 $wgOut->addWikiMsg( 'nonefound' );
249 }
250 if( $num || $this->offset ) {
251 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
252 }
253 $wgOut->addHTML( $this->powerSearchBox( $term ) );
254 wfProfileOut( $fname );
255 }
256
257 #------------------------------------------------------------------
258 # Private methods below this line
259
260 /**
261 *
262 */
263 function setupPage( $term ) {
264 global $wgOut;
265 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
266 $subtitlemsg = ( Title::newFromText($term) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
267 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
268 $wgOut->setArticleRelated( false );
269 $wgOut->setRobotpolicy( 'noindex,nofollow' );
270 }
271
272 /**
273 * Extract default namespaces to search from the given user's
274 * settings, returning a list of index numbers.
275 *
276 * @param User $user
277 * @return array
278 * @private
279 */
280 function userNamespaces( &$user ) {
281 $arr = array();
282 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
283 if( $user->getOption( 'searchNs' . $ns ) ) {
284 $arr[] = $ns;
285 }
286 }
287 return $arr;
288 }
289
290 /**
291 * Extract "power search" namespace settings from the request object,
292 * returning a list of index numbers to search.
293 *
294 * @param WebRequest $request
295 * @return array
296 * @private
297 */
298 function powerSearch( &$request ) {
299 $arr = array();
300 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
301 if( $request->getCheck( 'ns' . $ns ) ) {
302 $arr[] = $ns;
303 }
304 }
305 return $arr;
306 }
307
308 /**
309 * Reconstruct the 'power search' options for links
310 * @return array
311 * @private
312 */
313 function powerSearchOptions() {
314 $opt = array();
315 foreach( $this->namespaces as $n ) {
316 $opt['ns' . $n] = 1;
317 }
318 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
319 return $opt;
320 }
321
322
323
324 /**
325 * @param SearchResultSet $matches
326 * @param string $terms partial regexp for highlighting terms
327 */
328 function showMatches( &$matches ) {
329 $fname = 'SpecialSearch::showMatches';
330 wfProfileIn( $fname );
331
332 global $wgContLang;
333 $tm = $wgContLang->convertForSearchResult( $matches->termMatches() );
334 $terms = implode( '|', $tm );
335
336 $off = $this->offset + 1;
337 $out = "<ul start='{$off}' class='mw-search-results'>\n";
338
339 while( $result = $matches->next() ) {
340 $out .= $this->showHit( $result, $terms );
341 }
342 $out .= "</ul>\n";
343
344 // convert the whole thing to desired language variant
345 global $wgContLang;
346 $out = $wgContLang->convert( $out );
347 wfProfileOut( $fname );
348 return $out;
349 }
350
351 /**
352 * Format a single hit result
353 * @param SearchResult $result
354 * @param string $terms partial regexp for highlighting terms
355 */
356 function showHit( $result, $terms ) {
357 $fname = 'SpecialSearch::showHit';
358 wfProfileIn( $fname );
359 global $wgUser, $wgContLang, $wgLang;
360
361 $t = $result->getTitle();
362 if( is_null( $t ) ) {
363 wfProfileOut( $fname );
364 return "<!-- Broken link in search result -->\n";
365 }
366 $sk = $wgUser->getSkin();
367
368 //$contextlines = $wgUser->getOption( 'contextlines', 5 );
369 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
370 $contextchars = $wgUser->getOption( 'contextchars', 50 );
371
372 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet());
373
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 return "<li>{$link}</li>\n";
379 }
380
381 $revision = Revision::newFromTitle( $t );
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( !$revision ) {
386 return "<!-- missing page " .
387 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
388 }
389
390 if( is_null( $result->getScore() ) ) {
391 // Search engine doesn't report scoring info
392 $score = '';
393 } else {
394 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
395 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
396 . ' - ';
397 }
398
399 // try to fetch everything from the search engine backend
400 // then fill-in what couldn't be fetched
401 $extract = $result->getTextSnippet();
402 $byteSize = $result->getByteSize();
403 $wordCount = $result->getWordCount();
404 $timestamp = $result->getTimestamp();
405 $redirectTitle = $result->getRedirectTitle();
406 $redirectText = $result->getRedirectSnippet();
407 $sectionTitle = $result->getSectionTitle();
408 $sectionText = $result->getSectionSnippet();
409
410 // fallback
411 if( is_null($extract) || is_null($wordCount) || is_null($byteSize) ){
412 $text = $revision->getText();
413 if( is_null($extract) )
414 $extract = $this->extractText( $text, $terms, $contextlines, $contextchars );
415 if( is_null($byteSize) )
416 $byteSize = strlen( $text );
417 if( is_null($wordCount) )
418 $wordCount = str_word_count( $text );
419 }
420 if( is_null($timestamp) ){
421 $timestamp = $revision->getTimestamp();
422 }
423
424 // format description
425 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
426 $sk->formatSize( $byteSize ),
427 $wordCount );
428 $date = $wgLang->timeanddate( $timestamp );
429
430 // format redirects / sections
431 $redirect = '';
432 if( !is_null($redirectTitle) )
433 $redirect = "<span class='searchalttitle'>"
434 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
435 ."</span>";
436 $section = '';
437 if( !is_null($sectionTitle) )
438 $section = "<span class='searchalttitle'>"
439 .wfMsg('search-section', $sk->makeKnownLinkObj( $sectionTitle, $sectionText))
440 ."</span>";
441 // wrap extract
442 $extract = "<div class='searchresult'>".$extract."</div>";
443
444 // Include a thumbnail for media files...
445 if( $t->getNamespace() == NS_IMAGE ) {
446 $img = wfFindFile( $t );
447 if( $img ) {
448 $thumb = $img->getThumbnail( 120, 120 );
449 if( $thumb ) {
450 $desc = $img->getShortDesc();
451 wfProfileOut( $fname );
452 // Ugly table. :D
453 // Float doesn't seem to interact well with the bullets.
454 // Table messes up vertical alignment of the bullet, but I'm
455 // not sure what more I can do about that. :(
456 return "<li>" .
457 '<table class="searchResultImage">' .
458 '<tr>' .
459 '<td width="120" align="center">' .
460 $thumb->toHtml( array( 'desc-link' => true ) ) .
461 '</td>' .
462 '<td valign="top">' .
463 $link .
464 $extract .
465 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}</div>" .
466 '</td>' .
467 '</tr>' .
468 '</table>' .
469 "</li>\n";
470 }
471 }
472 }
473
474 wfProfileOut( $fname );
475 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
476 "<div class='mw-search-result-data'>{$score}{$size} - {$date}</div>" .
477 "</li>\n";
478
479 }
480
481 private function extractText( $text, $terms, $contextlines, $contextchars ) {
482 global $wgLang, $wgContLang;
483 $fname = __METHOD__;
484
485 $lines = explode( "\n", $text );
486
487 $max = intval( $contextchars ) + 1;
488 $pat1 = "/(.*)($terms)(.{0,$max})/i";
489
490 $lineno = 0;
491
492 $extract = "";
493 wfProfileIn( "$fname-extract" );
494 foreach ( $lines as $line ) {
495 if ( 0 == $contextlines ) {
496 break;
497 }
498 ++$lineno;
499 $m = array();
500 if ( ! preg_match( $pat1, $line, $m ) ) {
501 continue;
502 }
503 --$contextlines;
504 $pre = $wgContLang->truncate( $m[1], -$contextchars, ' ... ' );
505
506 if ( count( $m ) < 3 ) {
507 $post = '';
508 } else {
509 $post = $wgContLang->truncate( $m[3], $contextchars, ' ... ' );
510 }
511
512 $found = $m[2];
513
514 $line = htmlspecialchars( $pre . $found . $post );
515 $pat2 = '/(' . $terms . ")/i";
516 $line = preg_replace( $pat2,
517 "<span class='searchmatch'>\\1</span>", $line );
518
519 $extract .= "${line}\n";
520 }
521 wfProfileOut( "$fname-extract" );
522
523 return $extract;
524 }
525
526 /**
527 * Generates the power search box at bottom of [[Special:Search]]
528 * @param $term string: search term
529 * @return $out string: HTML form
530 */
531 function powerSearchBox( $term ) {
532 global $wgScript;
533
534 $namespaces = '';
535 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
536 $name = str_replace( '_', ' ', $name );
537 if( '' == $name ) {
538 $name = wfMsg( 'blanknamespace' );
539 }
540 $namespaces .= Xml::openElement( 'span', array( 'style' => 'white-space: nowrap' ) ) .
541 Xml::checkLabel( $name, "ns{$ns}", $name, in_array( $ns, $this->namespaces ) ) .
542 Xml::closeElement( 'span' ) . "\n";
543 }
544
545 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1' ) );
546 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
547 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'fulltext' ) ) . "\n";
548
549 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
550 Xml::openElement( 'fieldset' ) .
551 Xml::element( 'legend', array( ), wfMsg( 'powersearch-legend' ) ) .
552 Xml::hidden( 'title', 'Special:Search' ) .
553 wfMsgExt( 'powersearchtext', array( 'parse', 'replaceafter' ),
554 $namespaces, $redirect, $searchField,
555 '', '', '', '', '', # Dummy placeholders
556 $searchButton ) .
557 Xml::closeElement( 'fieldset' ) .
558 Xml::closeElement( 'form' );
559
560 return $out;
561 }
562
563 function powerSearchFocus() {
564 return "<script type='text/javascript'>" .
565 "document.getElementById('powerSearchText').focus();" .
566 "</script>";
567 }
568
569 function shortDialog($term) {
570 global $wgScript;
571
572 $out = Xml::openElement( 'form', array(
573 'id' => 'search',
574 'method' => 'get',
575 'action' => $wgScript
576 ));
577 $out .= Xml::hidden( 'title', 'Special:Search' );
578 $out .= Xml::input( 'search', 50, $term ) . ' ';
579 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
580 if( in_array( $ns, $this->namespaces ) ) {
581 $out .= Xml::hidden( "ns{$ns}", '1' );
582 }
583 }
584 $out .= Xml::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
585 $out .= Xml::closeElement( 'form' );
586
587 return $out;
588 }
589 }