trim $this->mUserName var so that login attempt throttle key isn't fragmented with...
[lhc/web/wiklou.git] / includes / specials / SpecialSearch.php
1 <?php
2 /**
3 * Implements Special:Search
4 *
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 * @ingroup SpecialPage
24 */
25
26 /**
27 * implements Special:Search - Run text & title search and display the output
28 * @ingroup SpecialPage
29 */
30 class SpecialSearch extends SpecialPage {
31 /// Current search profile
32 protected $profile;
33
34 /// Search engine
35 protected $searchEngine;
36
37 /// For links
38 protected $extraParams = array();
39
40 /// No idea, apparently used by some other classes
41 protected $mPrefix;
42
43 const NAMESPACES_CURRENT = 'sense';
44
45 public function __construct() {
46 parent::__construct( 'Search' );
47 }
48
49 /**
50 * Entry point
51 *
52 * @param $par String or null
53 */
54 public function execute( $par ) {
55 global $wgRequest, $wgUser, $wgOut;
56
57 $this->setHeaders();
58 $this->outputHeader();
59 $wgOut->allowClickjacking();
60 $wgOut->addModuleStyles( 'mediawiki.special' );
61
62 // Strip underscores from title parameter; most of the time we'll want
63 // text form here. But don't strip underscores from actual text params!
64 $titleParam = str_replace( '_', ' ', $par );
65
66 // Fetch the search term
67 $search = str_replace( "\n", " ", $wgRequest->getText( 'search', $titleParam ) );
68
69 $this->load( $wgRequest, $wgUser );
70
71 if ( $wgRequest->getVal( 'fulltext' )
72 || !is_null( $wgRequest->getVal( 'offset' ) )
73 || !is_null( $wgRequest->getVal( 'searchx' ) ) )
74 {
75 $this->showResults( $search );
76 } else {
77 $this->goResult( $search );
78 }
79 }
80
81 /**
82 * Set up basic search parameters from the request and user settings.
83 * Typically you'll pass $wgRequest and $wgUser.
84 *
85 * @param $request WebRequest
86 * @param $user User
87 */
88 public function load( &$request, &$user ) {
89 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
90 $this->mPrefix = $request->getVal( 'prefix', '' );
91
92
93 # Extract manually requested namespaces
94 $nslist = $this->powerSearch( $request );
95 $this->profile = $profile = $request->getVal( 'profile', null );
96 $profiles = $this->getSearchProfiles();
97 if ( $profile === null) {
98 // BC with old request format
99 $this->profile = 'advanced';
100 if ( count( $nslist ) ) {
101 foreach( $profiles as $key => $data ) {
102 if ( $nslist === $data['namespaces'] && $key !== 'advanced') {
103 $this->profile = $key;
104 }
105 }
106 $this->namespaces = $nslist;
107 } else {
108 $this->namespaces = SearchEngine::userNamespaces( $user );
109 }
110 } elseif ( $profile === 'advanced' ) {
111 $this->namespaces = $nslist;
112 } else {
113 if ( isset( $profiles[$profile]['namespaces'] ) ) {
114 $this->namespaces = $profiles[$profile]['namespaces'];
115 } else {
116 // Unknown profile requested
117 $this->profile = 'default';
118 $this->namespaces = $profiles['default']['namespaces'];
119 }
120 }
121
122 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
123 $default = $request->getBool( 'profile' ) ? 0 : 1;
124 $this->searchRedirects = $request->getBool( 'redirs', $default ) ? 1 : 0;
125 $this->sk = $this->getSkin();
126 $this->didYouMeanHtml = ''; # html of did you mean... link
127 $this->fulltext = $request->getVal('fulltext');
128 }
129
130 /**
131 * If an exact title match can be found, jump straight ahead to it.
132 *
133 * @param $term String
134 */
135 public function goResult( $term ) {
136 global $wgOut;
137 $this->setupPage( $term );
138 # Try to go to page as entered.
139 $t = Title::newFromText( $term );
140 # If the string cannot be used to create a title
141 if( is_null( $t ) ) {
142 return $this->showResults( $term );
143 }
144 # If there's an exact or very near match, jump right there.
145 $t = SearchEngine::getNearMatch( $term );
146
147 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
148 # Hook requested termination
149 return;
150 }
151
152 if( !is_null( $t ) ) {
153 $wgOut->redirect( $t->getFullURL() );
154 return;
155 }
156 # No match, generate an edit URL
157 $t = Title::newFromText( $term );
158 if( !is_null( $t ) ) {
159 global $wgGoToEdit;
160 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
161 wfDebugLog( 'nogomatch', $t->getText(), false );
162
163 # If the feature is enabled, go straight to the edit page
164 if( $wgGoToEdit ) {
165 $wgOut->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
166 return;
167 }
168 }
169 return $this->showResults( $term );
170 }
171
172 /**
173 * @param $term String
174 */
175 public function showResults( $term ) {
176 global $wgOut, $wgDisableTextSearch, $wgContLang, $wgScript;
177 wfProfileIn( __METHOD__ );
178
179 $sk = $this->getSkin();
180
181 $search = $this->getSearchEngine();
182 $search->setLimitOffset( $this->limit, $this->offset );
183 $search->setNamespaces( $this->namespaces );
184 $search->showRedirects = $this->searchRedirects; // BC
185 $search->setFeatureData( 'list-redirects', $this->searchRedirects );
186 $search->prefix = $this->mPrefix;
187 $term = $search->transformSearchTerm($term);
188
189 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
190
191 $this->setupPage( $term );
192
193 if( $wgDisableTextSearch ) {
194 global $wgSearchForwardUrl;
195 if( $wgSearchForwardUrl ) {
196 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
197 $wgOut->redirect( $url );
198 wfProfileOut( __METHOD__ );
199 return;
200 }
201 $wgOut->addHTML(
202 Xml::openElement( 'fieldset' ) .
203 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
204 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
205 wfMsg( 'googlesearch',
206 htmlspecialchars( $term ),
207 htmlspecialchars( 'UTF-8' ),
208 htmlspecialchars( wfMsg( 'searchbutton' ) )
209 ) .
210 Xml::closeElement( 'fieldset' )
211 );
212 wfProfileOut( __METHOD__ );
213 return;
214 }
215
216 $t = Title::newFromText( $term );
217
218 // fetch search results
219 $rewritten = $search->replacePrefixes($term);
220
221 $titleMatches = $search->searchTitle( $rewritten );
222 if( !($titleMatches instanceof SearchResultTooMany))
223 $textMatches = $search->searchText( $rewritten );
224
225 // did you mean... suggestions
226 if( $textMatches && $textMatches->hasSuggestion() ) {
227 $st = SpecialPage::getTitleFor( 'Search' );
228
229 # mirror Go/Search behaviour of original request ..
230 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
231
232 if($this->fulltext != null)
233 $didYouMeanParams['fulltext'] = $this->fulltext;
234
235 $stParams = array_merge(
236 $didYouMeanParams,
237 $this->powerSearchOptions()
238 );
239
240 $suggestionSnippet = $textMatches->getSuggestionSnippet();
241
242 if( $suggestionSnippet == '' )
243 $suggestionSnippet = null;
244
245 $suggestLink = $sk->linkKnown(
246 $st,
247 $suggestionSnippet,
248 array(),
249 $stParams
250 );
251
252 $this->didYouMeanHtml = '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
253 }
254 // start rendering the page
255 $wgOut->addHtml(
256 Xml::openElement(
257 'form',
258 array(
259 'id' => ( $this->profile === 'advanced' ? 'powersearch' : 'search' ),
260 'method' => 'get',
261 'action' => $wgScript
262 )
263 )
264 );
265 $wgOut->addHtml(
266 Xml::openElement( 'table', array( 'id'=>'mw-search-top-table', 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
267 Xml::openElement( 'tr' ) .
268 Xml::openElement( 'td' ) . "\n" .
269 $this->shortDialog( $term ) .
270 Xml::closeElement('td') .
271 Xml::closeElement('tr') .
272 Xml::closeElement('table')
273 );
274
275 // Sometimes the search engine knows there are too many hits
276 if( $titleMatches instanceof SearchResultTooMany ) {
277 $wgOut->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
278 wfProfileOut( __METHOD__ );
279 return;
280 }
281
282 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE).':';
283 if( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
284 $wgOut->addHTML( $this->formHeader( $term, 0, 0 ) );
285 $wgOut->addHtml( $this->getProfileForm( $this->profile, $term ) );
286 $wgOut->addHTML( '</form>' );
287 // Empty query -- straight view of search form
288 wfProfileOut( __METHOD__ );
289 return;
290 }
291
292 // Get number of results
293 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
294 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
295 // Total initial query matches (possible false positives)
296 $num = $titleMatchesNum + $textMatchesNum;
297
298 // Get total actual results (after second filtering, if any)
299 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
300 $titleMatches->getTotalHits() : $titleMatchesNum;
301 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
302 $textMatches->getTotalHits() : $textMatchesNum;
303
304 // get total number of results if backend can calculate it
305 $totalRes = 0;
306 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
307 $totalRes += $titleMatches->getTotalHits();
308 if($textMatches && !is_null( $textMatches->getTotalHits() ))
309 $totalRes += $textMatches->getTotalHits();
310
311 // show number of results and current offset
312 $wgOut->addHTML( $this->formHeader( $term, $num, $totalRes ) );
313 $wgOut->addHtml( $this->getProfileForm( $this->profile, $term ) );
314
315
316 $wgOut->addHtml( Xml::closeElement( 'form' ) );
317 $wgOut->addHtml( "<div class='searchresults'>" );
318
319 // prev/next links
320 if( $num || $this->offset ) {
321 // Show the create link ahead
322 $this->showCreateLink( $t );
323 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
324 SpecialPage::getTitleFor( 'Search' ),
325 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
326 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
327 );
328 //$wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
329 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
330 } else {
331 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
332 }
333
334 $wgOut->parserOptions()->setEditSection( false );
335 if( $titleMatches ) {
336 if( $numTitleMatches > 0 ) {
337 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
338 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
339 }
340 $titleMatches->free();
341 }
342 if( $textMatches ) {
343 // output appropriate heading
344 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
345 // if no title matches the heading is redundant
346 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
347 } elseif( $totalRes == 0 ) {
348 # Don't show the 'no text matches' if we received title matches
349 # $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
350 }
351 // show interwiki results if any
352 if( $textMatches->hasInterwikiResults() ) {
353 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
354 }
355 // show results
356 if( $numTextMatches > 0 ) {
357 $wgOut->addHTML( $this->showMatches( $textMatches ) );
358 }
359
360 $textMatches->free();
361 }
362 if( $num === 0 ) {
363 $wgOut->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
364 $this->showCreateLink( $t );
365 }
366 $wgOut->addHtml( "</div>" );
367
368 if( $num || $this->offset ) {
369 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
370 }
371 wfProfileOut( __METHOD__ );
372 }
373
374 protected function showCreateLink( $t ) {
375 global $wgOut;
376
377 // show direct page/create link if applicable
378 // Check DBkey !== '' in case of fragment link only.
379 $messageName = null;
380 if( !is_null($t) && $t->getDBkey() !== '' ) {
381 if( $t->isKnown() ) {
382 $messageName = 'searchmenu-exists';
383 } elseif( $t->userCan( 'create' ) ) {
384 $messageName = 'searchmenu-new';
385 } else {
386 $messageName = 'searchmenu-new-nocreate';
387 }
388 }
389 if( $messageName ) {
390 $wgOut->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) ) );
391 } else {
392 // preserve the paragraph for margins etc...
393 $wgOut->addHtml( '<p></p>' );
394 }
395 }
396
397 /**
398 *
399 */
400 protected function setupPage( $term ) {
401 global $wgOut;
402
403 # Should advanced UI be used?
404 $this->searchAdvanced = ($this->profile === 'advanced');
405 if( strval( $term ) !== '' ) {
406 $wgOut->setPageTitle( wfMsg( 'searchresults') );
407 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
408 }
409 // add javascript specific to special:search
410 $wgOut->addModules( 'mediawiki.special.search' );
411 }
412
413 /**
414 * Extract "power search" namespace settings from the request object,
415 * returning a list of index numbers to search.
416 *
417 * @param $request WebRequest
418 * @return Array
419 */
420 protected function powerSearch( &$request ) {
421 $arr = array();
422 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
423 if( $request->getCheck( 'ns' . $ns ) ) {
424 $arr[] = $ns;
425 }
426 }
427
428 return $arr;
429 }
430
431 /**
432 * Reconstruct the 'power search' options for links
433 *
434 * @return Array
435 */
436 protected function powerSearchOptions() {
437 $opt = array();
438 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
439 if( $this->profile !== 'advanced' ) {
440 $opt['profile'] = $this->profile;
441 } else {
442 foreach( $this->namespaces as $n ) {
443 $opt['ns' . $n] = 1;
444 }
445 }
446 return $opt + $this->extraParams;
447 }
448
449 /**
450 * Show whole set of results
451 *
452 * @param $matches SearchResultSet
453 */
454 protected function showMatches( &$matches ) {
455 global $wgContLang;
456 wfProfileIn( __METHOD__ );
457
458 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
459
460 $out = "";
461 $infoLine = $matches->getInfo();
462 if( !is_null($infoLine) ) {
463 $out .= "\n<!-- {$infoLine} -->\n";
464 }
465 $out .= "<ul class='mw-search-results'>\n";
466 while( $result = $matches->next() ) {
467 $out .= $this->showHit( $result, $terms );
468 }
469 $out .= "</ul>\n";
470
471 // convert the whole thing to desired language variant
472 $out = $wgContLang->convert( $out );
473 wfProfileOut( __METHOD__ );
474 return $out;
475 }
476
477 /**
478 * Format a single hit result
479 *
480 * @param $result SearchResult
481 * @param $terms Array: terms to highlight
482 */
483 protected function showHit( $result, $terms ) {
484 global $wgLang;
485 wfProfileIn( __METHOD__ );
486
487 if( $result->isBrokenTitle() ) {
488 wfProfileOut( __METHOD__ );
489 return "<!-- Broken link in search result -->\n";
490 }
491
492 $sk = $this->getSkin();
493 $t = $result->getTitle();
494
495 $titleSnippet = $result->getTitleSnippet($terms);
496
497 if( $titleSnippet == '' )
498 $titleSnippet = null;
499
500 $link_t = clone $t;
501
502 wfRunHooks( 'ShowSearchHitTitle',
503 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
504
505 $link = $this->sk->linkKnown(
506 $link_t,
507 $titleSnippet
508 );
509
510 //If page content is not readable, just return the title.
511 //This is not quite safe, but better than showing excerpts from non-readable pages
512 //Note that hiding the entry entirely would screw up paging.
513 if( !$t->userCanRead() ) {
514 wfProfileOut( __METHOD__ );
515 return "<li>{$link}</li>\n";
516 }
517
518 // If the page doesn't *exist*... our search index is out of date.
519 // The least confusing at this point is to drop the result.
520 // You may get less results, but... oh well. :P
521 if( $result->isMissingRevision() ) {
522 wfProfileOut( __METHOD__ );
523 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
524 }
525
526 // format redirects / relevant sections
527 $redirectTitle = $result->getRedirectTitle();
528 $redirectText = $result->getRedirectSnippet($terms);
529 $sectionTitle = $result->getSectionTitle();
530 $sectionText = $result->getSectionSnippet($terms);
531 $redirect = '';
532
533 if( !is_null($redirectTitle) ) {
534 if( $redirectText == '' )
535 $redirectText = null;
536
537 $redirect = "<span class='searchalttitle'>" .
538 wfMsg(
539 'search-redirect',
540 $this->sk->linkKnown(
541 $redirectTitle,
542 $redirectText
543 )
544 ) .
545 "</span>";
546 }
547
548 $section = '';
549
550 if( !is_null($sectionTitle) ) {
551 if( $sectionText == '' )
552 $sectionText = null;
553
554 $section = "<span class='searchalttitle'>" .
555 wfMsg(
556 'search-section', $this->sk->linkKnown(
557 $sectionTitle,
558 $sectionText
559 )
560 ) .
561 "</span>";
562 }
563
564 // format text extract
565 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
566
567 // format score
568 if( is_null( $result->getScore() ) ) {
569 // Search engine doesn't report scoring info
570 $score = '';
571 } else {
572 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
573 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
574 . ' - ';
575 }
576
577 // format description
578 $byteSize = $result->getByteSize();
579 $wordCount = $result->getWordCount();
580 $timestamp = $result->getTimestamp();
581 $size = wfMsgExt(
582 'search-result-size',
583 array( 'parsemag', 'escape' ),
584 $wgLang->formatSize( $byteSize ),
585 $wgLang->formatNum( $wordCount )
586 );
587
588 if( $t->getNamespace() == NS_CATEGORY ) {
589 $cat = Category::newFromTitle( $t );
590 $size = wfMsgExt(
591 'search-result-category-size',
592 array( 'parsemag', 'escape' ),
593 $wgLang->formatNum( $cat->getPageCount() ),
594 $wgLang->formatNum( $cat->getSubcatCount() ),
595 $wgLang->formatNum( $cat->getFileCount() )
596 );
597 }
598
599 $date = $wgLang->timeanddate( $timestamp );
600
601 // link to related articles if supported
602 $related = '';
603 if( $result->hasRelated() ) {
604 $st = SpecialPage::getTitleFor( 'Search' );
605 $stParams = array_merge(
606 $this->powerSearchOptions(),
607 array(
608 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
609 'fulltext' => wfMsg( 'search' )
610 )
611 );
612
613 $related = ' -- ' . $sk->linkKnown(
614 $st,
615 wfMsg('search-relatedarticle'),
616 array(),
617 $stParams
618 );
619 }
620
621 // Include a thumbnail for media files...
622 if( $t->getNamespace() == NS_FILE ) {
623 $img = wfFindFile( $t );
624 if( $img ) {
625 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
626 if( $thumb ) {
627 $desc = wfMsg( 'parentheses', $img->getShortDesc() );
628 wfProfileOut( __METHOD__ );
629 // Float doesn't seem to interact well with the bullets.
630 // Table messes up vertical alignment of the bullets.
631 // Bullets are therefore disabled (didn't look great anyway).
632 return "<li>" .
633 '<table class="searchResultImage">' .
634 '<tr>' .
635 '<td width="120" align="center" valign="top">' .
636 $thumb->toHtml( array( 'desc-link' => true ) ) .
637 '</td>' .
638 '<td valign="top">' .
639 $link .
640 $extract .
641 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
642 '</td>' .
643 '</tr>' .
644 '</table>' .
645 "</li>\n";
646 }
647 }
648 }
649
650 wfProfileOut( __METHOD__ );
651 return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
652 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
653 "</li>\n";
654
655 }
656
657 /**
658 * Show results from other wikis
659 *
660 * @param $matches SearchResultSet
661 * @param $query String
662 */
663 protected function showInterwiki( &$matches, $query ) {
664 global $wgContLang;
665 wfProfileIn( __METHOD__ );
666 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
667
668 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
669 wfMsg('search-interwiki-caption')."</div>\n";
670 $out .= "<ul class='mw-search-iwresults'>\n";
671
672 // work out custom project captions
673 $customCaptions = array();
674 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
675 foreach($customLines as $line) {
676 $parts = explode(":",$line,2);
677 if(count($parts) == 2) // validate line
678 $customCaptions[$parts[0]] = $parts[1];
679 }
680
681 $prev = null;
682 while( $result = $matches->next() ) {
683 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
684 $prev = $result->getInterwikiPrefix();
685 }
686 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
687 $out .= "</ul></div>\n";
688
689 // convert the whole thing to desired language variant
690 $out = $wgContLang->convert( $out );
691 wfProfileOut( __METHOD__ );
692 return $out;
693 }
694
695 /**
696 * Show single interwiki link
697 *
698 * @param $result SearchResult
699 * @param $lastInterwiki String
700 * @param $terms Array
701 * @param $query String
702 * @param $customCaptions Array: iw prefix -> caption
703 */
704 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
705 wfProfileIn( __METHOD__ );
706
707 if( $result->isBrokenTitle() ) {
708 wfProfileOut( __METHOD__ );
709 return "<!-- Broken link in search result -->\n";
710 }
711
712 $t = $result->getTitle();
713
714 $titleSnippet = $result->getTitleSnippet($terms);
715
716 if( $titleSnippet == '' )
717 $titleSnippet = null;
718
719 $link = $this->sk->linkKnown(
720 $t,
721 $titleSnippet
722 );
723
724 // format redirect if any
725 $redirectTitle = $result->getRedirectTitle();
726 $redirectText = $result->getRedirectSnippet($terms);
727 $redirect = '';
728 if( !is_null($redirectTitle) ) {
729 if( $redirectText == '' )
730 $redirectText = null;
731
732 $redirect = "<span class='searchalttitle'>" .
733 wfMsg(
734 'search-redirect',
735 $this->sk->linkKnown(
736 $redirectTitle,
737 $redirectText
738 )
739 ) .
740 "</span>";
741 }
742
743 $out = "";
744 // display project name
745 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
746 if( key_exists($t->getInterwiki(),$customCaptions) )
747 // captions from 'search-interwiki-custom'
748 $caption = $customCaptions[$t->getInterwiki()];
749 else{
750 // default is to show the hostname of the other wiki which might suck
751 // if there are many wikis on one hostname
752 $parsed = parse_url($t->getFullURL());
753 $caption = wfMsg('search-interwiki-default', $parsed['host']);
754 }
755 // "more results" link (special page stuff could be localized, but we might not know target lang)
756 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
757 $searchLink = $this->sk->linkKnown(
758 $searchTitle,
759 wfMsg('search-interwiki-more'),
760 array(),
761 array(
762 'search' => $query,
763 'fulltext' => 'Search'
764 )
765 );
766 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
767 {$searchLink}</span>{$caption}</div>\n<ul>";
768 }
769
770 $out .= "<li>{$link} {$redirect}</li>\n";
771 wfProfileOut( __METHOD__ );
772 return $out;
773 }
774
775 protected function getProfileForm( $profile, $term ) {
776 // Hidden stuff
777 $opts = array();
778 $opts['redirs'] = $this->searchRedirects;
779 $opts['profile'] = $this->profile;
780
781 if ( $profile === 'advanced' ) {
782 return $this->powerSearchBox( $term, $opts );
783 } else {
784 $form = '';
785 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
786 return $form;
787 }
788 }
789
790 /**
791 * Generates the power search box at [[Special:Search]]
792 *
793 * @param $term String: search term
794 * @return String: HTML form
795 */
796 protected function powerSearchBox( $term, $opts ) {
797 // Groups namespaces into rows according to subject
798 $rows = array();
799 foreach( SearchEngine::searchableNamespaces() as $namespace => $name ) {
800 $subject = MWNamespace::getSubject( $namespace );
801 if( !array_key_exists( $subject, $rows ) ) {
802 $rows[$subject] = "";
803 }
804 $name = str_replace( '_', ' ', $name );
805 if( $name == '' ) {
806 $name = wfMsg( 'blanknamespace' );
807 }
808 $rows[$subject] .=
809 Xml::openElement(
810 'td', array( 'style' => 'white-space: nowrap' )
811 ) .
812 Xml::checkLabel(
813 $name,
814 "ns{$namespace}",
815 "mw-search-ns{$namespace}",
816 in_array( $namespace, $this->namespaces )
817 ) .
818 Xml::closeElement( 'td' );
819 }
820 $rows = array_values( $rows );
821 $numRows = count( $rows );
822
823 // Lays out namespaces in multiple floating two-column tables so they'll
824 // be arranged nicely while still accommodating different screen widths
825 $namespaceTables = '';
826 for( $i = 0; $i < $numRows; $i += 4 ) {
827 $namespaceTables .= Xml::openElement(
828 'table',
829 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
830 );
831 for( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
832 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
833 }
834 $namespaceTables .= Xml::closeElement( 'table' );
835 }
836 // Show redirects check only if backend supports it
837 $redirects = '';
838 if( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
839 $redirects =
840 Xml::checkLabel( wfMsg( 'powersearch-redir' ), 'redirs', 'redirs', $this->searchRedirects );
841 }
842
843 $hidden = '';
844 unset( $opts['redirs'] );
845 foreach( $opts as $key => $value ) {
846 $hidden .= Html::hidden( $key, $value );
847 }
848 // Return final output
849 return
850 Xml::openElement(
851 'fieldset',
852 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
853 ) .
854 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
855 Xml::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
856 Xml::tags(
857 'div',
858 array( 'id' => 'mw-search-togglebox' ),
859 Xml::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
860 Xml::element(
861 'input',
862 array(
863 'type'=>'button',
864 'id' => 'mw-search-toggleall',
865 'value' => wfMsg( 'powersearch-toggleall' )
866 )
867 ) .
868 Xml::element(
869 'input',
870 array(
871 'type'=>'button',
872 'id' => 'mw-search-togglenone',
873 'value' => wfMsg( 'powersearch-togglenone' )
874 )
875 )
876 ) .
877 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
878 $namespaceTables .
879 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
880 $redirects . $hidden .
881 Xml::closeElement( 'fieldset' );
882 }
883
884 protected function getSearchProfiles() {
885 // Builds list of Search Types (profiles)
886 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
887
888 $profiles = array(
889 'default' => array(
890 'message' => 'searchprofile-articles',
891 'tooltip' => 'searchprofile-articles-tooltip',
892 'namespaces' => SearchEngine::defaultNamespaces(),
893 'namespace-messages' => SearchEngine::namespacesAsText(
894 SearchEngine::defaultNamespaces()
895 ),
896 ),
897 'images' => array(
898 'message' => 'searchprofile-images',
899 'tooltip' => 'searchprofile-images-tooltip',
900 'namespaces' => array( NS_FILE ),
901 ),
902 'help' => array(
903 'message' => 'searchprofile-project',
904 'tooltip' => 'searchprofile-project-tooltip',
905 'namespaces' => SearchEngine::helpNamespaces(),
906 'namespace-messages' => SearchEngine::namespacesAsText(
907 SearchEngine::helpNamespaces()
908 ),
909 ),
910 'all' => array(
911 'message' => 'searchprofile-everything',
912 'tooltip' => 'searchprofile-everything-tooltip',
913 'namespaces' => $nsAllSet,
914 ),
915 'advanced' => array(
916 'message' => 'searchprofile-advanced',
917 'tooltip' => 'searchprofile-advanced-tooltip',
918 'namespaces' => self::NAMESPACES_CURRENT,
919 )
920 );
921
922 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
923
924 foreach( $profiles as &$data ) {
925 if ( !is_array( $data['namespaces'] ) ) continue;
926 sort( $data['namespaces'] );
927 }
928
929 return $profiles;
930 }
931
932 protected function formHeader( $term, $resultsShown, $totalNum ) {
933 global $wgLang;
934
935 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
936
937 $bareterm = $term;
938 if( $this->startsWithImage( $term ) ) {
939 // Deletes prefixes
940 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
941 }
942
943 $profiles = $this->getSearchProfiles();
944
945 // Outputs XML for Search Types
946 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
947 $out .= Xml::openElement( 'ul' );
948 foreach ( $profiles as $id => $profile ) {
949 if ( !isset( $profile['parameters'] ) ) {
950 $profile['parameters'] = array();
951 }
952 $profile['parameters']['profile'] = $id;
953
954 $tooltipParam = isset( $profile['namespace-messages'] ) ?
955 $wgLang->commaList( $profile['namespace-messages'] ) : null;
956 $out .= Xml::tags(
957 'li',
958 array(
959 'class' => $this->profile === $id ? 'current' : 'normal'
960 ),
961 $this->makeSearchLink(
962 $bareterm,
963 array(),
964 wfMsg( $profile['message'] ),
965 wfMsg( $profile['tooltip'], $tooltipParam ),
966 $profile['parameters']
967 )
968 );
969 }
970 $out .= Xml::closeElement( 'ul' );
971 $out .= Xml::closeElement('div') ;
972
973 // Results-info
974 if ( $resultsShown > 0 ) {
975 if ( $totalNum > 0 ){
976 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
977 $wgLang->formatNum( $this->offset + 1 ),
978 $wgLang->formatNum( $this->offset + $resultsShown ),
979 $wgLang->formatNum( $totalNum ),
980 wfEscapeWikiText( $term ),
981 $wgLang->formatNum( $resultsShown )
982 );
983 } elseif ( $resultsShown >= $this->limit ) {
984 $top = wfShowingResults( $this->offset, $this->limit );
985 } else {
986 $top = wfMsgExt( 'showingresultsnum', array( 'parseinline' ),
987 $wgLang->formatNum( $this->limit ),
988 $wgLang->formatNum( $this->offset + 1 ),
989 $wgLang->formatNum( $resultsShown )
990 );
991 }
992 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
993 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
994 );
995 }
996
997 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
998 $out .= Xml::closeElement('div');
999
1000 return $out;
1001 }
1002
1003 protected function shortDialog( $term ) {
1004 $out = Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1005 // Term box
1006 $out .= Html::input( 'search', $term, 'search', array(
1007 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1008 'size' => '50',
1009 'autofocus'
1010 ) ) . "\n";
1011 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1012 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
1013 return $out . $this->didYouMeanHtml;
1014 }
1015
1016 /**
1017 * Make a search link with some target namespaces
1018 *
1019 * @param $term String
1020 * @param $namespaces Array ignored
1021 * @param $label String: link's text
1022 * @param $tooltip String: link's tooltip
1023 * @param $params Array: query string parameters
1024 * @return String: HTML fragment
1025 */
1026 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1027 $opt = $params;
1028 foreach( $namespaces as $n ) {
1029 $opt['ns' . $n] = 1;
1030 }
1031 $opt['redirs'] = $this->searchRedirects;
1032
1033 $stParams = array_merge(
1034 array(
1035 'search' => $term,
1036 'fulltext' => wfMsg( 'search' )
1037 ),
1038 $opt
1039 );
1040
1041 return Xml::element(
1042 'a',
1043 array(
1044 'href' => $this->getTitle()->getLocalURL( $stParams ),
1045 'title' => $tooltip),
1046 $label
1047 );
1048 }
1049
1050 /**
1051 * Check if query starts with image: prefix
1052 *
1053 * @param $term String: the string to check
1054 * @return Boolean
1055 */
1056 protected function startsWithImage( $term ) {
1057 global $wgContLang;
1058
1059 $p = explode( ':', $term );
1060 if( count( $p ) > 1 ) {
1061 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1062 }
1063 return false;
1064 }
1065
1066 /**
1067 * Check if query starts with all: prefix
1068 *
1069 * @param $term String: the string to check
1070 * @return Boolean
1071 */
1072 protected function startsWithAll( $term ) {
1073
1074 $allkeyword = wfMsgForContent('searchall');
1075
1076 $p = explode( ':', $term );
1077 if( count( $p ) > 1 ) {
1078 return $p[0] == $allkeyword;
1079 }
1080 return false;
1081 }
1082
1083 /**
1084 * @since 1.18
1085 */
1086 public function getSearchEngine() {
1087 if ( $this->searchEngine === null ) {
1088 $this->searchEngine = SearchEngine::create();
1089 }
1090 return $this->searchEngine;
1091 }
1092
1093 /**
1094 * Users of hook SpecialSearchSetupEngine can use this to
1095 * add more params to links to not lose selection when
1096 * user navigates search results.
1097 * @since 1.18
1098 */
1099 public function setExtraParam( $key, $value ) {
1100 $this->extraParams[$key] = $value;
1101 }
1102
1103 }