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