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