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