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