Export mw.Message's string formatter as mw.format
[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 /**
32 * Current search profile. Search profile is just a name that identifies
33 * the active search tab on the search page (content, discussions...)
34 * For users tt replaces the set of enabled namespaces from the query
35 * string when applicable. Extensions can add new profiles with hooks
36 * with custom search options just for that profile.
37 * @var null|string
38 */
39 protected $profile;
40
41 /** @var SearchEngine Search engine */
42 protected $searchEngine;
43
44 /** @var string Search engine type, if not default */
45 protected $searchEngineType;
46
47 /** @var array For links */
48 protected $extraParams = array();
49
50 /** @var string No idea, apparently used by some other classes */
51 protected $mPrefix;
52
53 /**
54 * @var int
55 */
56 protected $limit, $offset;
57
58 /**
59 * @var array
60 */
61 protected $namespaces;
62
63 /**
64 * @var string
65 */
66 protected $fulltext;
67
68 const NAMESPACES_CURRENT = 'sense';
69
70 public function __construct() {
71 parent::__construct( 'Search' );
72 }
73
74 /**
75 * Entry point
76 *
77 * @param string $par
78 */
79 public function execute( $par ) {
80 $this->setHeaders();
81 $this->outputHeader();
82 $out = $this->getOutput();
83 $out->allowClickjacking();
84 $out->addModuleStyles( array(
85 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button',
86 'mediawiki.ui.input',
87 ) );
88
89 // Strip underscores from title parameter; most of the time we'll want
90 // text form here. But don't strip underscores from actual text params!
91 $titleParam = str_replace( '_', ' ', $par );
92
93 $request = $this->getRequest();
94
95 // Fetch the search term
96 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
97
98 $this->load();
99 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
100 $this->saveNamespaces();
101 // Remove the token from the URL to prevent the user from inadvertently
102 // exposing it (e.g. by pasting it into a public wiki page) or undoing
103 // later settings changes (e.g. by reloading the page).
104 $query = $request->getValues();
105 unset( $query['title'], $query['nsRemember'] );
106 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
107 return;
108 }
109
110 $this->searchEngineType = $request->getVal( 'srbackend' );
111
112 if ( $request->getVal( 'fulltext' )
113 || !is_null( $request->getVal( 'offset' ) )
114 ) {
115 $this->showResults( $search );
116 } else {
117 $this->goResult( $search );
118 }
119 }
120
121 /**
122 * Set up basic search parameters from the request and user settings.
123 *
124 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
125 */
126 public function load() {
127 $request = $this->getRequest();
128 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, '' );
129 $this->mPrefix = $request->getVal( 'prefix', '' );
130
131 $user = $this->getUser();
132
133 # Extract manually requested namespaces
134 $nslist = $this->powerSearch( $request );
135 if ( !count( $nslist ) ) {
136 # Fallback to user preference
137 $nslist = SearchEngine::userNamespaces( $user );
138 }
139
140 $profile = null;
141 if ( !count( $nslist ) ) {
142 $profile = 'default';
143 }
144
145 $profile = $request->getVal( 'profile', $profile );
146 $profiles = $this->getSearchProfiles();
147 if ( $profile === null ) {
148 // BC with old request format
149 $profile = 'advanced';
150 foreach ( $profiles as $key => $data ) {
151 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
152 $profile = $key;
153 }
154 }
155 $this->namespaces = $nslist;
156 } elseif ( $profile === 'advanced' ) {
157 $this->namespaces = $nslist;
158 } else {
159 if ( isset( $profiles[$profile]['namespaces'] ) ) {
160 $this->namespaces = $profiles[$profile]['namespaces'];
161 } else {
162 // Unknown profile requested
163 $profile = 'default';
164 $this->namespaces = $profiles['default']['namespaces'];
165 }
166 }
167
168 $this->fulltext = $request->getVal( 'fulltext' );
169 $this->profile = $profile;
170 }
171
172 /**
173 * If an exact title match can be found, jump straight ahead to it.
174 *
175 * @param string $term
176 */
177 public function goResult( $term ) {
178 $this->setupPage( $term );
179 # Try to go to page as entered.
180 $title = Title::newFromText( $term );
181 # If the string cannot be used to create a title
182 if ( is_null( $title ) ) {
183 $this->showResults( $term );
184
185 return;
186 }
187 # If there's an exact or very near match, jump right there.
188 $title = SearchEngine::getNearMatch( $term );
189
190 if ( !is_null( $title ) ) {
191 $this->getOutput()->redirect( $title->getFullURL() );
192
193 return;
194 }
195 # No match, generate an edit URL
196 $title = Title::newFromText( $term );
197 if ( !is_null( $title ) ) {
198 Hooks::run( 'SpecialSearchNogomatch', array( &$title ) );
199 }
200 $this->showResults( $term );
201 }
202
203 /**
204 * @param string $term
205 */
206 public function showResults( $term ) {
207 global $wgContLang;
208
209 $profile = new ProfileSection( __METHOD__ );
210 $search = $this->getSearchEngine();
211 $search->setLimitOffset( $this->limit, $this->offset );
212 $search->setNamespaces( $this->namespaces );
213 $search->prefix = $this->mPrefix;
214 $term = $search->transformSearchTerm( $term );
215 $didYouMeanHtml = '';
216
217 Hooks::run( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
218
219 $this->setupPage( $term );
220
221 $out = $this->getOutput();
222
223 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
224 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
225 if ( $searchFowardUrl ) {
226 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
227 $out->redirect( $url );
228 } else {
229 $out->addHTML(
230 Xml::openElement( 'fieldset' ) .
231 Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
232 Xml::element(
233 'p',
234 array( 'class' => 'mw-searchdisabled' ),
235 $this->msg( 'searchdisabled' )->text()
236 ) .
237 $this->msg( 'googlesearch' )->rawParams(
238 htmlspecialchars( $term ),
239 'UTF-8',
240 $this->msg( 'searchbutton' )->escaped()
241 )->text() .
242 Xml::closeElement( 'fieldset' )
243 );
244 }
245
246 return;
247 }
248
249 $title = Title::newFromText( $term );
250 $showSuggestion = $title === null || !$title->isKnown();
251 $search->setShowSuggestion( $showSuggestion );
252
253 // fetch search results
254 $rewritten = $search->replacePrefixes( $term );
255
256 $titleMatches = $search->searchTitle( $rewritten );
257 $textMatches = $search->searchText( $rewritten );
258
259 $textStatus = null;
260 if ( $textMatches instanceof Status ) {
261 $textStatus = $textMatches;
262 $textMatches = null;
263 }
264
265 // did you mean... suggestions
266 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
267 # mirror Go/Search behavior of original request ..
268 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
269
270 if ( $this->fulltext != null ) {
271 $didYouMeanParams['fulltext'] = $this->fulltext;
272 }
273
274 $stParams = array_merge(
275 $didYouMeanParams,
276 $this->powerSearchOptions()
277 );
278
279 $suggestionSnippet = $textMatches->getSuggestionSnippet();
280
281 if ( $suggestionSnippet == '' ) {
282 $suggestionSnippet = null;
283 }
284
285 $suggestLink = Linker::linkKnown(
286 $this->getPageTitle(),
287 $suggestionSnippet,
288 array(),
289 $stParams
290 );
291
292 # html of did you mean... search suggestion link
293 $didYouMeanHtml =
294 Xml::openElement( 'div', array( 'class' => 'searchdidyoumean' ) ) .
295 $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() .
296 Xml::closeElement( 'div' );
297 }
298
299 if ( !Hooks::run( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
300 # Hook requested termination
301 return;
302 }
303
304 // start rendering the page
305 $out->addHtml(
306 Xml::openElement(
307 'form',
308 array(
309 'id' => ( $this->isPowerSearch() ? 'powersearch' : 'search' ),
310 'method' => 'get',
311 'action' => wfScript(),
312 )
313 )
314 );
315
316 // Get number of results
317 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
318 if ( $titleMatches ) {
319 $titleMatchesNum = $titleMatches->numRows();
320 $numTitleMatches = $titleMatches->getTotalHits();
321 }
322 if ( $textMatches ) {
323 $textMatchesNum = $textMatches->numRows();
324 $numTextMatches = $textMatches->getTotalHits();
325 }
326 $num = $titleMatchesNum + $textMatchesNum;
327 $totalRes = $numTitleMatches + $numTextMatches;
328
329 $out->addHtml(
330 # This is an awful awful ID name. It's not a table, but we
331 # named it poorly from when this was a table so now we're
332 # stuck with it
333 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
334 $this->shortDialog( $term, $num, $totalRes ) .
335 Xml::closeElement( 'div' ) .
336 $this->searchProfileTabs( $term ) .
337 $this->searchOptions( $term ) .
338 Xml::closeElement( 'form' ) .
339 $didYouMeanHtml
340 );
341
342 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
343 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
344 // Empty query -- straight view of search form
345 return;
346 }
347
348 $out->addHtml( "<div class='searchresults'>" );
349
350 // prev/next links
351 $prevnext = null;
352 if ( $num || $this->offset ) {
353 // Show the create link ahead
354 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
355 if ( $totalRes > $this->limit || $this->offset ) {
356 if ( $this->searchEngineType !== null ) {
357 $this->setExtraParam( 'srbackend', $this->searchEngineType );
358 }
359 $prevnext = $this->getLanguage()->viewPrevNext(
360 $this->getPageTitle(),
361 $this->offset,
362 $this->limit,
363 $this->powerSearchOptions() + array( 'search' => $term ),
364 $this->limit + $this->offset >= $totalRes
365 );
366 }
367 }
368 Hooks::run( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
369
370 $out->parserOptions()->setEditSection( false );
371 if ( $titleMatches ) {
372 if ( $numTitleMatches > 0 ) {
373 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
374 $out->addHTML( $this->showMatches( $titleMatches ) );
375 }
376 $titleMatches->free();
377 }
378 if ( $textMatches && !$textStatus ) {
379 // output appropriate heading
380 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
381 // if no title matches the heading is redundant
382 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
383 }
384
385 // show interwiki results if any
386 if ( $textMatches->hasInterwikiResults() ) {
387 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
388 }
389 // show results
390 if ( $numTextMatches > 0 ) {
391 $out->addHTML( $this->showMatches( $textMatches ) );
392 }
393
394 $textMatches->free();
395 }
396 if ( $num === 0 ) {
397 if ( $textStatus ) {
398 $out->addHTML( '<div class="error">' .
399 $textStatus->getMessage( 'search-error' ) . '</div>' );
400 } else {
401 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
402 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
403 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
404 }
405 }
406 $out->addHtml( "</div>" );
407
408 if ( $prevnext ) {
409 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
410 }
411 }
412
413 /**
414 * @param Title $title
415 * @param int $num The number of search results found
416 * @param null|SearchResultSet $titleMatches Results from title search
417 * @param null|SearchResultSet $textMatches Results from text search
418 */
419 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
420 // show direct page/create link if applicable
421
422 // Check DBkey !== '' in case of fragment link only.
423 if ( is_null( $title ) || $title->getDBkey() === ''
424 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
425 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
426 ) {
427 // invalid title
428 // preserve the paragraph for margins etc...
429 $this->getOutput()->addHtml( '<p></p>' );
430
431 return;
432 }
433
434 $messageName = 'searchmenu-new-nocreate';
435 $linkClass = 'mw-search-createlink';
436
437 if ( !$title->isExternal() ) {
438 if ( $title->isKnown() ) {
439 $messageName = 'searchmenu-exists';
440 $linkClass = 'mw-search-exists';
441 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
442 $messageName = 'searchmenu-new';
443 }
444 }
445
446 $params = array(
447 $messageName,
448 wfEscapeWikiText( $title->getPrefixedText() ),
449 Message::numParam( $num )
450 );
451 Hooks::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
452
453 // Extensions using the hook might still return an empty $messageName
454 if ( $messageName ) {
455 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
456 } else {
457 // preserve the paragraph for margins etc...
458 $this->getOutput()->addHtml( '<p></p>' );
459 }
460 }
461
462 /**
463 * @param string $term
464 */
465 protected function setupPage( $term ) {
466 $out = $this->getOutput();
467 if ( strval( $term ) !== '' ) {
468 $out->setPageTitle( $this->msg( 'searchresults' ) );
469 $out->setHTMLTitle( $this->msg( 'pagetitle' )
470 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
471 ->inContentLanguage()->text()
472 );
473 }
474 // add javascript specific to special:search
475 $out->addModules( 'mediawiki.special.search' );
476 }
477
478 /**
479 * Return true if current search is a power (advanced) search
480 *
481 * @return bool
482 */
483 protected function isPowerSearch() {
484 return $this->profile === 'advanced';
485 }
486
487 /**
488 * Extract "power search" namespace settings from the request object,
489 * returning a list of index numbers to search.
490 *
491 * @param WebRequest $request
492 * @return array
493 */
494 protected function powerSearch( &$request ) {
495 $arr = array();
496 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
497 if ( $request->getCheck( 'ns' . $ns ) ) {
498 $arr[] = $ns;
499 }
500 }
501
502 return $arr;
503 }
504
505 /**
506 * Reconstruct the 'power search' options for links
507 *
508 * @return array
509 */
510 protected function powerSearchOptions() {
511 $opt = array();
512 if ( !$this->isPowerSearch() ) {
513 $opt['profile'] = $this->profile;
514 } else {
515 foreach ( $this->namespaces as $n ) {
516 $opt['ns' . $n] = 1;
517 }
518 }
519
520 return $opt + $this->extraParams;
521 }
522
523 /**
524 * Save namespace preferences when we're supposed to
525 *
526 * @return bool Whether we wrote something
527 */
528 protected function saveNamespaces() {
529 $user = $this->getUser();
530 $request = $this->getRequest();
531
532 if ( $user->isLoggedIn() &&
533 $user->matchEditToken(
534 $request->getVal( 'nsRemember' ),
535 'searchnamespace',
536 $request
537 )
538 ) {
539 // Reset namespace preferences: namespaces are not searched
540 // when they're not mentioned in the URL parameters.
541 foreach ( MWNamespace::getValidNamespaces() as $n ) {
542 $user->setOption( 'searchNs' . $n, false );
543 }
544 // The request parameters include all the namespaces to be searched.
545 // Even if they're the same as an existing profile, they're not eaten.
546 foreach ( $this->namespaces as $n ) {
547 $user->setOption( 'searchNs' . $n, true );
548 }
549
550 $user->saveSettings();
551 return true;
552 }
553
554 return false;
555 }
556
557 /**
558 * Show whole set of results
559 *
560 * @param SearchResultSet $matches
561 *
562 * @return string
563 */
564 protected function showMatches( &$matches ) {
565 global $wgContLang;
566
567 $profile = new ProfileSection( __METHOD__ );
568 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
569
570 $out = "<ul class='mw-search-results'>\n";
571 $result = $matches->next();
572 while ( $result ) {
573 $out .= $this->showHit( $result, $terms );
574 $result = $matches->next();
575 }
576 $out .= "</ul>\n";
577
578 // convert the whole thing to desired language variant
579 $out = $wgContLang->convert( $out );
580
581 return $out;
582 }
583
584 /**
585 * Format a single hit result
586 *
587 * @param SearchResult $result
588 * @param array $terms Terms to highlight
589 *
590 * @return string
591 */
592 protected function showHit( $result, $terms ) {
593 $profile = new ProfileSection( __METHOD__ );
594
595 if ( $result->isBrokenTitle() ) {
596 return '';
597 }
598
599 $title = $result->getTitle();
600
601 $titleSnippet = $result->getTitleSnippet();
602
603 if ( $titleSnippet == '' ) {
604 $titleSnippet = null;
605 }
606
607 $link_t = clone $title;
608
609 Hooks::run( 'ShowSearchHitTitle',
610 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
611
612 $link = Linker::linkKnown(
613 $link_t,
614 $titleSnippet
615 );
616
617 //If page content is not readable, just return the title.
618 //This is not quite safe, but better than showing excerpts from non-readable pages
619 //Note that hiding the entry entirely would screw up paging.
620 if ( !$title->userCan( 'read', $this->getUser() ) ) {
621 return "<li>{$link}</li>\n";
622 }
623
624 // If the page doesn't *exist*... our search index is out of date.
625 // The least confusing at this point is to drop the result.
626 // You may get less results, but... oh well. :P
627 if ( $result->isMissingRevision() ) {
628 return '';
629 }
630
631 // format redirects / relevant sections
632 $redirectTitle = $result->getRedirectTitle();
633 $redirectText = $result->getRedirectSnippet();
634 $sectionTitle = $result->getSectionTitle();
635 $sectionText = $result->getSectionSnippet();
636 $categorySnippet = $result->getCategorySnippet();
637
638 $redirect = '';
639 if ( !is_null( $redirectTitle ) ) {
640 if ( $redirectText == '' ) {
641 $redirectText = null;
642 }
643
644 $redirect = "<span class='searchalttitle'>" .
645 $this->msg( 'search-redirect' )->rawParams(
646 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
647 "</span>";
648 }
649
650 $section = '';
651 if ( !is_null( $sectionTitle ) ) {
652 if ( $sectionText == '' ) {
653 $sectionText = null;
654 }
655
656 $section = "<span class='searchalttitle'>" .
657 $this->msg( 'search-section' )->rawParams(
658 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
659 "</span>";
660 }
661
662 $category = '';
663 if ( $categorySnippet ) {
664 $category = "<span class='searchalttitle'>" .
665 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
666 "</span>";
667 }
668
669 // format text extract
670 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
671
672 $lang = $this->getLanguage();
673
674 // format description
675 $byteSize = $result->getByteSize();
676 $wordCount = $result->getWordCount();
677 $timestamp = $result->getTimestamp();
678 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
679 ->numParams( $wordCount )->escaped();
680
681 if ( $title->getNamespace() == NS_CATEGORY ) {
682 $cat = Category::newFromTitle( $title );
683 $size = $this->msg( 'search-result-category-size' )
684 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
685 ->escaped();
686 }
687
688 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
689
690 $fileMatch = '';
691 // Include a thumbnail for media files...
692 if ( $title->getNamespace() == NS_FILE ) {
693 $img = $result->getFile();
694 $img = $img ?: wfFindFile( $title );
695 if ( $result->isFileMatch() ) {
696 $fileMatch = "<span class='searchalttitle'>" .
697 $this->msg( 'search-file-match' )->escaped() . "</span>";
698 }
699 if ( $img ) {
700 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
701 if ( $thumb ) {
702 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
703 // Float doesn't seem to interact well with the bullets.
704 // Table messes up vertical alignment of the bullets.
705 // Bullets are therefore disabled (didn't look great anyway).
706 return "<li>" .
707 '<table class="searchResultImage">' .
708 '<tr>' .
709 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
710 $thumb->toHtml( array( 'desc-link' => true ) ) .
711 '</td>' .
712 '<td style="vertical-align: top;">' .
713 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
714 $extract .
715 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
716 '</td>' .
717 '</tr>' .
718 '</table>' .
719 "</li>\n";
720 }
721 }
722 }
723
724 $html = null;
725
726 $score = '';
727 if ( Hooks::run( 'ShowSearchHit', array(
728 $this, $result, $terms,
729 &$link, &$redirect, &$section, &$extract,
730 &$score, &$size, &$date, &$related,
731 &$html
732 ) ) ) {
733 $html = "<li><div class='mw-search-result-heading'>" .
734 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
735 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
736 "</li>\n";
737 }
738
739 return $html;
740 }
741
742 /**
743 * Show results from other wikis
744 *
745 * @param SearchResultSet|array $matches
746 * @param string $query
747 *
748 * @return string
749 */
750 protected function showInterwiki( $matches, $query ) {
751 global $wgContLang;
752 $profile = new ProfileSection( __METHOD__ );
753
754 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
755 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
756 $out .= "<ul class='mw-search-iwresults'>\n";
757
758 // work out custom project captions
759 $customCaptions = array();
760 // format per line <iwprefix>:<caption>
761 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
762 foreach ( $customLines as $line ) {
763 $parts = explode( ":", $line, 2 );
764 if ( count( $parts ) == 2 ) { // validate line
765 $customCaptions[$parts[0]] = $parts[1];
766 }
767 }
768
769 if ( !is_array( $matches ) ) {
770 $matches = array( $matches );
771 }
772
773 foreach ( $matches as $set ) {
774 $prev = null;
775 $result = $set->next();
776 while ( $result ) {
777 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
778 $prev = $result->getInterwikiPrefix();
779 $result = $set->next();
780 }
781 }
782
783 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
784 $out .= "</ul></div>\n";
785
786 // convert the whole thing to desired language variant
787 $out = $wgContLang->convert( $out );
788
789 return $out;
790 }
791
792 /**
793 * Show single interwiki link
794 *
795 * @param SearchResult $result
796 * @param string $lastInterwiki
797 * @param string $query
798 * @param array $customCaptions Interwiki prefix -> caption
799 *
800 * @return string
801 */
802 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
803 $profile = new ProfileSection( __METHOD__ );
804
805 if ( $result->isBrokenTitle() ) {
806 return '';
807 }
808
809 $title = $result->getTitle();
810
811 $titleSnippet = $result->getTitleSnippet();
812
813 if ( $titleSnippet == '' ) {
814 $titleSnippet = null;
815 }
816
817 $link = Linker::linkKnown(
818 $title,
819 $titleSnippet
820 );
821
822 // format redirect if any
823 $redirectTitle = $result->getRedirectTitle();
824 $redirectText = $result->getRedirectSnippet();
825 $redirect = '';
826 if ( !is_null( $redirectTitle ) ) {
827 if ( $redirectText == '' ) {
828 $redirectText = null;
829 }
830
831 $redirect = "<span class='searchalttitle'>" .
832 $this->msg( 'search-redirect' )->rawParams(
833 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
834 "</span>";
835 }
836
837 $out = "";
838 // display project name
839 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
840 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
841 // captions from 'search-interwiki-custom'
842 $caption = $customCaptions[$title->getInterwiki()];
843 } else {
844 // default is to show the hostname of the other wiki which might suck
845 // if there are many wikis on one hostname
846 $parsed = wfParseUrl( $title->getFullURL() );
847 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
848 }
849 // "more results" link (special page stuff could be localized, but we might not know target lang)
850 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
851 $searchLink = Linker::linkKnown(
852 $searchTitle,
853 $this->msg( 'search-interwiki-more' )->text(),
854 array(),
855 array(
856 'search' => $query,
857 'fulltext' => 'Search'
858 )
859 );
860 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
861 {$searchLink}</span>{$caption}</div>\n<ul>";
862 }
863
864 $out .= "<li>{$link} {$redirect}</li>\n";
865
866 return $out;
867 }
868
869 /**
870 * Generates the power search box at [[Special:Search]]
871 *
872 * @param string $term Search term
873 * @param array $opts
874 * @return string HTML form
875 */
876 protected function powerSearchBox( $term, $opts ) {
877 global $wgContLang;
878
879 // Groups namespaces into rows according to subject
880 $rows = array();
881 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
882 $subject = MWNamespace::getSubject( $namespace );
883 if ( !array_key_exists( $subject, $rows ) ) {
884 $rows[$subject] = "";
885 }
886
887 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
888 if ( $name == '' ) {
889 $name = $this->msg( 'blanknamespace' )->text();
890 }
891
892 $rows[$subject] .=
893 Xml::openElement( 'td' ) .
894 Xml::checkLabel(
895 $name,
896 "ns{$namespace}",
897 "mw-search-ns{$namespace}",
898 in_array( $namespace, $this->namespaces )
899 ) .
900 Xml::closeElement( 'td' );
901 }
902
903 $rows = array_values( $rows );
904 $numRows = count( $rows );
905
906 // Lays out namespaces in multiple floating two-column tables so they'll
907 // be arranged nicely while still accommodating different screen widths
908 $namespaceTables = '';
909 for ( $i = 0; $i < $numRows; $i += 4 ) {
910 $namespaceTables .= Xml::openElement( 'table' );
911
912 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
913 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
914 }
915
916 $namespaceTables .= Xml::closeElement( 'table' );
917 }
918
919 $showSections = array( 'namespaceTables' => $namespaceTables );
920
921 Hooks::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
922
923 $hidden = '';
924 foreach ( $opts as $key => $value ) {
925 $hidden .= Html::hidden( $key, $value );
926 }
927
928 # Stuff to feed saveNamespaces()
929 $remember = '';
930 $user = $this->getUser();
931 if ( $user->isLoggedIn() ) {
932 $remember .= Xml::checkLabel(
933 $this->msg( 'powersearch-remember' )->text(),
934 'nsRemember',
935 'mw-search-powersearch-remember',
936 false,
937 // The token goes here rather than in a hidden field so it
938 // is only sent when necessary (not every form submission).
939 array( 'value' => $user->getEditToken(
940 'searchnamespace',
941 $this->getRequest()
942 ) )
943 );
944 }
945
946 // Return final output
947 return Xml::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
948 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
949 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
950 Xml::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
951 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
952 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
953 $hidden .
954 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
955 $remember .
956 Xml::closeElement( 'fieldset' );
957 }
958
959 /**
960 * @return array
961 */
962 protected function getSearchProfiles() {
963 // Builds list of Search Types (profiles)
964 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
965
966 $profiles = array(
967 'default' => array(
968 'message' => 'searchprofile-articles',
969 'tooltip' => 'searchprofile-articles-tooltip',
970 'namespaces' => SearchEngine::defaultNamespaces(),
971 'namespace-messages' => SearchEngine::namespacesAsText(
972 SearchEngine::defaultNamespaces()
973 ),
974 ),
975 'images' => array(
976 'message' => 'searchprofile-images',
977 'tooltip' => 'searchprofile-images-tooltip',
978 'namespaces' => array( NS_FILE ),
979 ),
980 'all' => array(
981 'message' => 'searchprofile-everything',
982 'tooltip' => 'searchprofile-everything-tooltip',
983 'namespaces' => $nsAllSet,
984 ),
985 'advanced' => array(
986 'message' => 'searchprofile-advanced',
987 'tooltip' => 'searchprofile-advanced-tooltip',
988 'namespaces' => self::NAMESPACES_CURRENT,
989 )
990 );
991
992 Hooks::run( 'SpecialSearchProfiles', array( &$profiles ) );
993
994 foreach ( $profiles as &$data ) {
995 if ( !is_array( $data['namespaces'] ) ) {
996 continue;
997 }
998 sort( $data['namespaces'] );
999 }
1000
1001 return $profiles;
1002 }
1003
1004 /**
1005 * @param string $term
1006 * @return string
1007 */
1008 protected function searchProfileTabs( $term ) {
1009 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1010
1011 $bareterm = $term;
1012 if ( $this->startsWithImage( $term ) ) {
1013 // Deletes prefixes
1014 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1015 }
1016
1017 $profiles = $this->getSearchProfiles();
1018 $lang = $this->getLanguage();
1019
1020 // Outputs XML for Search Types
1021 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1022 $out .= Xml::openElement( 'ul' );
1023 foreach ( $profiles as $id => $profile ) {
1024 if ( !isset( $profile['parameters'] ) ) {
1025 $profile['parameters'] = array();
1026 }
1027 $profile['parameters']['profile'] = $id;
1028
1029 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1030 $lang->commaList( $profile['namespace-messages'] ) : null;
1031 $out .= Xml::tags(
1032 'li',
1033 array(
1034 'class' => $this->profile === $id ? 'current' : 'normal'
1035 ),
1036 $this->makeSearchLink(
1037 $bareterm,
1038 array(),
1039 $this->msg( $profile['message'] )->text(),
1040 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1041 $profile['parameters']
1042 )
1043 );
1044 }
1045 $out .= Xml::closeElement( 'ul' );
1046 $out .= Xml::closeElement( 'div' );
1047 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1048 $out .= Xml::closeElement( 'div' );
1049
1050 return $out;
1051 }
1052
1053 /**
1054 * @param string $term Search term
1055 * @return string
1056 */
1057 protected function searchOptions( $term ) {
1058 $out = '';
1059 $opts = array();
1060 $opts['profile'] = $this->profile;
1061
1062 if ( $this->isPowerSearch() ) {
1063 $out .= $this->powerSearchBox( $term, $opts );
1064 } else {
1065 $form = '';
1066 Hooks::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile, $term, $opts ) );
1067 $out .= $form;
1068 }
1069
1070 return $out;
1071 }
1072
1073 /**
1074 * @param string $term
1075 * @param int $resultsShown
1076 * @param int $totalNum
1077 * @return string
1078 */
1079 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1080 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1081 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1082 // Term box
1083 $out .= Html::input( 'search', $term, 'search', array(
1084 'id' => $this->isPowerSearch() ? 'powerSearchText' : 'searchText',
1085 'size' => '50',
1086 'autofocus' => trim( $term ) === '',
1087 'class' => 'mw-ui-input mw-ui-input-inline',
1088 ) ) . "\n";
1089 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1090 $out .= Html::submitButton(
1091 $this->msg( 'searchbutton' )->text(),
1092 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1093 array( 'mw-ui-progressive' )
1094 ) . "\n";
1095
1096 // Results-info
1097 if ( $totalNum > 0 && $this->offset < $totalNum ) {
1098 $top = $this->msg( 'search-showingresults' )
1099 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1100 ->numParams( $resultsShown )
1101 ->parse();
1102 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1103 Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1104 }
1105
1106 return $out;
1107 }
1108
1109 /**
1110 * Make a search link with some target namespaces
1111 *
1112 * @param string $term
1113 * @param array $namespaces Ignored
1114 * @param string $label Link's text
1115 * @param string $tooltip Link's tooltip
1116 * @param array $params Query string parameters
1117 * @return string HTML fragment
1118 */
1119 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1120 $opt = $params;
1121 foreach ( $namespaces as $n ) {
1122 $opt['ns' . $n] = 1;
1123 }
1124
1125 $stParams = array_merge(
1126 array(
1127 'search' => $term,
1128 'fulltext' => $this->msg( 'search' )->text()
1129 ),
1130 $opt
1131 );
1132
1133 return Xml::element(
1134 'a',
1135 array(
1136 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1137 'title' => $tooltip
1138 ),
1139 $label
1140 );
1141 }
1142
1143 /**
1144 * Check if query starts with image: prefix
1145 *
1146 * @param string $term The string to check
1147 * @return bool
1148 */
1149 protected function startsWithImage( $term ) {
1150 global $wgContLang;
1151
1152 $parts = explode( ':', $term );
1153 if ( count( $parts ) > 1 ) {
1154 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1155 }
1156
1157 return false;
1158 }
1159
1160 /**
1161 * Check if query starts with all: prefix
1162 *
1163 * @param string $term The string to check
1164 * @return bool
1165 */
1166 protected function startsWithAll( $term ) {
1167
1168 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1169
1170 $parts = explode( ':', $term );
1171 if ( count( $parts ) > 1 ) {
1172 return $parts[0] == $allkeyword;
1173 }
1174
1175 return false;
1176 }
1177
1178 /**
1179 * @since 1.18
1180 *
1181 * @return SearchEngine
1182 */
1183 public function getSearchEngine() {
1184 if ( $this->searchEngine === null ) {
1185 $this->searchEngine = $this->searchEngineType ?
1186 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1187 }
1188
1189 return $this->searchEngine;
1190 }
1191
1192 /**
1193 * Current search profile.
1194 * @return null|string
1195 */
1196 function getProfile() {
1197 return $this->profile;
1198 }
1199
1200 /**
1201 * Current namespaces.
1202 * @return array
1203 */
1204 function getNamespaces() {
1205 return $this->namespaces;
1206 }
1207
1208 /**
1209 * Users of hook SpecialSearchSetupEngine can use this to
1210 * add more params to links to not lose selection when
1211 * user navigates search results.
1212 * @since 1.18
1213 *
1214 * @param string $key
1215 * @param mixed $value
1216 */
1217 public function setExtraParam( $key, $value ) {
1218 $this->extraParams[$key] = $value;
1219 }
1220
1221 protected function getGroupName() {
1222 return 'pages';
1223 }
1224 }