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