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