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