Remove some unused globals
[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;
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 // prev/next links
263 if( $num || $this->offset ) {
264 // Show the create link ahead
265 $this->showCreateLink( $t );
266 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
267 SpecialPage::getTitleFor( 'Search' ),
268 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
269 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
270 );
271 //$wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
272 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
273 } else {
274 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
275 }
276
277 if( $titleMatches ) {
278 if( $numTitleMatches > 0 ) {
279 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
280 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
281 }
282 $titleMatches->free();
283 }
284 if( $textMatches ) {
285 // output appropriate heading
286 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
287 // if no title matches the heading is redundant
288 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
289 } elseif( $totalRes == 0 ) {
290 # Don't show the 'no text matches' if we received title matches
291 # $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
292 }
293 // show interwiki results if any
294 if( $textMatches->hasInterwikiResults() ) {
295 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
296 }
297 // show results
298 if( $numTextMatches > 0 ) {
299 $wgOut->addHTML( $this->showMatches( $textMatches ) );
300 }
301
302 $textMatches->free();
303 }
304 if( $num === 0 ) {
305 $wgOut->addWikiMsg( 'search-nonefound', wfEscapeWikiText( $term ) );
306 $this->showCreateLink( $t );
307 }
308 $wgOut->addHtml( "</div>" );
309 if( $num === 0 ) {
310 $wgOut->addHTML( $this->searchFocus() );
311 }
312
313 if( $num || $this->offset ) {
314 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
315 }
316 wfProfileOut( __METHOD__ );
317 }
318
319 protected function showCreateLink( $t ) {
320 global $wgOut;
321
322 // show direct page/create link
323 if( !is_null($t) ) {
324 if( !$t->isKnown() ) {
325 $wgOut->addWikiMsg( 'searchmenu-new', wfEscapeWikiText( $t->getPrefixedText() ) );
326 } else {
327 $wgOut->addWikiMsg( 'searchmenu-exists', wfEscapeWikiText( $t->getPrefixedText() ) );
328 }
329 } else {
330 // preserve the paragraph for margins etc...
331 $wgOut->addHTML('<p></p>');
332 }
333 }
334
335 /**
336 *
337 */
338 protected function setupPage( $term ) {
339 global $wgOut;
340 // Figure out the active search profile header
341 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
342 if( $this->searchAdvanced )
343 $this->active = 'advanced';
344 else {
345 $profiles = $this->getSearchProfiles();
346
347 foreach( $profiles as $key => $data ) {
348 if ( $this->namespaces == $data['namespaces'] && $key != 'advanced')
349 $this->active = $key;
350 }
351
352 }
353 # Should advanced UI be used?
354 $this->searchAdvanced = ($this->active === 'advanced');
355 if( !empty( $term ) ) {
356 $wgOut->setPageTitle( wfMsg( 'searchresults') );
357 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
358 }
359 $wgOut->setArticleRelated( false );
360 $wgOut->setRobotPolicy( 'noindex,nofollow' );
361 // add javascript specific to special:search
362 $wgOut->addScriptFile( 'search.js' );
363 }
364
365 /**
366 * Extract "power search" namespace settings from the request object,
367 * returning a list of index numbers to search.
368 *
369 * @param WebRequest $request
370 * @return array
371 */
372 protected function powerSearch( &$request ) {
373 $arr = array();
374 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
375 if( $request->getCheck( 'ns' . $ns ) ) {
376 $arr[] = $ns;
377 }
378 }
379 return $arr;
380 }
381
382 /**
383 * Reconstruct the 'power search' options for links
384 * @return array
385 */
386 protected function powerSearchOptions() {
387 $opt = array();
388 foreach( $this->namespaces as $n ) {
389 $opt['ns' . $n] = 1;
390 }
391 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
392 if( $this->searchAdvanced ) {
393 $opt['advanced'] = $this->searchAdvanced;
394 }
395 return $opt;
396 }
397
398 /**
399 * Show whole set of results
400 *
401 * @param SearchResultSet $matches
402 */
403 protected function showMatches( &$matches ) {
404 global $wgContLang;
405 wfProfileIn( __METHOD__ );
406
407 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
408
409 $out = "";
410 $infoLine = $matches->getInfo();
411 if( !is_null($infoLine) ) {
412 $out .= "\n<!-- {$infoLine} -->\n";
413 }
414 $off = $this->offset + 1;
415 $out .= "<ul class='mw-search-results'>\n";
416 while( $result = $matches->next() ) {
417 $out .= $this->showHit( $result, $terms );
418 }
419 $out .= "</ul>\n";
420
421 // convert the whole thing to desired language variant
422 $out = $wgContLang->convert( $out );
423 wfProfileOut( __METHOD__ );
424 return $out;
425 }
426
427 /**
428 * Format a single hit result
429 * @param SearchResult $result
430 * @param array $terms terms to highlight
431 */
432 protected function showHit( $result, $terms ) {
433 global $wgContLang, $wgLang, $wgUser;
434 wfProfileIn( __METHOD__ );
435
436 if( $result->isBrokenTitle() ) {
437 wfProfileOut( __METHOD__ );
438 return "<!-- Broken link in search result -->\n";
439 }
440
441 $sk = $wgUser->getSkin();
442 $t = $result->getTitle();
443
444 $titleSnippet = $result->getTitleSnippet($terms);
445
446 if( $titleSnippet == '' )
447 $titleSnippet = null;
448
449 $link_t = clone $t;
450
451 wfRunHooks( 'ShowSearchHitTitle',
452 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
453
454 $link = $this->sk->linkKnown(
455 $link_t,
456 $titleSnippet
457 );
458
459 //If page content is not readable, just return the title.
460 //This is not quite safe, but better than showing excerpts from non-readable pages
461 //Note that hiding the entry entirely would screw up paging.
462 if( !$t->userCanRead() ) {
463 wfProfileOut( __METHOD__ );
464 return "<li>{$link}</li>\n";
465 }
466
467 // If the page doesn't *exist*... our search index is out of date.
468 // The least confusing at this point is to drop the result.
469 // You may get less results, but... oh well. :P
470 if( $result->isMissingRevision() ) {
471 wfProfileOut( __METHOD__ );
472 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
473 }
474
475 // format redirects / relevant sections
476 $redirectTitle = $result->getRedirectTitle();
477 $redirectText = $result->getRedirectSnippet($terms);
478 $sectionTitle = $result->getSectionTitle();
479 $sectionText = $result->getSectionSnippet($terms);
480 $redirect = '';
481
482 if( !is_null($redirectTitle) ) {
483 if( $redirectText == '' )
484 $redirectText = null;
485
486 $redirect = "<span class='searchalttitle'>" .
487 wfMsg(
488 'search-redirect',
489 $this->sk->linkKnown(
490 $redirectTitle,
491 $redirectText
492 )
493 ) .
494 "</span>";
495 }
496
497 $section = '';
498
499
500 if( !is_null($sectionTitle) ) {
501 if( $sectionText == '' )
502 $sectionText = null;
503
504 $section = "<span class='searchalttitle'>" .
505 wfMsg(
506 'search-section', $this->sk->linkKnown(
507 $sectionTitle,
508 $sectionText
509 )
510 ) .
511 "</span>";
512 }
513
514 // format text extract
515 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
516
517 // format score
518 if( is_null( $result->getScore() ) ) {
519 // Search engine doesn't report scoring info
520 $score = '';
521 } else {
522 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
523 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
524 . ' - ';
525 }
526
527 // format description
528 $byteSize = $result->getByteSize();
529 $wordCount = $result->getWordCount();
530 $timestamp = $result->getTimestamp();
531 $size = wfMsgExt(
532 'search-result-size',
533 array( 'parsemag', 'escape' ),
534 $this->sk->formatSize( $byteSize ),
535 $wgLang->formatNum( $wordCount )
536 );
537 $date = $wgLang->timeanddate( $timestamp );
538
539 // link to related articles if supported
540 $related = '';
541 if( $result->hasRelated() ) {
542 $st = SpecialPage::getTitleFor( 'Search' );
543 $stParams = array_merge(
544 $this->powerSearchOptions(),
545 array(
546 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
547 'fulltext' => wfMsg( 'search' )
548 )
549 );
550
551 $related = ' -- ' . $sk->linkKnown(
552 $st,
553 wfMsg('search-relatedarticle'),
554 array(),
555 $stParams
556 );
557 }
558
559 // Include a thumbnail for media files...
560 if( $t->getNamespace() == NS_FILE ) {
561 $img = wfFindFile( $t );
562 if( $img ) {
563 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
564 if( $thumb ) {
565 $desc = $img->getShortDesc();
566 wfProfileOut( __METHOD__ );
567 // Float doesn't seem to interact well with the bullets.
568 // Table messes up vertical alignment of the bullets.
569 // Bullets are therefore disabled (didn't look great anyway).
570 return "<li>" .
571 '<table class="searchResultImage">' .
572 '<tr>' .
573 '<td width="120" align="center" valign="top">' .
574 $thumb->toHtml( array( 'desc-link' => true ) ) .
575 '</td>' .
576 '<td valign="top">' .
577 $link .
578 $extract .
579 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
580 '</td>' .
581 '</tr>' .
582 '</table>' .
583 "</li>\n";
584 }
585 }
586 }
587
588 wfProfileOut( __METHOD__ );
589 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
590 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
591 "</li>\n";
592
593 }
594
595 /**
596 * Show results from other wikis
597 *
598 * @param SearchResultSet $matches
599 */
600 protected function showInterwiki( &$matches, $query ) {
601 global $wgContLang;
602 wfProfileIn( __METHOD__ );
603 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
604
605 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
606 wfMsg('search-interwiki-caption')."</div>\n";
607 $off = $this->offset + 1;
608 $out .= "<ul class='mw-search-iwresults'>\n";
609
610 // work out custom project captions
611 $customCaptions = array();
612 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
613 foreach($customLines as $line) {
614 $parts = explode(":",$line,2);
615 if(count($parts) == 2) // validate line
616 $customCaptions[$parts[0]] = $parts[1];
617 }
618
619 $prev = null;
620 while( $result = $matches->next() ) {
621 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
622 $prev = $result->getInterwikiPrefix();
623 }
624 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
625 $out .= "</ul></div>\n";
626
627 // convert the whole thing to desired language variant
628 $out = $wgContLang->convert( $out );
629 wfProfileOut( __METHOD__ );
630 return $out;
631 }
632
633 /**
634 * Show single interwiki link
635 *
636 * @param SearchResult $result
637 * @param string $lastInterwiki
638 * @param array $terms
639 * @param string $query
640 * @param array $customCaptions iw prefix -> caption
641 */
642 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
643 wfProfileIn( __METHOD__ );
644 global $wgContLang, $wgLang;
645
646 if( $result->isBrokenTitle() ) {
647 wfProfileOut( __METHOD__ );
648 return "<!-- Broken link in search result -->\n";
649 }
650
651 $t = $result->getTitle();
652
653 $titleSnippet = $result->getTitleSnippet($terms);
654
655 if( $titleSnippet == '' )
656 $titleSnippet = null;
657
658 $link = $this->sk->linkKnown(
659 $t,
660 $titleSnippet
661 );
662
663 // format redirect if any
664 $redirectTitle = $result->getRedirectTitle();
665 $redirectText = $result->getRedirectSnippet($terms);
666 $redirect = '';
667 if( !is_null($redirectTitle) ) {
668 if( $redirectText == '' )
669 $redirectText = null;
670
671 $redirect = "<span class='searchalttitle'>" .
672 wfMsg(
673 'search-redirect',
674 $this->sk->linkKnown(
675 $redirectTitle,
676 $redirectText
677 )
678 ) .
679 "</span>";
680 }
681
682 $out = "";
683 // display project name
684 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
685 if( key_exists($t->getInterwiki(),$customCaptions) )
686 // captions from 'search-interwiki-custom'
687 $caption = $customCaptions[$t->getInterwiki()];
688 else{
689 // default is to show the hostname of the other wiki which might suck
690 // if there are many wikis on one hostname
691 $parsed = parse_url($t->getFullURL());
692 $caption = wfMsg('search-interwiki-default', $parsed['host']);
693 }
694 // "more results" link (special page stuff could be localized, but we might not know target lang)
695 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
696 $searchLink = $this->sk->linkKnown(
697 $searchTitle,
698 wfMsg('search-interwiki-more'),
699 array(),
700 array(
701 'search' => $query,
702 'fulltext' => 'Search'
703 )
704 );
705 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
706 {$searchLink}</span>{$caption}</div>\n<ul>";
707 }
708
709 $out .= "<li>{$link} {$redirect}</li>\n";
710 wfProfileOut( __METHOD__ );
711 return $out;
712 }
713
714
715 /**
716 * Generates the power search box at bottom of [[Special:Search]]
717 * @param $term string: search term
718 * @return $out string: HTML form
719 */
720 protected function powerSearchBox( $term ) {
721 global $wgScript, $wgContLang;
722
723 // Groups namespaces into rows according to subject
724 $rows = array();
725 foreach( SearchEngine::searchableNamespaces() as $namespace => $name ) {
726 $subject = MWNamespace::getSubject( $namespace );
727 if( !array_key_exists( $subject, $rows ) ) {
728 $rows[$subject] = "";
729 }
730 $name = str_replace( '_', ' ', $name );
731 if( $name == '' ) {
732 $name = wfMsg( 'blanknamespace' );
733 }
734 $rows[$subject] .=
735 Xml::openElement(
736 'td', array( 'style' => 'white-space: nowrap' )
737 ) .
738 Xml::checkLabel(
739 $name,
740 "ns{$namespace}",
741 "mw-search-ns{$namespace}",
742 in_array( $namespace, $this->namespaces )
743 ) .
744 Xml::closeElement( 'td' );
745 }
746 $rows = array_values( $rows );
747 $numRows = count( $rows );
748
749 // Lays out namespaces in multiple floating two-column tables so they'll
750 // be arranged nicely while still accommodating different screen widths
751 $namespaceTables = '';
752 for( $i = 0; $i < $numRows; $i += 4 ) {
753 $namespaceTables .= Xml::openElement(
754 'table',
755 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
756 );
757 for( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
758 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
759 }
760 $namespaceTables .= Xml::closeElement( 'table' );
761 }
762 // Show redirects check only if backend supports it
763 $redirects = '';
764 if( $this->searchEngine->acceptListRedirects() ) {
765 $redirects =
766 Xml::check(
767 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' )
768 ) .
769 ' ' .
770 Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
771 }
772 // Return final output
773 return
774 Xml::openElement(
775 'fieldset',
776 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
777 ) .
778 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
779 Xml::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
780 Xml::tags(
781 'div',
782 array( 'id' => 'mw-search-togglebox' ),
783 Xml::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
784 Xml::element(
785 'input',
786 array(
787 'type'=>'button',
788 'id' => 'mw-search-toggleall',
789 'onclick' => 'mwToggleSearchCheckboxes("all");',
790 'value' => wfMsg( 'powersearch-toggleall' )
791 )
792 ) .
793 Xml::element(
794 'input',
795 array(
796 'type'=>'button',
797 'id' => 'mw-search-togglenone',
798 'onclick' => 'mwToggleSearchCheckboxes("none");',
799 'value' => wfMsg( 'powersearch-togglenone' )
800 )
801 )
802 ) .
803 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
804 $namespaceTables .
805 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
806 $redirects .
807 Xml::hidden( 'title', SpecialPage::getTitleFor( 'Search' )->getPrefixedText() ) .
808 Xml::hidden( 'advanced', $this->searchAdvanced ) .
809 Xml::hidden( 'fulltext', 'Advanced search' ) .
810 Xml::closeElement( 'fieldset' );
811 }
812
813 protected function searchFocus() {
814 return Html::inlineScript(
815 "hookEvent(\"load\", function() {" .
816 "document.getElementById('searchText').focus();" .
817 "});" );
818 }
819
820 protected function getSearchProfiles() {
821 // Builds list of Search Types (profiles)
822 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
823
824 $profiles = array(
825 'default' => array(
826 'message' => 'searchprofile-articles',
827 'tooltip' => 'searchprofile-articles-tooltip',
828 'namespaces' => SearchEngine::defaultNamespaces(),
829 'namespace-messages' => SearchEngine::namespacesAsText(
830 SearchEngine::defaultNamespaces()
831 ),
832 ),
833 'images' => array(
834 'message' => 'searchprofile-images',
835 'tooltip' => 'searchprofile-images-tooltip',
836 'namespaces' => array( NS_FILE ),
837 ),
838 'help' => array(
839 'message' => 'searchprofile-project',
840 'tooltip' => 'searchprofile-project-tooltip',
841 'namespaces' => SearchEngine::helpNamespaces(),
842 'namespace-messages' => SearchEngine::namespacesAsText(
843 SearchEngine::helpNamespaces()
844 ),
845 ),
846 'all' => array(
847 'message' => 'searchprofile-everything',
848 'tooltip' => 'searchprofile-everything-tooltip',
849 'namespaces' => $nsAllSet,
850 ),
851 'advanced' => array(
852 'message' => 'searchprofile-advanced',
853 'tooltip' => 'searchprofile-advanced-tooltip',
854 'namespaces' => $this->namespaces,
855 'parameters' => array( 'advanced' => 1 ),
856 )
857 );
858
859 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
860
861 foreach( $profiles as $key => &$data ) {
862 sort($data['namespaces']);
863 }
864
865 return $profiles;
866 }
867
868 protected function formHeader( $term, $resultsShown, $totalNum ) {
869 global $wgContLang, $wgLang;
870
871 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
872
873 $bareterm = $term;
874 if( $this->startsWithImage( $term ) ) {
875 // Deletes prefixes
876 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
877 }
878
879
880 $profiles = $this->getSearchProfiles();
881
882 // Outputs XML for Search Types
883 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
884 $out .= Xml::openElement( 'ul' );
885 foreach ( $profiles as $id => $profile ) {
886 $tooltipParam = isset( $profile['namespace-messages'] ) ?
887 $wgLang->commaList( $profile['namespace-messages'] ) : null;
888 $out .= Xml::tags(
889 'li',
890 array(
891 'class' => $this->active == $id ? 'current' : 'normal'
892 ),
893 $this->makeSearchLink(
894 $bareterm,
895 $profile['namespaces'],
896 wfMsg( $profile['message'] ),
897 wfMsg( $profile['tooltip'], $tooltipParam ),
898 isset( $profile['parameters'] ) ? $profile['parameters'] : array()
899 )
900 );
901 }
902 $out .= Xml::closeElement( 'ul' );
903 $out .= Xml::closeElement('div') ;
904
905 // Results-info
906 if ( $resultsShown > 0 ) {
907 if ( $totalNum > 0 ){
908 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
909 $wgLang->formatNum( $this->offset + 1 ),
910 $wgLang->formatNum( $this->offset + $resultsShown ),
911 $wgLang->formatNum( $totalNum ),
912 wfEscapeWikiText( $term ),
913 $wgLang->formatNum( $resultsShown )
914 );
915 } elseif ( $resultsShown >= $this->limit ) {
916 $top = wfShowingResults( $this->offset, $this->limit );
917 } else {
918 $top = wfShowingResultsNum( $this->offset, $this->limit, $resultsShown );
919 }
920 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
921 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
922 );
923 }
924
925 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
926 $out .= Xml::closeElement('div');
927
928 // Adds hidden namespace fields
929 if ( !$this->searchAdvanced ) {
930 foreach( $this->namespaces as $ns ) {
931 $out .= Xml::hidden( "ns{$ns}", '1' );
932 }
933 }
934
935 return $out;
936 }
937
938 protected function shortDialog( $term ) {
939 $searchTitle = SpecialPage::getTitleFor( 'Search' );
940 $searchable = SearchEngine::searchableNamespaces();
941 $out = Html::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
942 // Keep redirect setting
943 $out .= Html::hidden( "redirs", (int)$this->searchRedirects ) . "\n";
944 // Term box
945 $out .= Html::input( 'search', $term, 'search', array(
946 'id' => 'searchText',
947 'size' => '50',
948 'autofocus'
949 ) ) . "\n";
950 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
951 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
952 return $out . $this->didYouMeanHtml;
953 }
954
955 /** Make a search link with some target namespaces */
956 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params=array() ) {
957 $opt = $params;
958 foreach( $namespaces as $n ) {
959 $opt['ns' . $n] = 1;
960 }
961 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
962
963 $st = SpecialPage::getTitleFor( 'Search' );
964 $stParams = array_merge(
965 array(
966 'search' => $term,
967 'fulltext' => wfMsg( 'search' )
968 ),
969 $opt
970 );
971
972 return Xml::element(
973 'a',
974 array(
975 'href' => $st->getLocalURL( $stParams ),
976 'title' => $tooltip,
977 'onmousedown' => 'mwSearchHeaderClick(this);',
978 'onkeydown' => 'mwSearchHeaderClick(this);'),
979 $label
980 );
981 }
982
983 /** Check if query starts with image: prefix */
984 protected function startsWithImage( $term ) {
985 global $wgContLang;
986
987 $p = explode( ':', $term );
988 if( count( $p ) > 1 ) {
989 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
990 }
991 return false;
992 }
993
994 /** Check if query starts with all: prefix */
995 protected function startsWithAll( $term ) {
996
997 $allkeyword = wfMsgForContent('searchall');
998
999 $p = explode( ':', $term );
1000 if( count( $p ) > 1 ) {
1001 return $p[0] == $allkeyword;
1002 }
1003 return false;
1004 }
1005 }
1006