Only link local titles on Special:Search
[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 $redirect = '';
625
626 if ( !is_null( $redirectTitle ) ) {
627 if ( $redirectText == '' ) {
628 $redirectText = null;
629 }
630
631 $redirect = "<span class='searchalttitle'>" .
632 $this->msg( 'search-redirect' )->rawParams(
633 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
634 "</span>";
635 }
636
637 $section = '';
638
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 // format text extract
651 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
652
653 $lang = $this->getLanguage();
654
655 // format description
656 $byteSize = $result->getByteSize();
657 $wordCount = $result->getWordCount();
658 $timestamp = $result->getTimestamp();
659 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
660 ->numParams( $wordCount )->escaped();
661
662 if ( $title->getNamespace() == NS_CATEGORY ) {
663 $cat = Category::newFromTitle( $title );
664 $size = $this->msg( 'search-result-category-size' )
665 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
666 ->escaped();
667 }
668
669 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
670
671 $fileMatch = '';
672 // Include a thumbnail for media files...
673 if ( $title->getNamespace() == NS_FILE ) {
674 $img = $result->getFile();
675 $img = $img ?: wfFindFile( $title );
676 if ( $result->isFileMatch() ) {
677 $fileMatch = "<span class='searchalttitle'>" .
678 $this->msg( 'search-file-match' )->escaped() . "</span>";
679 }
680 if ( $img ) {
681 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
682 if ( $thumb ) {
683 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
684 // Float doesn't seem to interact well with the bullets.
685 // Table messes up vertical alignment of the bullets.
686 // Bullets are therefore disabled (didn't look great anyway).
687 return "<li>" .
688 '<table class="searchResultImage">' .
689 '<tr>' .
690 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
691 $thumb->toHtml( array( 'desc-link' => true ) ) .
692 '</td>' .
693 '<td style="vertical-align: top;">' .
694 "{$link} {$redirect} {$section} {$fileMatch}" .
695 $extract .
696 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
697 '</td>' .
698 '</tr>' .
699 '</table>' .
700 "</li>\n";
701 }
702 }
703 }
704
705 $html = null;
706
707 $score = '';
708 if ( wfRunHooks( 'ShowSearchHit', array(
709 $this, $result, $terms,
710 &$link, &$redirect, &$section, &$extract,
711 &$score, &$size, &$date, &$related,
712 &$html
713 ) ) ) {
714 $html = "<li><div class='mw-search-result-heading'>" .
715 "{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
716 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
717 "</li>\n";
718 }
719
720 return $html;
721 }
722
723 /**
724 * Show results from other wikis
725 *
726 * @param SearchResultSet|array $matches
727 * @param string $query
728 *
729 * @return string
730 */
731 protected function showInterwiki( $matches, $query ) {
732 global $wgContLang;
733 $profile = new ProfileSection( __METHOD__ );
734
735 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
736 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
737 $out .= "<ul class='mw-search-iwresults'>\n";
738
739 // work out custom project captions
740 $customCaptions = array();
741 // format per line <iwprefix>:<caption>
742 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
743 foreach ( $customLines as $line ) {
744 $parts = explode( ":", $line, 2 );
745 if ( count( $parts ) == 2 ) { // validate line
746 $customCaptions[$parts[0]] = $parts[1];
747 }
748 }
749
750 if ( !is_array( $matches ) ) {
751 $matches = array( $matches );
752 }
753
754 foreach ( $matches as $set ) {
755 $prev = null;
756 $result = $set->next();
757 while ( $result ) {
758 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
759 $prev = $result->getInterwikiPrefix();
760 $result = $set->next();
761 }
762 }
763
764 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
765 $out .= "</ul></div>\n";
766
767 // convert the whole thing to desired language variant
768 $out = $wgContLang->convert( $out );
769
770 return $out;
771 }
772
773 /**
774 * Show single interwiki link
775 *
776 * @param SearchResult $result
777 * @param string $lastInterwiki
778 * @param string $query
779 * @param array $customCaptions Interwiki prefix -> caption
780 *
781 * @return string
782 */
783 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
784 $profile = new ProfileSection( __METHOD__ );
785
786 if ( $result->isBrokenTitle() ) {
787 return '';
788 }
789
790 $title = $result->getTitle();
791
792 $titleSnippet = $result->getTitleSnippet();
793
794 if ( $titleSnippet == '' ) {
795 $titleSnippet = null;
796 }
797
798 $link = Linker::linkKnown(
799 $title,
800 $titleSnippet
801 );
802
803 // format redirect if any
804 $redirectTitle = $result->getRedirectTitle();
805 $redirectText = $result->getRedirectSnippet();
806 $redirect = '';
807 if ( !is_null( $redirectTitle ) ) {
808 if ( $redirectText == '' ) {
809 $redirectText = null;
810 }
811
812 $redirect = "<span class='searchalttitle'>" .
813 $this->msg( 'search-redirect' )->rawParams(
814 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
815 "</span>";
816 }
817
818 $out = "";
819 // display project name
820 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
821 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
822 // captions from 'search-interwiki-custom'
823 $caption = $customCaptions[$title->getInterwiki()];
824 } else {
825 // default is to show the hostname of the other wiki which might suck
826 // if there are many wikis on one hostname
827 $parsed = wfParseUrl( $title->getFullURL() );
828 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
829 }
830 // "more results" link (special page stuff could be localized, but we might not know target lang)
831 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
832 $searchLink = Linker::linkKnown(
833 $searchTitle,
834 $this->msg( 'search-interwiki-more' )->text(),
835 array(),
836 array(
837 'search' => $query,
838 'fulltext' => 'Search'
839 )
840 );
841 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
842 {$searchLink}</span>{$caption}</div>\n<ul>";
843 }
844
845 $out .= "<li>{$link} {$redirect}</li>\n";
846
847 return $out;
848 }
849
850 /**
851 * Generates the power search box at [[Special:Search]]
852 *
853 * @param string $term Search term
854 * @param array $opts
855 * @return string HTML form
856 */
857 protected function powerSearchBox( $term, $opts ) {
858 global $wgContLang;
859
860 // Groups namespaces into rows according to subject
861 $rows = array();
862 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
863 $subject = MWNamespace::getSubject( $namespace );
864 if ( !array_key_exists( $subject, $rows ) ) {
865 $rows[$subject] = "";
866 }
867
868 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
869 if ( $name == '' ) {
870 $name = $this->msg( 'blanknamespace' )->text();
871 }
872
873 $rows[$subject] .=
874 Xml::openElement( 'td' ) .
875 Xml::checkLabel(
876 $name,
877 "ns{$namespace}",
878 "mw-search-ns{$namespace}",
879 in_array( $namespace, $this->namespaces )
880 ) .
881 Xml::closeElement( 'td' );
882 }
883
884 $rows = array_values( $rows );
885 $numRows = count( $rows );
886
887 // Lays out namespaces in multiple floating two-column tables so they'll
888 // be arranged nicely while still accommodating different screen widths
889 $namespaceTables = '';
890 for ( $i = 0; $i < $numRows; $i += 4 ) {
891 $namespaceTables .= Xml::openElement(
892 'table',
893 array( 'cellpadding' => 0, 'cellspacing' => 0 )
894 );
895
896 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
897 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
898 }
899
900 $namespaceTables .= Xml::closeElement( 'table' );
901 }
902
903 $showSections = array( 'namespaceTables' => $namespaceTables );
904
905 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
906
907 $hidden = '';
908 foreach ( $opts as $key => $value ) {
909 $hidden .= Html::hidden( $key, $value );
910 }
911
912 # Stuff to feed saveNamespaces()
913 $remember = '';
914 $user = $this->getUser();
915 if ( $user->isLoggedIn() ) {
916 $remember .= Xml::checkLabel(
917 wfMessage( 'powersearch-remember' )->text(),
918 'nsRemember',
919 'mw-search-powersearch-remember',
920 false,
921 // The token goes here rather than in a hidden field so it
922 // is only sent when necessary (not every form submission).
923 array( 'value' => $user->getEditToken(
924 'searchnamespace',
925 $this->getRequest()
926 ) )
927 );
928 }
929
930 // Return final output
931 return Xml::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
932 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
933 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
934 Xml::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
935 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
936 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
937 $hidden .
938 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
939 $remember .
940 Xml::closeElement( 'fieldset' );
941 }
942
943 /**
944 * @return array
945 */
946 protected function getSearchProfiles() {
947 // Builds list of Search Types (profiles)
948 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
949
950 $profiles = array(
951 'default' => array(
952 'message' => 'searchprofile-articles',
953 'tooltip' => 'searchprofile-articles-tooltip',
954 'namespaces' => SearchEngine::defaultNamespaces(),
955 'namespace-messages' => SearchEngine::namespacesAsText(
956 SearchEngine::defaultNamespaces()
957 ),
958 ),
959 'images' => array(
960 'message' => 'searchprofile-images',
961 'tooltip' => 'searchprofile-images-tooltip',
962 'namespaces' => array( NS_FILE ),
963 ),
964 'all' => array(
965 'message' => 'searchprofile-everything',
966 'tooltip' => 'searchprofile-everything-tooltip',
967 'namespaces' => $nsAllSet,
968 ),
969 'advanced' => array(
970 'message' => 'searchprofile-advanced',
971 'tooltip' => 'searchprofile-advanced-tooltip',
972 'namespaces' => self::NAMESPACES_CURRENT,
973 )
974 );
975
976 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
977
978 foreach ( $profiles as &$data ) {
979 if ( !is_array( $data['namespaces'] ) ) {
980 continue;
981 }
982 sort( $data['namespaces'] );
983 }
984
985 return $profiles;
986 }
987
988 /**
989 * @param string $term
990 * @return string
991 */
992 protected function formHeader( $term ) {
993 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
994
995 $bareterm = $term;
996 if ( $this->startsWithImage( $term ) ) {
997 // Deletes prefixes
998 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
999 }
1000
1001 $profiles = $this->getSearchProfiles();
1002 $lang = $this->getLanguage();
1003
1004 // Outputs XML for Search Types
1005 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1006 $out .= Xml::openElement( 'ul' );
1007 foreach ( $profiles as $id => $profile ) {
1008 if ( !isset( $profile['parameters'] ) ) {
1009 $profile['parameters'] = array();
1010 }
1011 $profile['parameters']['profile'] = $id;
1012
1013 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1014 $lang->commaList( $profile['namespace-messages'] ) : null;
1015 $out .= Xml::tags(
1016 'li',
1017 array(
1018 'class' => $this->profile === $id ? 'current' : 'normal'
1019 ),
1020 $this->makeSearchLink(
1021 $bareterm,
1022 array(),
1023 $this->msg( $profile['message'] )->text(),
1024 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1025 $profile['parameters']
1026 )
1027 );
1028 }
1029 $out .= Xml::closeElement( 'ul' );
1030 $out .= Xml::closeElement( 'div' );
1031 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1032 $out .= Xml::closeElement( 'div' );
1033
1034 // Hidden stuff
1035 $opts = array();
1036 $opts['profile'] = $this->profile;
1037
1038 if ( $this->profile === 'advanced' ) {
1039 $out .= $this->powerSearchBox( $term, $opts );
1040 } else {
1041 $form = '';
1042 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile, $term, $opts ) );
1043 $out .= $form;
1044 }
1045
1046 return $out;
1047 }
1048
1049 /**
1050 * @param string $term
1051 * @param int $resultsShown
1052 * @param int $totalNum
1053 * @return string
1054 */
1055 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1056 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1057 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1058 // Term box
1059 $out .= Html::input( 'search', $term, 'search', array(
1060 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1061 'size' => '50',
1062 'autofocus',
1063 'class' => 'mw-ui-input mw-ui-input-inline',
1064 ) ) . "\n";
1065 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1066 $out .= Html::submitButton(
1067 $this->msg( 'searchbutton' )->text(),
1068 array(), array( 'mw-ui-progressive' )
1069 ) . "\n";
1070
1071 // Results-info
1072 if ( $totalNum > 0 && $this->offset < $totalNum ) {
1073 $top = $this->msg( 'search-showingresults' )
1074 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1075 ->numParams( $resultsShown )
1076 ->parse();
1077 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1078 Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1079 }
1080
1081 return $out . $this->didYouMeanHtml;
1082 }
1083
1084 /**
1085 * Make a search link with some target namespaces
1086 *
1087 * @param string $term
1088 * @param array $namespaces Ignored
1089 * @param string $label Link's text
1090 * @param string $tooltip Link's tooltip
1091 * @param array $params Query string parameters
1092 * @return string HTML fragment
1093 */
1094 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1095 $opt = $params;
1096 foreach ( $namespaces as $n ) {
1097 $opt['ns' . $n] = 1;
1098 }
1099
1100 $stParams = array_merge(
1101 array(
1102 'search' => $term,
1103 'fulltext' => $this->msg( 'search' )->text()
1104 ),
1105 $opt
1106 );
1107
1108 return Xml::element(
1109 'a',
1110 array(
1111 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1112 'title' => $tooltip
1113 ),
1114 $label
1115 );
1116 }
1117
1118 /**
1119 * Check if query starts with image: prefix
1120 *
1121 * @param string $term The string to check
1122 * @return bool
1123 */
1124 protected function startsWithImage( $term ) {
1125 global $wgContLang;
1126
1127 $parts = explode( ':', $term );
1128 if ( count( $parts ) > 1 ) {
1129 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1130 }
1131
1132 return false;
1133 }
1134
1135 /**
1136 * Check if query starts with all: prefix
1137 *
1138 * @param string $term The string to check
1139 * @return bool
1140 */
1141 protected function startsWithAll( $term ) {
1142
1143 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1144
1145 $parts = explode( ':', $term );
1146 if ( count( $parts ) > 1 ) {
1147 return $parts[0] == $allkeyword;
1148 }
1149
1150 return false;
1151 }
1152
1153 /**
1154 * @since 1.18
1155 *
1156 * @return SearchEngine
1157 */
1158 public function getSearchEngine() {
1159 if ( $this->searchEngine === null ) {
1160 $this->searchEngine = $this->searchEngineType ?
1161 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1162 }
1163
1164 return $this->searchEngine;
1165 }
1166
1167 /**
1168 * Current search profile.
1169 * @return null|string
1170 */
1171 function getProfile() {
1172 return $this->profile;
1173 }
1174
1175 /**
1176 * Current namespaces.
1177 * @return array
1178 */
1179 function getNamespaces() {
1180 return $this->namespaces;
1181 }
1182
1183 /**
1184 * Users of hook SpecialSearchSetupEngine can use this to
1185 * add more params to links to not lose selection when
1186 * user navigates search results.
1187 * @since 1.18
1188 *
1189 * @param string $key
1190 * @param mixed $value
1191 */
1192 public function setExtraParam( $key, $value ) {
1193 $this->extraParams[$key] = $value;
1194 }
1195
1196 protected function getGroupName() {
1197 return 'pages';
1198 }
1199 }