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