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