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