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