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