Special:Watchlist: Add user preference to "Show last" options, fix float comparison
[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 if ( Hooks::run( 'ShowSearchHit', array(
857 $this, $result, $terms,
858 &$link, &$redirect, &$section, &$extract,
859 &$score, &$size, &$date, &$related,
860 &$html
861 ) ) ) {
862 $html = "<li><div class='mw-search-result-heading'>" .
863 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
864 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
865 "</li>\n";
866 }
867
868 return $html;
869 }
870
871 /**
872 * Extract custom captions from search-interwiki-custom message
873 */
874 protected function getCustomCaptions() {
875 if ( is_null( $this->customCaptions ) ) {
876 $this->customCaptions = array();
877 // format per line <iwprefix>:<caption>
878 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
879 foreach ( $customLines as $line ) {
880 $parts = explode( ":", $line, 2 );
881 if ( count( $parts ) == 2 ) { // validate line
882 $this->customCaptions[$parts[0]] = $parts[1];
883 }
884 }
885 }
886 }
887
888 /**
889 * Show results from other wikis
890 *
891 * @param SearchResultSet|array $matches
892 * @param string $query
893 *
894 * @return string
895 */
896 protected function showInterwiki( $matches, $query ) {
897 global $wgContLang;
898
899 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
900 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
901 $out .= "<ul class='mw-search-iwresults'>\n";
902
903 // work out custom project captions
904 $this->getCustomCaptions();
905
906 if ( !is_array( $matches ) ) {
907 $matches = array( $matches );
908 }
909
910 foreach ( $matches as $set ) {
911 $prev = null;
912 $result = $set->next();
913 while ( $result ) {
914 $out .= $this->showInterwikiHit( $result, $prev, $query );
915 $prev = $result->getInterwikiPrefix();
916 $result = $set->next();
917 }
918 }
919
920 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
921 $out .= "</ul></div>\n";
922
923 // convert the whole thing to desired language variant
924 $out = $wgContLang->convert( $out );
925
926 return $out;
927 }
928
929 /**
930 * Show single interwiki link
931 *
932 * @param SearchResult $result
933 * @param string $lastInterwiki
934 * @param string $query
935 *
936 * @return string
937 */
938 protected function showInterwikiHit( $result, $lastInterwiki, $query ) {
939
940 if ( $result->isBrokenTitle() ) {
941 return '';
942 }
943
944 $title = $result->getTitle();
945
946 $titleSnippet = $result->getTitleSnippet();
947
948 if ( $titleSnippet == '' ) {
949 $titleSnippet = null;
950 }
951
952 $link = Linker::linkKnown(
953 $title,
954 $titleSnippet
955 );
956
957 // format redirect if any
958 $redirectTitle = $result->getRedirectTitle();
959 $redirectText = $result->getRedirectSnippet();
960 $redirect = '';
961 if ( !is_null( $redirectTitle ) ) {
962 if ( $redirectText == '' ) {
963 $redirectText = null;
964 }
965
966 $redirect = "<span class='searchalttitle'>" .
967 $this->msg( 'search-redirect' )->rawParams(
968 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
969 "</span>";
970 }
971
972 $out = "";
973 // display project name
974 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
975 if ( array_key_exists( $title->getInterwiki(), $this->customCaptions ) ) {
976 // captions from 'search-interwiki-custom'
977 $caption = $this->customCaptions[$title->getInterwiki()];
978 } else {
979 // default is to show the hostname of the other wiki which might suck
980 // if there are many wikis on one hostname
981 $parsed = wfParseUrl( $title->getFullURL() );
982 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
983 }
984 // "more results" link (special page stuff could be localized, but we might not know target lang)
985 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
986 $searchLink = Linker::linkKnown(
987 $searchTitle,
988 $this->msg( 'search-interwiki-more' )->text(),
989 array(),
990 array(
991 'search' => $query,
992 'fulltext' => 'Search'
993 )
994 );
995 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
996 {$searchLink}</span>{$caption}</div>\n<ul>";
997 }
998
999 $out .= "<li>{$link} {$redirect}</li>\n";
1000
1001 return $out;
1002 }
1003
1004 /**
1005 * Generates the power search box at [[Special:Search]]
1006 *
1007 * @param string $term Search term
1008 * @param array $opts
1009 * @return string HTML form
1010 */
1011 protected function powerSearchBox( $term, $opts ) {
1012 global $wgContLang;
1013
1014 // Groups namespaces into rows according to subject
1015 $rows = array();
1016 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
1017 $subject = MWNamespace::getSubject( $namespace );
1018 if ( !array_key_exists( $subject, $rows ) ) {
1019 $rows[$subject] = "";
1020 }
1021
1022 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
1023 if ( $name == '' ) {
1024 $name = $this->msg( 'blanknamespace' )->text();
1025 }
1026
1027 $rows[$subject] .=
1028 Xml::openElement( 'td' ) .
1029 Xml::checkLabel(
1030 $name,
1031 "ns{$namespace}",
1032 "mw-search-ns{$namespace}",
1033 in_array( $namespace, $this->namespaces )
1034 ) .
1035 Xml::closeElement( 'td' );
1036 }
1037
1038 $rows = array_values( $rows );
1039 $numRows = count( $rows );
1040
1041 // Lays out namespaces in multiple floating two-column tables so they'll
1042 // be arranged nicely while still accommodating different screen widths
1043 $namespaceTables = '';
1044 for ( $i = 0; $i < $numRows; $i += 4 ) {
1045 $namespaceTables .= Xml::openElement( 'table' );
1046
1047 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
1048 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
1049 }
1050
1051 $namespaceTables .= Xml::closeElement( 'table' );
1052 }
1053
1054 $showSections = array( 'namespaceTables' => $namespaceTables );
1055
1056 Hooks::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
1057
1058 $hidden = '';
1059 foreach ( $opts as $key => $value ) {
1060 $hidden .= Html::hidden( $key, $value );
1061 }
1062
1063 # Stuff to feed saveNamespaces()
1064 $remember = '';
1065 $user = $this->getUser();
1066 if ( $user->isLoggedIn() ) {
1067 $remember .= Xml::checkLabel(
1068 $this->msg( 'powersearch-remember' )->text(),
1069 'nsRemember',
1070 'mw-search-powersearch-remember',
1071 false,
1072 // The token goes here rather than in a hidden field so it
1073 // is only sent when necessary (not every form submission).
1074 array( 'value' => $user->getEditToken(
1075 'searchnamespace',
1076 $this->getRequest()
1077 ) )
1078 );
1079 }
1080
1081 // Return final output
1082 return Xml::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
1083 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1084 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1085 Xml::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
1086 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
1087 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1088 $hidden .
1089 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
1090 $remember .
1091 Xml::closeElement( 'fieldset' );
1092 }
1093
1094 /**
1095 * @return array
1096 */
1097 protected function getSearchProfiles() {
1098 // Builds list of Search Types (profiles)
1099 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
1100
1101 $profiles = array(
1102 'default' => array(
1103 'message' => 'searchprofile-articles',
1104 'tooltip' => 'searchprofile-articles-tooltip',
1105 'namespaces' => SearchEngine::defaultNamespaces(),
1106 'namespace-messages' => SearchEngine::namespacesAsText(
1107 SearchEngine::defaultNamespaces()
1108 ),
1109 ),
1110 'images' => array(
1111 'message' => 'searchprofile-images',
1112 'tooltip' => 'searchprofile-images-tooltip',
1113 'namespaces' => array( NS_FILE ),
1114 ),
1115 'all' => array(
1116 'message' => 'searchprofile-everything',
1117 'tooltip' => 'searchprofile-everything-tooltip',
1118 'namespaces' => $nsAllSet,
1119 ),
1120 'advanced' => array(
1121 'message' => 'searchprofile-advanced',
1122 'tooltip' => 'searchprofile-advanced-tooltip',
1123 'namespaces' => self::NAMESPACES_CURRENT,
1124 )
1125 );
1126
1127 Hooks::run( 'SpecialSearchProfiles', array( &$profiles ) );
1128
1129 foreach ( $profiles as &$data ) {
1130 if ( !is_array( $data['namespaces'] ) ) {
1131 continue;
1132 }
1133 sort( $data['namespaces'] );
1134 }
1135
1136 return $profiles;
1137 }
1138
1139 /**
1140 * @param string $term
1141 * @return string
1142 */
1143 protected function searchProfileTabs( $term ) {
1144 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1145
1146 $bareterm = $term;
1147 if ( $this->startsWithImage( $term ) ) {
1148 // Deletes prefixes
1149 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1150 }
1151
1152 $profiles = $this->getSearchProfiles();
1153 $lang = $this->getLanguage();
1154
1155 // Outputs XML for Search Types
1156 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1157 $out .= Xml::openElement( 'ul' );
1158 foreach ( $profiles as $id => $profile ) {
1159 if ( !isset( $profile['parameters'] ) ) {
1160 $profile['parameters'] = array();
1161 }
1162 $profile['parameters']['profile'] = $id;
1163
1164 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1165 $lang->commaList( $profile['namespace-messages'] ) : null;
1166 $out .= Xml::tags(
1167 'li',
1168 array(
1169 'class' => $this->profile === $id ? 'current' : 'normal'
1170 ),
1171 $this->makeSearchLink(
1172 $bareterm,
1173 array(),
1174 $this->msg( $profile['message'] )->text(),
1175 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1176 $profile['parameters']
1177 )
1178 );
1179 }
1180 $out .= Xml::closeElement( 'ul' );
1181 $out .= Xml::closeElement( 'div' );
1182 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1183 $out .= Xml::closeElement( 'div' );
1184
1185 return $out;
1186 }
1187
1188 /**
1189 * @param string $term Search term
1190 * @return string
1191 */
1192 protected function searchOptions( $term ) {
1193 $out = '';
1194 $opts = array();
1195 $opts['profile'] = $this->profile;
1196
1197 if ( $this->isPowerSearch() ) {
1198 $out .= $this->powerSearchBox( $term, $opts );
1199 } else {
1200 $form = '';
1201 Hooks::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile, $term, $opts ) );
1202 $out .= $form;
1203 }
1204
1205 return $out;
1206 }
1207
1208 /**
1209 * @param string $term
1210 * @param int $resultsShown
1211 * @param int $totalNum
1212 * @return string
1213 */
1214 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1215 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1216 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1217 // Term box
1218 $out .= Html::input( 'search', $term, 'search', array(
1219 'id' => $this->isPowerSearch() ? 'powerSearchText' : 'searchText',
1220 'size' => '50',
1221 'autofocus' => trim( $term ) === '',
1222 'class' => 'mw-ui-input mw-ui-input-inline',
1223 ) ) . "\n";
1224 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1225 $out .= Html::submitButton(
1226 $this->msg( 'searchbutton' )->text(),
1227 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1228 array( 'mw-ui-progressive' )
1229 ) . "\n";
1230
1231 // Results-info
1232 if ( $totalNum > 0 && $this->offset < $totalNum ) {
1233 $top = $this->msg( 'search-showingresults' )
1234 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1235 ->numParams( $resultsShown )
1236 ->parse();
1237 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1238 Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1239 }
1240
1241 return $out;
1242 }
1243
1244 /**
1245 * Make a search link with some target namespaces
1246 *
1247 * @param string $term
1248 * @param array $namespaces Ignored
1249 * @param string $label Link's text
1250 * @param string $tooltip Link's tooltip
1251 * @param array $params Query string parameters
1252 * @return string HTML fragment
1253 */
1254 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1255 $opt = $params;
1256 foreach ( $namespaces as $n ) {
1257 $opt['ns' . $n] = 1;
1258 }
1259
1260 $stParams = array_merge(
1261 array(
1262 'search' => $term,
1263 'fulltext' => $this->msg( 'search' )->text()
1264 ),
1265 $opt
1266 );
1267
1268 return Xml::element(
1269 'a',
1270 array(
1271 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1272 'title' => $tooltip
1273 ),
1274 $label
1275 );
1276 }
1277
1278 /**
1279 * Check if query starts with image: prefix
1280 *
1281 * @param string $term The string to check
1282 * @return bool
1283 */
1284 protected function startsWithImage( $term ) {
1285 global $wgContLang;
1286
1287 $parts = explode( ':', $term );
1288 if ( count( $parts ) > 1 ) {
1289 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1290 }
1291
1292 return false;
1293 }
1294
1295 /**
1296 * Check if query starts with all: prefix
1297 *
1298 * @param string $term The string to check
1299 * @return bool
1300 */
1301 protected function startsWithAll( $term ) {
1302
1303 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1304
1305 $parts = explode( ':', $term );
1306 if ( count( $parts ) > 1 ) {
1307 return $parts[0] == $allkeyword;
1308 }
1309
1310 return false;
1311 }
1312
1313 /**
1314 * @since 1.18
1315 *
1316 * @return SearchEngine
1317 */
1318 public function getSearchEngine() {
1319 if ( $this->searchEngine === null ) {
1320 $this->searchEngine = $this->searchEngineType ?
1321 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1322 }
1323
1324 return $this->searchEngine;
1325 }
1326
1327 /**
1328 * Current search profile.
1329 * @return null|string
1330 */
1331 function getProfile() {
1332 return $this->profile;
1333 }
1334
1335 /**
1336 * Current namespaces.
1337 * @return array
1338 */
1339 function getNamespaces() {
1340 return $this->namespaces;
1341 }
1342
1343 /**
1344 * Users of hook SpecialSearchSetupEngine can use this to
1345 * add more params to links to not lose selection when
1346 * user navigates search results.
1347 * @since 1.18
1348 *
1349 * @param string $key
1350 * @param mixed $value
1351 */
1352 public function setExtraParam( $key, $value ) {
1353 $this->extraParams[$key] = $value;
1354 }
1355
1356 protected function getGroupName() {
1357 return 'pages';
1358 }
1359 }