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