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