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