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