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