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