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