2c50b49a3dbbaea9215f34b66a3c91a6cc53b32c
[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( "\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, 'search' );
39 } else {
40 $searchPage->goResult( $search );
41 }
42 }
43
44 /**
45 * implements Special:Search - Run text & title search and display the output
46 * @addtogroup SpecialPage
47 */
48 class SpecialSearch {
49
50 /**
51 * Set up basic search parameters from the request and user settings.
52 * Typically you'll pass $wgRequest and $wgUser.
53 *
54 * @param WebRequest $request
55 * @param User $user
56 * @public
57 */
58 function SpecialSearch( &$request, &$user ) {
59 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
60
61 $this->namespaces = $this->powerSearch( $request );
62 if( empty( $this->namespaces ) ) {
63 $this->namespaces = SearchEngine::userNamespaces( $user );
64 }
65
66 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
67 }
68
69 /**
70 * If an exact title match can be found, jump straight ahead to it.
71 * @param string $term
72 * @public
73 */
74 function goResult( $term ) {
75 global $wgOut;
76 global $wgGoToEdit;
77
78 $this->setupPage( $term );
79
80 # Try to go to page as entered.
81 $t = Title::newFromText( $term );
82
83 # If the string cannot be used to create a title
84 if( is_null( $t ) ){
85 return $this->showResults( $term );
86 }
87
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() );
92 return;
93 }
94
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
100 if ( $wgGoToEdit ) {
101 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
102 return;
103 }
104 }
105 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
106 $wgOut->addWikiMsg( 'noexactmatch', wfEscapeWikiText( $term ) );
107 } else {
108 $wgOut->addWikiMsg( 'noexactmatch-nocreate', wfEscapeWikiText( $term ) );
109 }
110
111 return $this->showResults( $term );
112 }
113
114 /**
115 * @param string $term
116 * @public
117 */
118 function showResults( $term ) {
119 $fname = 'SpecialSearch::showResults';
120 wfProfileIn( $fname );
121 global $wgOut, $wgUser;
122 $sk = $wgUser->getSkin();
123
124 $this->setupPage( $term );
125
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
180 $textMatches = $search->searchText( $rewritten );
181
182 // did you mean... suggestions
183 if($textMatches && $textMatches->hasSuggestion()){
184 $st = SpecialPage::getTitleFor( 'Search' );
185 $stParams = wfArrayToCGI( array(
186 'search' => $textMatches->getSuggestionQuery(),
187 'fulltext' => wfMsg('search')),
188 $this->powerSearchOptions());
189
190 $suggestLink = '<a href="'.$st->escapeLocalURL($stParams).'">'.
191 $textMatches->getSuggestionSnippet().'</a>';
192
193 $wgOut->addHTML('<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>');
194 }
195
196 // show number of results
197 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
198 + ( $textMatches ? $textMatches->numRows() : 0);
199 $totalNum = 0;
200 if($titleMatches && !is_null($titleMatches->getTotalHits()))
201 $totalNum += $titleMatches->getTotalHits();
202 if($textMatches && !is_null($textMatches->getTotalHits()))
203 $totalNum += $textMatches->getTotalHits();
204 if ( $num > 0 ) {
205 if ( $totalNum > 0 ){
206 $top = wfMsgExt('showingresultstotal', array( 'parseinline' ),
207 $this->offset+1, $this->offset+$num, $totalNum );
208 } elseif ( $num >= $this->limit ) {
209 $top = wfShowingResults( $this->offset, $this->limit );
210 } else {
211 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
212 }
213 $wgOut->addHTML( "<p>{$top}</p>\n" );
214 }
215
216 // prev/next links
217 if( $num || $this->offset ) {
218 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
219 SpecialPage::getTitleFor( 'Search' ),
220 wfArrayToCGI(
221 $this->powerSearchOptions(),
222 array( 'search' => $term ) ),
223 ($num < $this->limit) );
224 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
225 wfRunHooks( 'SpecialSearchResults', array( $term, $titleMatches, $textMatches ) );
226 } else {
227 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
228 }
229
230 if( $titleMatches ) {
231 if( $titleMatches->numRows() ) {
232 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
233 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
234 } else {
235 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
236 }
237 $titleMatches->free();
238 }
239
240 if( $textMatches ) {
241 // output appropriate heading
242 if( $textMatches->numRows() ) {
243 if($titleMatches)
244 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
245 else // if no title matches the heading is redundant
246 $wgOut->addHTML("<hr/>");
247 } elseif( $num == 0 ) {
248 # Don't show the 'no text matches' if we received title matches
249 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
250 }
251 // show interwiki results if any
252 if( $textMatches->hasInterwikiResults() )
253 $wgOut->addHtml( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ));
254 // show results
255 if( $textMatches->numRows() )
256 $wgOut->addHTML( $this->showMatches( $textMatches ) );
257
258 $textMatches->free();
259 }
260
261 if ( $num == 0 ) {
262 $wgOut->addWikiMsg( 'nonefound' );
263 }
264 if( $num || $this->offset ) {
265 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
266 }
267 $wgOut->addHTML( $this->powerSearchBox( $term ) );
268 wfProfileOut( $fname );
269 }
270
271 #------------------------------------------------------------------
272 # Private methods below this line
273
274 /**
275 *
276 */
277 function setupPage( $term ) {
278 global $wgOut;
279 if( !empty( $term ) )
280 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
281 $subtitlemsg = ( Title::newFromText( $term ) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
282 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
283 $wgOut->setArticleRelated( false );
284 $wgOut->setRobotpolicy( 'noindex,nofollow' );
285 }
286
287 /**
288 * Extract "power search" namespace settings from the request object,
289 * returning a list of index numbers to search.
290 *
291 * @param WebRequest $request
292 * @return array
293 * @private
294 */
295 function powerSearch( &$request ) {
296 $arr = array();
297 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
298 if( $request->getCheck( 'ns' . $ns ) ) {
299 $arr[] = $ns;
300 }
301 }
302 return $arr;
303 }
304
305 /**
306 * Reconstruct the 'power search' options for links
307 * @return array
308 * @private
309 */
310 function powerSearchOptions() {
311 $opt = array();
312 foreach( $this->namespaces as $n ) {
313 $opt['ns' . $n] = 1;
314 }
315 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
316 return $opt;
317 }
318
319 /**
320 * Show whole set of results
321 *
322 * @param SearchResultSet $matches
323 */
324 function showMatches( &$matches ) {
325 $fname = 'SpecialSearch::showMatches';
326 wfProfileIn( $fname );
327
328 global $wgContLang;
329 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
330
331 $out = "";
332
333 $infoLine = $matches->getInfo();
334 if( !is_null($infoLine) )
335 $out .= "\n<!-- {$infoLine} -->\n";
336
337
338 $off = $this->offset + 1;
339 $out .= "<ul class='mw-search-results'>\n";
340
341 while( $result = $matches->next() ) {
342 $out .= $this->showHit( $result, $terms );
343 }
344 $out .= "</ul>\n";
345
346 // convert the whole thing to desired language variant
347 global $wgContLang;
348 $out = $wgContLang->convert( $out );
349 wfProfileOut( $fname );
350 return $out;
351 }
352
353 /**
354 * Format a single hit result
355 * @param SearchResult $result
356 * @param array $terms terms to highlight
357 */
358 function showHit( $result, $terms ) {
359 $fname = 'SpecialSearch::showHit';
360 wfProfileIn( $fname );
361 global $wgUser, $wgContLang, $wgLang;
362
363 if( $result->isBrokenTitle() ) {
364 wfProfileOut( $fname );
365 return "<!-- Broken link in search result -->\n";
366 }
367
368 $t = $result->getTitle();
369 $sk = $wgUser->getSkin();
370
371 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
372
373 //If page content is not readable, just return the title.
374 //This is not quite safe, but better than showing excerpts from non-readable pages
375 //Note that hiding the entry entirely would screw up paging.
376 if (!$t->userCanRead()) {
377 wfProfileOut( $fname );
378 return "<li>{$link}</li>\n";
379 }
380
381 // If the page doesn't *exist*... our search index is out of date.
382 // The least confusing at this point is to drop the result.
383 // You may get less results, but... oh well. :P
384 if( $result->isMissingRevision() ) {
385 wfProfileOut( $fname );
386 return "<!-- missing page " .
387 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
388 }
389
390 // format redirects / relevant sections
391 $redirectTitle = $result->getRedirectTitle();
392 $redirectText = $result->getRedirectSnippet($terms);
393 $sectionTitle = $result->getSectionTitle();
394 $sectionText = $result->getSectionSnippet($terms);
395 $redirect = '';
396 if( !is_null($redirectTitle) )
397 $redirect = "<span class='searchalttitle'>"
398 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
399 ."</span>";
400 $section = '';
401 if( !is_null($sectionTitle) )
402 $section = "<span class='searchalttitle'>"
403 .wfMsg('search-section', $sk->makeKnownLinkObj( $sectionTitle, $sectionText))
404 ."</span>";
405
406 // format text extract
407 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
408
409 // format score
410 if( is_null( $result->getScore() ) ) {
411 // Search engine doesn't report scoring info
412 $score = '';
413 } else {
414 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
415 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
416 . ' - ';
417 }
418
419 // format description
420 $byteSize = $result->getByteSize();
421 $wordCount = $result->getWordCount();
422 $timestamp = $result->getTimestamp();
423 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
424 $sk->formatSize( $byteSize ),
425 $wordCount );
426 $date = $wgLang->timeanddate( $timestamp );
427
428 // link to related articles if supported
429 $related = '';
430 if( $result->hasRelated() ){
431 $st = SpecialPage::getTitleFor( 'Search' );
432 $stParams = wfArrayToCGI( $this->powerSearchOptions(),
433 array('search' => wfMsgForContent('searchrelated').':'.$t->getPrefixedText(),
434 'fulltext' => wfMsg('search') ));
435
436 $related = ' -- <a href="'.$st->escapeLocalURL($stParams).'">'.
437 wfMsg('search-relatedarticle').'</a>';
438 }
439
440 // Include a thumbnail for media files...
441 if( $t->getNamespace() == NS_IMAGE ) {
442 $img = wfFindFile( $t );
443 if( $img ) {
444 $thumb = $img->getThumbnail( 120, 120 );
445 if( $thumb ) {
446 $desc = $img->getShortDesc();
447 wfProfileOut( $fname );
448 // Ugly table. :D
449 // Float doesn't seem to interact well with the bullets.
450 // Table messes up vertical alignment of the bullet, but I'm
451 // not sure what more I can do about that. :(
452 return "<li>" .
453 '<table class="searchResultImage">' .
454 '<tr>' .
455 '<td width="120" align="center">' .
456 $thumb->toHtml( array( 'desc-link' => true ) ) .
457 '</td>' .
458 '<td valign="top">' .
459 $link .
460 $extract .
461 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
462 '</td>' .
463 '</tr>' .
464 '</table>' .
465 "</li>\n";
466 }
467 }
468 }
469
470 wfProfileOut( $fname );
471 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
472 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
473 "</li>\n";
474
475 }
476
477 /**
478 * Show results from other wikis
479 *
480 * @param SearchResultSet $matches
481 */
482 function showInterwiki( &$matches, $query ) {
483 $fname = 'SpecialSearch::showInterwiki';
484 wfProfileIn( $fname );
485
486 global $wgContLang;
487 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
488
489 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".wfMsg('search-interwiki-caption')."</div>\n";
490 $off = $this->offset + 1;
491 $out .= "<ul start='{$off}' class='mw-search-iwresults'>\n";
492
493 // work out custom project captions
494 $customCaptions = array();
495 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
496 foreach($customLines as $line){
497 $parts = explode(":",$line,2);
498 if(count($parts) == 2) // validate line
499 $customCaptions[$parts[0]] = $parts[1];
500 }
501
502
503 $prev = null;
504 while( $result = $matches->next() ) {
505 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
506 $prev = $result->getInterwikiPrefix();
507 }
508 // FIXME: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
509 $out .= "</ul></div>\n";
510
511 // convert the whole thing to desired language variant
512 global $wgContLang;
513 $out = $wgContLang->convert( $out );
514 wfProfileOut( $fname );
515 return $out;
516 }
517
518 /**
519 * Show single interwiki link
520 *
521 * @param SearchResult $result
522 * @param string $lastInterwiki
523 * @param array $terms
524 * @param string $query
525 * @param array $customCaptions iw prefix -> caption
526 */
527 function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions){
528 $fname = 'SpecialSearch::showInterwikiHit';
529 wfProfileIn( $fname );
530 global $wgUser, $wgContLang, $wgLang;
531
532 if( $result->isBrokenTitle() ) {
533 wfProfileOut( $fname );
534 return "<!-- Broken link in search result -->\n";
535 }
536
537 $t = $result->getTitle();
538 $sk = $wgUser->getSkin();
539
540 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
541
542 // format redirect if any
543 $redirectTitle = $result->getRedirectTitle();
544 $redirectText = $result->getRedirectSnippet($terms);
545 $redirect = '';
546 if( !is_null($redirectTitle) )
547 $redirect = "<span class='searchalttitle'>"
548 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
549 ."</span>";
550
551 $out = "";
552 // display project name
553 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()){
554 if( key_exists($t->getInterwiki(),$customCaptions) )
555 // captions from 'search-interwiki-custom'
556 $caption = $customCaptions[$t->getInterwiki()];
557 else{
558 // default is to show the hostname of the other wiki which might suck
559 // if there are many wikis on one hostname
560 $parsed = parse_url($t->getFullURL());
561 $caption = wfMsg('search-interwiki-default', $parsed['host']);
562 }
563 // "more results" link (special page stuff could be localized, but we might not know target lang)
564 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
565 $searchLink = $sk->makeKnownLinkObj( $searchTitle, wfMsg('search-interwiki-more'),
566 wfArrayToCGI(array('search' => $query, 'fulltext' => 'Search')));
567 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>{$searchLink}</span>{$caption}</div>\n<ul>";
568 }
569
570 $out .= "<li>{$link} {$redirect}</li>\n";
571 wfProfileOut( $fname );
572 return $out;
573 }
574
575
576 /**
577 * Generates the power search box at bottom of [[Special:Search]]
578 * @param $term string: search term
579 * @return $out string: HTML form
580 */
581 function powerSearchBox( $term ) {
582 global $wgScript;
583
584 $namespaces = '';
585 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
586 $name = str_replace( '_', ' ', $name );
587 if( '' == $name ) {
588 $name = wfMsg( 'blanknamespace' );
589 }
590 $namespaces .= Xml::openElement( 'span', array( 'style' => 'white-space: nowrap' ) ) .
591 Xml::checkLabel( $name, "ns{$ns}", "mw-search-ns{$ns}", in_array( $ns, $this->namespaces ) ) .
592 Xml::closeElement( 'span' ) . "\n";
593 }
594
595 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1' ) );
596 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
597 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'fulltext' ) ) . "\n";
598
599 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
600 Xml::openElement( 'fieldset' ) .
601 Xml::element( 'legend', array( ), wfMsg( 'powersearch-legend' ) ) .
602 Xml::hidden( 'title', 'Special:Search' ) .
603 wfMsgExt( 'powersearchtext', array( 'parse', 'replaceafter' ),
604 $namespaces, $redirect, $searchField,
605 '', '', '', '', '', # Dummy placeholders
606 $searchButton ) .
607 Xml::closeElement( 'fieldset' ) .
608 Xml::closeElement( 'form' );
609
610 return $out;
611 }
612
613 function powerSearchFocus() {
614 return "<script type='text/javascript'>" .
615 "document.getElementById('powerSearchText').focus();" .
616 "</script>";
617 }
618
619 function shortDialog($term) {
620 global $wgScript;
621
622 $out = Xml::openElement( 'form', array(
623 'id' => 'search',
624 'method' => 'get',
625 'action' => $wgScript
626 ));
627 $out .= Xml::hidden( 'title', 'Special:Search' );
628 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . ' ';
629 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
630 if( in_array( $ns, $this->namespaces ) ) {
631 $out .= Xml::hidden( "ns{$ns}", '1' );
632 }
633 }
634 $out .= Xml::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
635 $out .= Xml::closeElement( 'form' );
636
637 return $out;
638 }
639 }