541faa14a4d70b66ce6fcdee869cd2ddb77ca250
[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} {$redirect} {$section} {$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 Interwiki 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( 'td' ) .
897 Xml::checkLabel(
898 $name,
899 "ns{$namespace}",
900 "mw-search-ns{$namespace}",
901 in_array( $namespace, $this->namespaces )
902 ) .
903 Xml::closeElement( 'td' );
904 }
905
906 $rows = array_values( $rows );
907 $numRows = count( $rows );
908
909 // Lays out namespaces in multiple floating two-column tables so they'll
910 // be arranged nicely while still accommodating different screen widths
911 $namespaceTables = '';
912 for ( $i = 0; $i < $numRows; $i += 4 ) {
913 $namespaceTables .= Xml::openElement(
914 'table',
915 array( 'cellpadding' => 0, 'cellspacing' => 0 )
916 );
917
918 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
919 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
920 }
921
922 $namespaceTables .= Xml::closeElement( 'table' );
923 }
924
925 $showSections = array( 'namespaceTables' => $namespaceTables );
926
927 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
928
929 $hidden = '';
930 foreach ( $opts as $key => $value ) {
931 $hidden .= Html::hidden( $key, $value );
932 }
933
934 # Stuff to feed saveNamespaces()
935 $remember = '';
936 $user = $this->getUser();
937 if ( $user->isLoggedIn() ) {
938 $remember .= Html::hidden(
939 'nsToken',
940 $user->getEditToken(
941 'searchnamespace',
942 $this->getRequest()
943 )
944 ) .
945 Xml::checkLabel(
946 wfMessage( 'powersearch-remember' )->text(),
947 'nsRemember',
948 'mw-search-powersearch-remember',
949 false
950 );
951 }
952
953 // Return final output
954 return Xml::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
955 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
956 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
957 Html::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
958 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
959 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
960 $hidden .
961 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
962 $remember .
963 Xml::closeElement( 'fieldset' );
964 }
965
966 /**
967 * @return array
968 */
969 protected function getSearchProfiles() {
970 // Builds list of Search Types (profiles)
971 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
972
973 $profiles = array(
974 'default' => array(
975 'message' => 'searchprofile-articles',
976 'tooltip' => 'searchprofile-articles-tooltip',
977 'namespaces' => SearchEngine::defaultNamespaces(),
978 'namespace-messages' => SearchEngine::namespacesAsText(
979 SearchEngine::defaultNamespaces()
980 ),
981 ),
982 'images' => array(
983 'message' => 'searchprofile-images',
984 'tooltip' => 'searchprofile-images-tooltip',
985 'namespaces' => array( NS_FILE ),
986 ),
987 'all' => array(
988 'message' => 'searchprofile-everything',
989 'tooltip' => 'searchprofile-everything-tooltip',
990 'namespaces' => $nsAllSet,
991 ),
992 'advanced' => array(
993 'message' => 'searchprofile-advanced',
994 'tooltip' => 'searchprofile-advanced-tooltip',
995 'namespaces' => self::NAMESPACES_CURRENT,
996 )
997 );
998
999 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1000
1001 foreach ( $profiles as &$data ) {
1002 if ( !is_array( $data['namespaces'] ) ) {
1003 continue;
1004 }
1005 sort( $data['namespaces'] );
1006 }
1007
1008 return $profiles;
1009 }
1010
1011 /**
1012 * @param string $term
1013 * @return string
1014 */
1015 protected function formHeader( $term ) {
1016 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1017
1018 $bareterm = $term;
1019 if ( $this->startsWithImage( $term ) ) {
1020 // Deletes prefixes
1021 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1022 }
1023
1024 $profiles = $this->getSearchProfiles();
1025 $lang = $this->getLanguage();
1026
1027 // Outputs XML for Search Types
1028 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1029 $out .= Xml::openElement( 'ul' );
1030 foreach ( $profiles as $id => $profile ) {
1031 if ( !isset( $profile['parameters'] ) ) {
1032 $profile['parameters'] = array();
1033 }
1034 $profile['parameters']['profile'] = $id;
1035
1036 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1037 $lang->commaList( $profile['namespace-messages'] ) : null;
1038 $out .= Xml::tags(
1039 'li',
1040 array(
1041 'class' => $this->profile === $id ? 'current' : 'normal'
1042 ),
1043 $this->makeSearchLink(
1044 $bareterm,
1045 array(),
1046 $this->msg( $profile['message'] )->text(),
1047 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1048 $profile['parameters']
1049 )
1050 );
1051 }
1052 $out .= Xml::closeElement( 'ul' );
1053 $out .= Xml::closeElement( 'div' );
1054 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1055 $out .= Xml::closeElement( 'div' );
1056
1057 // Hidden stuff
1058 $opts = array();
1059 $opts['profile'] = $this->profile;
1060
1061 if ( $this->profile === 'advanced' ) {
1062 $out .= $this->powerSearchBox( $term, $opts );
1063 } else {
1064 $form = '';
1065 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile, $term, $opts ) );
1066 $out .= $form;
1067 }
1068
1069 return $out;
1070 }
1071
1072 /**
1073 * @param string $term
1074 * @return string
1075 */
1076 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1077 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1078 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1079 // Term box
1080 $out .= Html::input( 'search', $term, 'search', array(
1081 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1082 'size' => '50',
1083 'autofocus',
1084 'class' => 'mw-ui-input',
1085 ) ) . "\n";
1086 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1087 $out .= Xml::submitButton(
1088 $this->msg( 'searchbutton' )->text(),
1089 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1090 ) . "\n";
1091
1092 // Results-info
1093 if ( $totalNum > 0 ) {
1094 $top = $this->msg( 'showingresultsheader' )
1095 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1096 ->params( wfEscapeWikiText( $term ) )
1097 ->numParams( $resultsShown )
1098 ->parse();
1099 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1100 Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1101 }
1102
1103 return $out . $this->didYouMeanHtml;
1104 }
1105
1106 /**
1107 * Make a search link with some target namespaces
1108 *
1109 * @param string $term
1110 * @param array $namespaces Ignored
1111 * @param string $label Link's text
1112 * @param string $tooltip Link's tooltip
1113 * @param array $params Query string parameters
1114 * @return string HTML fragment
1115 */
1116 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1117 $opt = $params;
1118 foreach ( $namespaces as $n ) {
1119 $opt['ns' . $n] = 1;
1120 }
1121
1122 $stParams = array_merge(
1123 array(
1124 'search' => $term,
1125 'fulltext' => $this->msg( 'search' )->text()
1126 ),
1127 $opt
1128 );
1129
1130 return Xml::element(
1131 'a',
1132 array(
1133 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1134 'title' => $tooltip
1135 ),
1136 $label
1137 );
1138 }
1139
1140 /**
1141 * Check if query starts with image: prefix
1142 *
1143 * @param string $term The string to check
1144 * @return bool
1145 */
1146 protected function startsWithImage( $term ) {
1147 global $wgContLang;
1148
1149 $parts = explode( ':', $term );
1150 if ( count( $parts ) > 1 ) {
1151 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1152 }
1153
1154 return false;
1155 }
1156
1157 /**
1158 * Check if query starts with all: prefix
1159 *
1160 * @param string $term The string to check
1161 * @return bool
1162 */
1163 protected function startsWithAll( $term ) {
1164
1165 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1166
1167 $parts = explode( ':', $term );
1168 if ( count( $parts ) > 1 ) {
1169 return $parts[0] == $allkeyword;
1170 }
1171
1172 return false;
1173 }
1174
1175 /**
1176 * @since 1.18
1177 *
1178 * @return SearchEngine
1179 */
1180 public function getSearchEngine() {
1181 if ( $this->searchEngine === null ) {
1182 $this->searchEngine = $this->searchEngineType ?
1183 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1184 }
1185
1186 return $this->searchEngine;
1187 }
1188
1189 /**
1190 * Current search profile.
1191 * @return null|string
1192 */
1193 function getProfile() {
1194 return $this->profile;
1195 }
1196
1197 /**
1198 * Current namespaces.
1199 * @return array
1200 */
1201 function getNamespaces() {
1202 return $this->namespaces;
1203 }
1204
1205 /**
1206 * Users of hook SpecialSearchSetupEngine can use this to
1207 * add more params to links to not lose selection when
1208 * user navigates search results.
1209 * @since 1.18
1210 *
1211 * @param string $key
1212 * @param mixed $value
1213 */
1214 public function setExtraParam( $key, $value ) {
1215 $this->extraParams[$key] = $value;
1216 }
1217
1218 protected function getGroupName() {
1219 return 'pages';
1220 }
1221 }