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