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