d308681d8f9b8c1630b28702b0fdeee32338d91c
[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 htmlspecialchars( $textStatus->getWikiText( '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->userCan( '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 if ( $n >= 0 ) {
544 $user->setOption( 'searchNs' . $n, false );
545 }
546 }
547 // The request parameters include all the namespaces we just searched.
548 // Even if they're the same as an existing profile, they're not eaten.
549 foreach ( $this->namespaces as $n ) {
550 $user->setOption( 'searchNs' . $n, true );
551 }
552
553 $user->saveSettings();
554 return true;
555 }
556
557 return false;
558 }
559
560 /**
561 * Show whole set of results
562 *
563 * @param SearchResultSet $matches
564 *
565 * @return string
566 */
567 protected function showMatches( &$matches ) {
568 global $wgContLang;
569
570 $profile = new ProfileSection( __METHOD__ );
571 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
572
573 $out = "<ul class='mw-search-results'>\n";
574 $result = $matches->next();
575 $count = 0;
576 while ( $result && $count < $this->limit ) {
577 $out .= $this->showHit( $result, $terms );
578 $result = $matches->next();
579 $count++;
580 }
581 $out .= "</ul>\n";
582
583 // convert the whole thing to desired language variant
584 $out = $wgContLang->convert( $out );
585
586 return $out;
587 }
588
589 /**
590 * Format a single hit result
591 *
592 * @param SearchResult $result
593 * @param array $terms Terms to highlight
594 *
595 * @return string
596 */
597 protected function showHit( $result, $terms ) {
598 $profile = new ProfileSection( __METHOD__ );
599
600 if ( $result->isBrokenTitle() ) {
601 return '';
602 }
603
604 $title = $result->getTitle();
605
606 $titleSnippet = $result->getTitleSnippet( $terms );
607
608 if ( $titleSnippet == '' ) {
609 $titleSnippet = null;
610 }
611
612 $link_t = clone $title;
613
614 wfRunHooks( 'ShowSearchHitTitle',
615 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
616
617 $link = Linker::linkKnown(
618 $link_t,
619 $titleSnippet
620 );
621
622 //If page content is not readable, just return the title.
623 //This is not quite safe, but better than showing excerpts from non-readable pages
624 //Note that hiding the entry entirely would screw up paging.
625 if ( !$title->userCan( 'read', $this->getUser() ) ) {
626 return "<li>{$link}</li>\n";
627 }
628
629 // If the page doesn't *exist*... our search index is out of date.
630 // The least confusing at this point is to drop the result.
631 // You may get less results, but... oh well. :P
632 if ( $result->isMissingRevision() ) {
633 return '';
634 }
635
636 // format redirects / relevant sections
637 $redirectTitle = $result->getRedirectTitle();
638 $redirectText = $result->getRedirectSnippet( $terms );
639 $sectionTitle = $result->getSectionTitle();
640 $sectionText = $result->getSectionSnippet( $terms );
641 $redirect = '';
642
643 if ( !is_null( $redirectTitle ) ) {
644 if ( $redirectText == '' ) {
645 $redirectText = null;
646 }
647
648 $redirect = "<span class='searchalttitle'>" .
649 $this->msg( 'search-redirect' )->rawParams(
650 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
651 "</span>";
652 }
653
654 $section = '';
655
656 if ( !is_null( $sectionTitle ) ) {
657 if ( $sectionText == '' ) {
658 $sectionText = null;
659 }
660
661 $section = "<span class='searchalttitle'>" .
662 $this->msg( 'search-section' )->rawParams(
663 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
664 "</span>";
665 }
666
667 // format text extract
668 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
669
670 $lang = $this->getLanguage();
671
672 // format score
673 if ( is_null( $result->getScore() ) ) {
674 // Search engine doesn't report scoring info
675 $score = '';
676 } else {
677 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
678 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
679 . ' - ';
680 }
681
682 // format description
683 $byteSize = $result->getByteSize();
684 $wordCount = $result->getWordCount();
685 $timestamp = $result->getTimestamp();
686 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
687 ->numParams( $wordCount )->escaped();
688
689 if ( $title->getNamespace() == NS_CATEGORY ) {
690 $cat = Category::newFromTitle( $title );
691 $size = $this->msg( 'search-result-category-size' )
692 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
693 ->escaped();
694 }
695
696 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
697
698 // link to related articles if supported
699 $related = '';
700 if ( $result->hasRelated() ) {
701 $stParams = array_merge(
702 $this->powerSearchOptions(),
703 array(
704 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
705 ':' . $title->getPrefixedText(),
706 'fulltext' => $this->msg( 'search' )->text()
707 )
708 );
709
710 $related = ' -- ' . Linker::linkKnown(
711 $this->getPageTitle(),
712 $this->msg( 'search-relatedarticle' )->text(),
713 array(),
714 $stParams
715 );
716 }
717
718 $fileMatch = '';
719 // Include a thumbnail for media files...
720 if ( $title->getNamespace() == NS_FILE ) {
721 $img = $result->getFile();
722 $img = $img ?: wfFindFile( $title );
723 if ( $result->isFileMatch() ) {
724 $fileMatch = "<span class='searchalttitle'>" .
725 $this->msg( 'search-file-match' )->escaped() . "</span>";
726 }
727 if ( $img ) {
728 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
729 if ( $thumb ) {
730 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
731 // Float doesn't seem to interact well with the bullets.
732 // Table messes up vertical alignment of the bullets.
733 // Bullets are therefore disabled (didn't look great anyway).
734 return "<li>" .
735 '<table class="searchResultImage">' .
736 '<tr>' .
737 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
738 $thumb->toHtml( array( 'desc-link' => true ) ) .
739 '</td>' .
740 '<td style="vertical-align: top;">' .
741 "{$link} {$fileMatch}" .
742 $extract .
743 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
744 '</td>' .
745 '</tr>' .
746 '</table>' .
747 "</li>\n";
748 }
749 }
750 }
751
752 $html = null;
753
754 if ( wfRunHooks( 'ShowSearchHit', array(
755 $this, $result, $terms,
756 &$link, &$redirect, &$section, &$extract,
757 &$score, &$size, &$date, &$related,
758 &$html
759 ) ) ) {
760 $html = "<li><div class='mw-search-result-heading'>" .
761 "{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
762 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
763 "</li>\n";
764 }
765
766 return $html;
767 }
768
769 /**
770 * Show results from other wikis
771 *
772 * @param SearchResultSet|array $matches
773 * @param string $query
774 *
775 * @return string
776 */
777 protected function showInterwiki( $matches, $query ) {
778 global $wgContLang;
779 $profile = new ProfileSection( __METHOD__ );
780
781 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
782 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
783 $out .= "<ul class='mw-search-iwresults'>\n";
784
785 // work out custom project captions
786 $customCaptions = array();
787 // format per line <iwprefix>:<caption>
788 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
789 foreach ( $customLines as $line ) {
790 $parts = explode( ":", $line, 2 );
791 if ( count( $parts ) == 2 ) { // validate line
792 $customCaptions[$parts[0]] = $parts[1];
793 }
794 }
795
796 if ( !is_array( $matches ) ) {
797 $matches = array( $matches );
798 }
799
800 foreach ( $matches as $set ) {
801 $prev = null;
802 $result = $set->next();
803 while ( $result ) {
804 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
805 $prev = $result->getInterwikiPrefix();
806 $result = $set->next();
807 }
808 }
809
810 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
811 $out .= "</ul></div>\n";
812
813 // convert the whole thing to desired language variant
814 $out = $wgContLang->convert( $out );
815
816 return $out;
817 }
818
819 /**
820 * Show single interwiki link
821 *
822 * @param SearchResult $result
823 * @param string $lastInterwiki
824 * @param string $query
825 * @param array $customCaptions iw prefix -> caption
826 *
827 * @return string
828 */
829 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
830 $profile = new ProfileSection( __METHOD__ );
831
832 if ( $result->isBrokenTitle() ) {
833 return '';
834 }
835
836 $title = $result->getTitle();
837
838 $titleSnippet = $result->getTitleSnippet();
839
840 if ( $titleSnippet == '' ) {
841 $titleSnippet = null;
842 }
843
844 $link = Linker::linkKnown(
845 $title,
846 $titleSnippet
847 );
848
849 // format redirect if any
850 $redirectTitle = $result->getRedirectTitle();
851 $redirectText = $result->getRedirectSnippet();
852 $redirect = '';
853 if ( !is_null( $redirectTitle ) ) {
854 if ( $redirectText == '' ) {
855 $redirectText = null;
856 }
857
858 $redirect = "<span class='searchalttitle'>" .
859 $this->msg( 'search-redirect' )->rawParams(
860 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
861 "</span>";
862 }
863
864 $out = "";
865 // display project name
866 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
867 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
868 // captions from 'search-interwiki-custom'
869 $caption = $customCaptions[$title->getInterwiki()];
870 } else {
871 // default is to show the hostname of the other wiki which might suck
872 // if there are many wikis on one hostname
873 $parsed = wfParseUrl( $title->getFullURL() );
874 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
875 }
876 // "more results" link (special page stuff could be localized, but we might not know target lang)
877 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
878 $searchLink = Linker::linkKnown(
879 $searchTitle,
880 $this->msg( 'search-interwiki-more' )->text(),
881 array(),
882 array(
883 'search' => $query,
884 'fulltext' => 'Search'
885 )
886 );
887 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
888 {$searchLink}</span>{$caption}</div>\n<ul>";
889 }
890
891 $out .= "<li>{$link} {$redirect}</li>\n";
892
893 return $out;
894 }
895
896 /**
897 * @param string $profile
898 * @param string $term
899 * @return string
900 */
901 protected function getProfileForm( $profile, $term ) {
902 // Hidden stuff
903 $opts = array();
904 $opts['profile'] = $this->profile;
905
906 if ( $profile === 'advanced' ) {
907 return $this->powerSearchBox( $term, $opts );
908 } else {
909 $form = '';
910 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
911
912 return $form;
913 }
914 }
915
916 /**
917 * Generates the power search box at [[Special:Search]]
918 *
919 * @param string $term Search term
920 * @param array $opts
921 * @return string HTML form
922 */
923 protected function powerSearchBox( $term, $opts ) {
924 global $wgContLang;
925
926 // Groups namespaces into rows according to subject
927 $rows = array();
928 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
929 $subject = MWNamespace::getSubject( $namespace );
930 if ( !array_key_exists( $subject, $rows ) ) {
931 $rows[$subject] = "";
932 }
933
934 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
935 if ( $name == '' ) {
936 $name = $this->msg( 'blanknamespace' )->text();
937 }
938
939 $rows[$subject] .=
940 Xml::openElement(
941 'td', array( 'style' => 'white-space: nowrap' )
942 ) .
943 Xml::checkLabel(
944 $name,
945 "ns{$namespace}",
946 "mw-search-ns{$namespace}",
947 in_array( $namespace, $this->namespaces )
948 ) .
949 Xml::closeElement( 'td' );
950 }
951
952 $rows = array_values( $rows );
953 $numRows = count( $rows );
954
955 // Lays out namespaces in multiple floating two-column tables so they'll
956 // be arranged nicely while still accommodating different screen widths
957 $namespaceTables = '';
958 for ( $i = 0; $i < $numRows; $i += 4 ) {
959 $namespaceTables .= Xml::openElement(
960 'table',
961 array( 'cellpadding' => 0, 'cellspacing' => 0 )
962 );
963
964 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
965 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
966 }
967
968 $namespaceTables .= Xml::closeElement( 'table' );
969 }
970
971 $showSections = array( 'namespaceTables' => $namespaceTables );
972
973 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
974
975 $hidden = '';
976 foreach ( $opts as $key => $value ) {
977 $hidden .= Html::hidden( $key, $value );
978 }
979
980 # Stuff to feed saveNamespaces()
981 $remember = '';
982 $user = $this->getUser();
983 if ( $user->isLoggedIn() ) {
984 $remember .= Html::hidden( 'nsToken', $user->getEditToken() ) .
985 Xml::checkLabel(
986 wfMessage( 'powersearch-remember' )->text(),
987 'nsRemember',
988 'mw-search-powersearch-remember',
989 false
990 );
991 }
992
993 // Return final output
994 return Xml::openElement(
995 'fieldset',
996 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
997 ) .
998 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
999 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1000 Html::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
1001 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
1002 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1003 $hidden .
1004 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
1005 $remember .
1006 Xml::closeElement( 'fieldset' );
1007 }
1008
1009 /**
1010 * @return array
1011 */
1012 protected function getSearchProfiles() {
1013 // Builds list of Search Types (profiles)
1014 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
1015
1016 $profiles = array(
1017 'default' => array(
1018 'message' => 'searchprofile-articles',
1019 'tooltip' => 'searchprofile-articles-tooltip',
1020 'namespaces' => SearchEngine::defaultNamespaces(),
1021 'namespace-messages' => SearchEngine::namespacesAsText(
1022 SearchEngine::defaultNamespaces()
1023 ),
1024 ),
1025 'images' => array(
1026 'message' => 'searchprofile-images',
1027 'tooltip' => 'searchprofile-images-tooltip',
1028 'namespaces' => array( NS_FILE ),
1029 ),
1030 'all' => array(
1031 'message' => 'searchprofile-everything',
1032 'tooltip' => 'searchprofile-everything-tooltip',
1033 'namespaces' => $nsAllSet,
1034 ),
1035 'advanced' => array(
1036 'message' => 'searchprofile-advanced',
1037 'tooltip' => 'searchprofile-advanced-tooltip',
1038 'namespaces' => self::NAMESPACES_CURRENT,
1039 )
1040 );
1041
1042 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1043
1044 foreach ( $profiles as &$data ) {
1045 if ( !is_array( $data['namespaces'] ) ) {
1046 continue;
1047 }
1048 sort( $data['namespaces'] );
1049 }
1050
1051 return $profiles;
1052 }
1053
1054 /**
1055 * @param string $term
1056 * @param int $resultsShown
1057 * @param int $totalNum
1058 * @return string
1059 */
1060 protected function formHeader( $term, $resultsShown, $totalNum ) {
1061 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1062
1063 $bareterm = $term;
1064 if ( $this->startsWithImage( $term ) ) {
1065 // Deletes prefixes
1066 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1067 }
1068
1069 $profiles = $this->getSearchProfiles();
1070 $lang = $this->getLanguage();
1071
1072 // Outputs XML for Search Types
1073 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1074 $out .= Xml::openElement( 'ul' );
1075 foreach ( $profiles as $id => $profile ) {
1076 if ( !isset( $profile['parameters'] ) ) {
1077 $profile['parameters'] = array();
1078 }
1079 $profile['parameters']['profile'] = $id;
1080
1081 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1082 $lang->commaList( $profile['namespace-messages'] ) : null;
1083 $out .= Xml::tags(
1084 'li',
1085 array(
1086 'class' => $this->profile === $id ? 'current' : 'normal'
1087 ),
1088 $this->makeSearchLink(
1089 $bareterm,
1090 array(),
1091 $this->msg( $profile['message'] )->text(),
1092 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1093 $profile['parameters']
1094 )
1095 );
1096 }
1097 $out .= Xml::closeElement( 'ul' );
1098 $out .= Xml::closeElement( 'div' );
1099
1100 // Results-info
1101 if ( $resultsShown > 0 ) {
1102 if ( $totalNum > 0 ) {
1103 $top = $this->msg( 'showingresultsheader' )
1104 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1105 ->params( wfEscapeWikiText( $term ) )
1106 ->numParams( $resultsShown )
1107 ->parse();
1108 } elseif ( $resultsShown >= $this->limit ) {
1109 $top = $this->msg( 'showingresults' )
1110 ->numParams( $this->limit, $this->offset + 1 )
1111 ->parse();
1112 } else {
1113 $top = $this->msg( 'showingresultsnum' )
1114 ->numParams( $this->limit, $this->offset + 1, $resultsShown )
1115 ->parse();
1116 }
1117 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
1118 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
1119 );
1120 }
1121
1122 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1123 $out .= Xml::closeElement( 'div' );
1124
1125 return $out;
1126 }
1127
1128 /**
1129 * @param string $term
1130 * @return string
1131 */
1132 protected function shortDialog( $term ) {
1133 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1134 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1135 // Term box
1136 $out .= Html::input( 'search', $term, 'search', array(
1137 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1138 'size' => '50',
1139 'autofocus',
1140 'class' => 'mw-ui-input',
1141 ) ) . "\n";
1142 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1143 $out .= Xml::submitButton(
1144 $this->msg( 'searchbutton' )->text(),
1145 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1146 ) . "\n";
1147
1148 return $out . $this->didYouMeanHtml;
1149 }
1150
1151 /**
1152 * Make a search link with some target namespaces
1153 *
1154 * @param string $term
1155 * @param array $namespaces Ignored
1156 * @param string $label Link's text
1157 * @param string $tooltip Link's tooltip
1158 * @param array $params Query string parameters
1159 * @return string HTML fragment
1160 */
1161 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1162 $opt = $params;
1163 foreach ( $namespaces as $n ) {
1164 $opt['ns' . $n] = 1;
1165 }
1166
1167 $stParams = array_merge(
1168 array(
1169 'search' => $term,
1170 'fulltext' => $this->msg( 'search' )->text()
1171 ),
1172 $opt
1173 );
1174
1175 return Xml::element(
1176 'a',
1177 array(
1178 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1179 'title' => $tooltip
1180 ),
1181 $label
1182 );
1183 }
1184
1185 /**
1186 * Check if query starts with image: prefix
1187 *
1188 * @param string $term The string to check
1189 * @return bool
1190 */
1191 protected function startsWithImage( $term ) {
1192 global $wgContLang;
1193
1194 $parts = explode( ':', $term );
1195 if ( count( $parts ) > 1 ) {
1196 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1197 }
1198
1199 return false;
1200 }
1201
1202 /**
1203 * Check if query starts with all: prefix
1204 *
1205 * @param string $term The string to check
1206 * @return bool
1207 */
1208 protected function startsWithAll( $term ) {
1209
1210 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1211
1212 $parts = explode( ':', $term );
1213 if ( count( $parts ) > 1 ) {
1214 return $parts[0] == $allkeyword;
1215 }
1216
1217 return false;
1218 }
1219
1220 /**
1221 * @since 1.18
1222 *
1223 * @return SearchEngine
1224 */
1225 public function getSearchEngine() {
1226 if ( $this->searchEngine === null ) {
1227 $this->searchEngine = $this->searchEngineType ?
1228 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1229 }
1230
1231 return $this->searchEngine;
1232 }
1233
1234 /**
1235 * Current search profile.
1236 * @return null|string
1237 */
1238 function getProfile() {
1239 return $this->profile;
1240 }
1241
1242 /**
1243 * Current namespaces.
1244 * @return array
1245 */
1246 function getNamespaces() {
1247 return $this->namespaces;
1248 }
1249
1250 /**
1251 * Users of hook SpecialSearchSetupEngine can use this to
1252 * add more params to links to not lose selection when
1253 * user navigates search results.
1254 * @since 1.18
1255 *
1256 * @param string $key
1257 * @param mixed $value
1258 */
1259 public function setExtraParam( $key, $value ) {
1260 $this->extraParams[$key] = $value;
1261 }
1262
1263 protected function getGroupName() {
1264 return 'pages';
1265 }
1266 }