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