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