Make resolveConflictOn() accept a prefix different from the page name (needed for...
[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_t = clone $t;
444
445 wfRunHooks( 'ShowSearchHitTitle',
446 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
447
448 $link = $this->sk->linkKnown(
449 $link_t,
450 $titleSnippet
451 );
452
453 //If page content is not readable, just return the title.
454 //This is not quite safe, but better than showing excerpts from non-readable pages
455 //Note that hiding the entry entirely would screw up paging.
456 if( !$t->userCanRead() ) {
457 wfProfileOut( __METHOD__ );
458 return "<li>{$link}</li>\n";
459 }
460
461 // If the page doesn't *exist*... our search index is out of date.
462 // The least confusing at this point is to drop the result.
463 // You may get less results, but... oh well. :P
464 if( $result->isMissingRevision() ) {
465 wfProfileOut( __METHOD__ );
466 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
467 }
468
469 // format redirects / relevant sections
470 $redirectTitle = $result->getRedirectTitle();
471 $redirectText = $result->getRedirectSnippet($terms);
472 $sectionTitle = $result->getSectionTitle();
473 $sectionText = $result->getSectionSnippet($terms);
474 $redirect = '';
475
476 if( !is_null($redirectTitle) ) {
477 if( $redirectText == '' )
478 $redirectText = null;
479
480 $redirect = "<span class='searchalttitle'>" .
481 wfMsg(
482 'search-redirect',
483 $this->sk->linkKnown(
484 $redirectTitle,
485 $redirectText
486 )
487 ) .
488 "</span>";
489 }
490
491 $section = '';
492
493
494 if( !is_null($sectionTitle) ) {
495 if( $sectionText == '' )
496 $sectionText = null;
497
498 $section = "<span class='searchalttitle'>" .
499 wfMsg(
500 'search-section', $this->sk->linkKnown(
501 $sectionTitle,
502 $sectionText
503 )
504 ) .
505 "</span>";
506 }
507
508 // format text extract
509 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
510
511 // format score
512 if( is_null( $result->getScore() ) ) {
513 // Search engine doesn't report scoring info
514 $score = '';
515 } else {
516 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
517 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
518 . ' - ';
519 }
520
521 // format description
522 $byteSize = $result->getByteSize();
523 $wordCount = $result->getWordCount();
524 $timestamp = $result->getTimestamp();
525 $size = wfMsgExt(
526 'search-result-size',
527 array( 'parsemag', 'escape' ),
528 $this->sk->formatSize( $byteSize ),
529 $wgLang->formatNum( $wordCount )
530 );
531 $date = $wgLang->timeanddate( $timestamp );
532
533 // link to related articles if supported
534 $related = '';
535 if( $result->hasRelated() ) {
536 $st = SpecialPage::getTitleFor( 'Search' );
537 $stParams = array_merge(
538 $this->powerSearchOptions(),
539 array(
540 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
541 'fulltext' => wfMsg( 'search' )
542 )
543 );
544
545 $related = ' -- ' . $sk->linkKnown(
546 $st,
547 wfMsg('search-relatedarticle'),
548 array(),
549 $stParams
550 );
551 }
552
553 // Include a thumbnail for media files...
554 if( $t->getNamespace() == NS_FILE ) {
555 $img = wfFindFile( $t );
556 if( $img ) {
557 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
558 if( $thumb ) {
559 $desc = $img->getShortDesc();
560 wfProfileOut( __METHOD__ );
561 // Float doesn't seem to interact well with the bullets.
562 // Table messes up vertical alignment of the bullets.
563 // Bullets are therefore disabled (didn't look great anyway).
564 return "<li>" .
565 '<table class="searchResultImage">' .
566 '<tr>' .
567 '<td width="120" align="center" valign="top">' .
568 $thumb->toHtml( array( 'desc-link' => true ) ) .
569 '</td>' .
570 '<td valign="top">' .
571 $link .
572 $extract .
573 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
574 '</td>' .
575 '</tr>' .
576 '</table>' .
577 "</li>\n";
578 }
579 }
580 }
581
582 wfProfileOut( __METHOD__ );
583 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
584 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
585 "</li>\n";
586
587 }
588
589 /**
590 * Show results from other wikis
591 *
592 * @param SearchResultSet $matches
593 */
594 protected function showInterwiki( &$matches, $query ) {
595 global $wgContLang;
596 wfProfileIn( __METHOD__ );
597 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
598
599 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
600 wfMsg('search-interwiki-caption')."</div>\n";
601 $off = $this->offset + 1;
602 $out .= "<ul class='mw-search-iwresults'>\n";
603
604 // work out custom project captions
605 $customCaptions = array();
606 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
607 foreach($customLines as $line) {
608 $parts = explode(":",$line,2);
609 if(count($parts) == 2) // validate line
610 $customCaptions[$parts[0]] = $parts[1];
611 }
612
613 $prev = null;
614 while( $result = $matches->next() ) {
615 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
616 $prev = $result->getInterwikiPrefix();
617 }
618 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
619 $out .= "</ul></div>\n";
620
621 // convert the whole thing to desired language variant
622 $out = $wgContLang->convert( $out );
623 wfProfileOut( __METHOD__ );
624 return $out;
625 }
626
627 /**
628 * Show single interwiki link
629 *
630 * @param SearchResult $result
631 * @param string $lastInterwiki
632 * @param array $terms
633 * @param string $query
634 * @param array $customCaptions iw prefix -> caption
635 */
636 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
637 wfProfileIn( __METHOD__ );
638 global $wgContLang, $wgLang;
639
640 if( $result->isBrokenTitle() ) {
641 wfProfileOut( __METHOD__ );
642 return "<!-- Broken link in search result -->\n";
643 }
644
645 $t = $result->getTitle();
646
647 $titleSnippet = $result->getTitleSnippet($terms);
648
649 if( $titleSnippet == '' )
650 $titleSnippet = null;
651
652 $link = $this->sk->linkKnown(
653 $t,
654 $titleSnippet
655 );
656
657 // format redirect if any
658 $redirectTitle = $result->getRedirectTitle();
659 $redirectText = $result->getRedirectSnippet($terms);
660 $redirect = '';
661 if( !is_null($redirectTitle) ) {
662 if( $redirectText == '' )
663 $redirectText = null;
664
665 $redirect = "<span class='searchalttitle'>" .
666 wfMsg(
667 'search-redirect',
668 $this->sk->linkKnown(
669 $redirectTitle,
670 $redirectText
671 )
672 ) .
673 "</span>";
674 }
675
676 $out = "";
677 // display project name
678 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
679 if( key_exists($t->getInterwiki(),$customCaptions) )
680 // captions from 'search-interwiki-custom'
681 $caption = $customCaptions[$t->getInterwiki()];
682 else{
683 // default is to show the hostname of the other wiki which might suck
684 // if there are many wikis on one hostname
685 $parsed = parse_url($t->getFullURL());
686 $caption = wfMsg('search-interwiki-default', $parsed['host']);
687 }
688 // "more results" link (special page stuff could be localized, but we might not know target lang)
689 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
690 $searchLink = $this->sk->linkKnown(
691 $searchTitle,
692 wfMsg('search-interwiki-more'),
693 array(),
694 array(
695 'search' => $query,
696 'fulltext' => 'Search'
697 )
698 );
699 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
700 {$searchLink}</span>{$caption}</div>\n<ul>";
701 }
702
703 $out .= "<li>{$link} {$redirect}</li>\n";
704 wfProfileOut( __METHOD__ );
705 return $out;
706 }
707
708
709 /**
710 * Generates the power search box at bottom of [[Special:Search]]
711 * @param $term string: search term
712 * @return $out string: HTML form
713 */
714 protected function powerSearchBox( $term ) {
715 global $wgScript, $wgContLang;
716
717 // Groups namespaces into rows according to subject
718 $rows = array();
719 foreach( SearchEngine::searchableNamespaces() as $namespace => $name ) {
720 $subject = MWNamespace::getSubject( $namespace );
721 if( !array_key_exists( $subject, $rows ) ) {
722 $rows[$subject] = "";
723 }
724 $name = str_replace( '_', ' ', $name );
725 if( $name == '' ) {
726 $name = wfMsg( 'blanknamespace' );
727 }
728 $rows[$subject] .=
729 Xml::openElement(
730 'td', array( 'style' => 'white-space: nowrap' )
731 ) .
732 Xml::checkLabel(
733 $name,
734 "ns{$namespace}",
735 "mw-search-ns{$namespace}",
736 in_array( $namespace, $this->namespaces )
737 ) .
738 Xml::closeElement( 'td' );
739 }
740 $rows = array_values( $rows );
741 $numRows = count( $rows );
742
743 // Lays out namespaces in multiple floating two-column tables so they'll
744 // be arranged nicely while still accommodating different screen widths
745 $namespaceTables = '';
746 for( $i = 0; $i < $numRows; $i += 4 ) {
747 $namespaceTables .= Xml::openElement(
748 'table',
749 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
750 );
751 for( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
752 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
753 }
754 $namespaceTables .= Xml::closeElement( 'table' );
755 }
756 // Show redirects check only if backend supports it
757 $redirects = '';
758 if( $this->searchEngine->acceptListRedirects() ) {
759 $redirects =
760 Xml::check(
761 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' )
762 ) .
763 ' ' .
764 Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
765 }
766 // Return final output
767 return
768 Xml::openElement(
769 'fieldset',
770 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
771 ) .
772 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
773 Xml::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
774 Xml::tags(
775 'div',
776 array( 'id' => 'mw-search-togglebox' ),
777 Xml::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
778 Xml::element(
779 'input',
780 array(
781 'type'=>'button',
782 'id' => 'mw-search-toggleall',
783 'onclick' => 'mwToggleSearchCheckboxes("all");',
784 'value' => wfMsg( 'powersearch-toggleall' )
785 )
786 ) .
787 Xml::element(
788 'input',
789 array(
790 'type'=>'button',
791 'id' => 'mw-search-togglenone',
792 'onclick' => 'mwToggleSearchCheckboxes("none");',
793 'value' => wfMsg( 'powersearch-togglenone'
794 )
795 )
796 )
797 ) .
798 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
799 $namespaceTables .
800 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
801 $redirects .
802 Xml::hidden( 'title', SpecialPage::getTitleFor( 'Search' )->getPrefixedText() ) .
803 Xml::hidden( 'advanced', $this->searchAdvanced ) .
804 Xml::hidden( 'fulltext', 'Advanced search' ) .
805 Xml::closeElement( 'fieldset' );
806 }
807
808 protected function searchFocus() {
809 return Html::inlineScript(
810 "hookEvent(\"load\", function() {" .
811 "document.getElementById('searchText').focus();" .
812 "});" );
813 }
814
815 protected function formHeader( $term, $resultsShown, $totalNum ) {
816 global $wgContLang, $wgCanonicalNamespaceNames, $wgLang;
817
818 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
819
820 $bareterm = $term;
821 if( $this->startsWithImage( $term ) ) {
822 // Deletes prefixes
823 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
824 }
825 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
826
827 // Builds list of Search Types (profiles)
828 $profiles = array(
829 'default' => array(
830 'message' => 'searchprofile-articles',
831 'tooltip' => 'searchprofile-articles-tooltip',
832 'namespaces' => SearchEngine::defaultNamespaces(),
833 'namespace-messages' => SearchEngine::namespacesAsText(
834 SearchEngine::defaultNamespaces()
835 ),
836 ),
837 'images' => array(
838 'message' => 'searchprofile-images',
839 'tooltip' => 'searchprofile-images-tooltip',
840 'namespaces' => array( NS_FILE ),
841 ),
842 'help' => array(
843 'message' => 'searchprofile-project',
844 'tooltip' => 'searchprofile-project-tooltip',
845 'namespaces' => SearchEngine::helpNamespaces(),
846 'namespace-messages' => SearchEngine::namespacesAsText(
847 SearchEngine::helpNamespaces()
848 ),
849 ),
850 'all' => array(
851 'message' => 'searchprofile-everything',
852 'tooltip' => 'searchprofile-everything-tooltip',
853 'namespaces' => $nsAllSet,
854 ),
855 'advanced' => array(
856 'message' => 'searchprofile-advanced',
857 'tooltip' => 'searchprofile-advanced-tooltip',
858 'namespaces' => $this->namespaces,
859 'parameters' => array( 'advanced' => 1 ),
860 )
861 );
862 // Outputs XML for Search Types
863 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
864 $out .= Xml::openElement( 'ul' );
865 foreach ( $profiles as $id => $profile ) {
866 $tooltipParam = isset( $profile['namespace-messages'] ) ?
867 $wgLang->commaList( $profile['namespace-messages'] ) : null;
868 $out .= Xml::tags(
869 'li',
870 array(
871 'class' => $this->active == $id ? 'current' : 'normal'
872 ),
873 $this->makeSearchLink(
874 $bareterm,
875 $profile['namespaces'],
876 wfMsg( $profile['message'] ),
877 wfMsg( $profile['tooltip'], $tooltipParam ),
878 isset( $profile['parameters'] ) ? $profile['parameters'] : array()
879 )
880 );
881 }
882 $out .= Xml::closeElement( 'ul' );
883 $out .= Xml::closeElement('div') ;
884
885 // Results-info
886 if ( $resultsShown > 0 ) {
887 if ( $totalNum > 0 ){
888 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
889 $wgLang->formatNum( $this->offset + 1 ),
890 $wgLang->formatNum( $this->offset + $resultsShown ),
891 $wgLang->formatNum( $totalNum ),
892 wfEscapeWikiText( $term ),
893 $wgLang->formatNum( $resultsShown )
894 );
895 } elseif ( $resultsShown >= $this->limit ) {
896 $top = wfShowingResults( $this->offset, $this->limit );
897 } else {
898 $top = wfShowingResultsNum( $this->offset, $this->limit, $resultsShown );
899 }
900 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
901 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
902 );
903 }
904
905 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
906 $out .= Xml::closeElement('div');
907
908 // Adds hidden namespace fields
909 if ( !$this->searchAdvanced ) {
910 foreach( $this->namespaces as $ns ) {
911 $out .= Xml::hidden( "ns{$ns}", '1' );
912 }
913 }
914
915 return $out;
916 }
917
918 protected function shortDialog( $term ) {
919 $searchTitle = SpecialPage::getTitleFor( 'Search' );
920 $searchable = SearchEngine::searchableNamespaces();
921 $out = Html::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
922 // Keep redirect setting
923 $out .= Html::hidden( "redirs", (int)$this->searchRedirects ) . "\n";
924 // Term box
925 $out .= Html::input( 'search', $term, 'search', array(
926 'id' => 'searchText',
927 'size' => '50',
928 'autofocus'
929 ) ) . "\n";
930 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
931 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
932 return $out . $this->didYouMeanHtml;
933 }
934
935 /** Make a search link with some target namespaces */
936 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params=array() ) {
937 $opt = $params;
938 foreach( $namespaces as $n ) {
939 $opt['ns' . $n] = 1;
940 }
941 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
942
943 $st = SpecialPage::getTitleFor( 'Search' );
944 $stParams = array_merge(
945 array(
946 'search' => $term,
947 'fulltext' => wfMsg( 'search' )
948 ),
949 $opt
950 );
951
952 return Xml::element(
953 'a',
954 array(
955 'href' => $st->getLocalURL( $stParams ),
956 'title' => $tooltip,
957 'onmousedown' => 'mwSearchHeaderClick(this);',
958 'onkeydown' => 'mwSearchHeaderClick(this);'),
959 $label
960 );
961 }
962
963 /** Check if query starts with image: prefix */
964 protected function startsWithImage( $term ) {
965 global $wgContLang;
966
967 $p = explode( ':', $term );
968 if( count( $p ) > 1 ) {
969 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
970 }
971 return false;
972 }
973
974 /** Check if query starts with all: prefix */
975 protected function startsWithAll( $term ) {
976
977 $allkeyword = wfMsgForContent('searchall');
978
979 $p = explode( ':', $term );
980 if( count( $p ) > 1 ) {
981 return $p[0] == $allkeyword;
982 }
983 return false;
984 }
985 }
986