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