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