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