Suppress index link if no term given
[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
34 // Strip underscores from title parameter; most of the time we'll want
35 // text form here. But don't strip underscores from actual text params!
36 $titleParam = str_replace( '_', ' ', $par );
37
38 $search = str_replace( "\n", " ", $wgRequest->getText( 'search', $titleParam ) );
39 $searchPage = new SpecialSearch( $wgRequest, $wgUser );
40 if( $wgRequest->getVal( 'fulltext' )
41 || !is_null( $wgRequest->getVal( 'offset' ))
42 || !is_null( $wgRequest->getVal( 'searchx' )) )
43 {
44 $searchPage->showResults( $search, 'search' );
45 } else {
46 $searchPage->goResult( $search );
47 }
48 }
49
50 /**
51 * implements Special:Search - Run text & title search and display the output
52 * @ingroup SpecialPage
53 */
54 class SpecialSearch {
55
56 /**
57 * Set up basic search parameters from the request and user settings.
58 * Typically you'll pass $wgRequest and $wgUser.
59 *
60 * @param WebRequest $request
61 * @param User $user
62 * @public
63 */
64 function SpecialSearch( &$request, &$user ) {
65 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
66
67 $this->namespaces = $this->powerSearch( $request );
68 if( empty( $this->namespaces ) ) {
69 $this->namespaces = SearchEngine::userNamespaces( $user );
70 }
71
72 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
73 $this->searchAdvanced = $request->getVal('advanced');
74 }
75
76 /**
77 * If an exact title match can be found, jump straight ahead to it.
78 * @param string $term
79 * @public
80 */
81 function goResult( $term ) {
82 global $wgOut, $wgGoToEdit;
83
84 $this->setupPage( $term );
85
86 # Try to go to page as entered.
87 $t = Title::newFromText( $term );
88
89 # If the string cannot be used to create a title
90 if( is_null( $t ) ) {
91 return $this->showResults( $term );
92 }
93
94 # If there's an exact or very near match, jump right there.
95 $t = SearchEngine::getNearMatch( $term );
96 if( !is_null( $t ) ) {
97 $wgOut->redirect( $t->getFullURL() );
98 return;
99 }
100
101 # No match, generate an edit URL
102 $t = Title::newFromText( $term );
103 if( ! is_null( $t ) ) {
104 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
105 # If the feature is enabled, go straight to the edit page
106 if( $wgGoToEdit ) {
107 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
108 return;
109 }
110 }
111
112 return $this->showResults( $term );
113 }
114
115 /**
116 * @param string $term
117 * @public
118 */
119 function showResults( $term ) {
120 $fname = 'SpecialSearch::showResults';
121 wfProfileIn( $fname );
122 global $wgOut, $wgUser;
123 $sk = $wgUser->getSkin();
124
125 $this->setupPage( $term );
126 $this->searchEngine = SearchEngine::create();
127
128 $t = Title::newFromText( $term );
129
130 $wgOut->addHtml(
131 Xml::openElement( 'table', array( 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
132 Xml::openElement( 'tr' ) .
133 Xml::openElement( 'td' ) . "\n"
134 );
135 if( $this->searchAdvanced ) {
136 $wgOut->addHTML( $this->powerSearchBox( $term ) );
137 $showMenu = false;
138 } else {
139 $wgOut->addHTML( $this->shortDialog( $term ) );
140 $showMenu = true;
141 }
142 $wgOut->addHtml(
143 Xml::closeElement('td') .
144 Xml::closeElement('tr') .
145 Xml::closeElement('table')
146 );
147
148 if( '' === trim( $term ) ) {
149 // Empty query -- straight view of search form
150 wfProfileOut( $fname );
151 return;
152 }
153
154 global $wgDisableTextSearch;
155 if( $wgDisableTextSearch ) {
156 global $wgSearchForwardUrl;
157 if( $wgSearchForwardUrl ) {
158 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
159 $wgOut->redirect( $url );
160 return;
161 }
162 global $wgInputEncoding;
163 $wgOut->addHTML(
164 Xml::openElement( 'fieldset' ) .
165 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
166 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
167 wfMsg( 'googlesearch',
168 htmlspecialchars( $term ),
169 htmlspecialchars( $wgInputEncoding ),
170 htmlspecialchars( wfMsg( 'searchbutton' ) )
171 ) .
172 Xml::closeElement( 'fieldset' )
173 );
174 wfProfileOut( $fname );
175 return;
176 }
177
178 $search =& $this->searchEngine;
179 $search->setLimitOffset( $this->limit, $this->offset );
180 $search->setNamespaces( $this->namespaces );
181 $search->showRedirects = $this->searchRedirects;
182 $rewritten = $search->replacePrefixes($term);
183
184 $titleMatches = $search->searchTitle( $rewritten );
185
186 // Sometimes the search engine knows there are too many hits
187 if( $titleMatches instanceof SearchResultTooMany ) {
188 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
189 wfProfileOut( $fname );
190 return;
191 }
192
193 $textMatches = $search->searchText( $rewritten );
194
195 // did you mean... suggestions
196 if( $textMatches && $textMatches->hasSuggestion() ) {
197 $st = SpecialPage::getTitleFor( 'Search' );
198 $stParams = wfArrayToCGI(
199 array( 'search' => $textMatches->getSuggestionQuery(), 'fulltext' => wfMsg('search') ),
200 $this->powerSearchOptions()
201 );
202 $suggestLink = '<a href="'.$st->escapeLocalURL($stParams).'">'.
203 $textMatches->getSuggestionSnippet().'</a>';
204
205 $wgOut->addHTML('<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>');
206 }
207
208 // show direct page/create link
209 if( !is_null($t) ) {
210 if( !$t->exists() ) {
211 $wgOut->addWikiMsg( 'searchmenu-new', wfEscapeWikiText( $t->getPrefixedText() ) );
212 } else {
213 $wgOut->addWikiMsg( 'searchmenu-exists', wfEscapeWikiText( $t->getPrefixedText() ) );
214 }
215 }
216
217 // show number of results
218 $numTitleMatches = $titleMatches ? $titleMatches->numRows() : 0;
219 $numTextMatches = $textMatches ? $textMatches->numRows() : 0;
220 $highestNum = max( $numTitleMatches, $numTextMatches );
221 // Total query matches (possible false positives)
222 $num = $numTitleMatches + $numTextMatches;
223 // Get total actual results
224 $totalNum = 0;
225 if( $titleMatches && !is_null($titleMatches->getTotalHits()) )
226 $totalNum += $titleMatches->getTotalHits();
227 if( $textMatches && !is_null($textMatches->getTotalHits()) )
228 $totalNum += $textMatches->getTotalHits();
229 if( $num > 0 ) {
230 if( $totalNum > 0 ) {
231 $top = wfMsgExt('showingresultstotal', array( 'parseinline' ),
232 $this->offset+1, $this->offset+$num, $totalNum, $num );
233 } elseif( $num >= $this->limit ) {
234 $top = wfShowingResults( $this->offset, $this->limit );
235 } else {
236 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
237 }
238 $wgOut->addHTML( "<p class='mw-search-numberresults'>{$top}</p>\n" );
239 }
240
241 // prev/next links
242 if( $num || $this->offset ) {
243 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
244 SpecialPage::getTitleFor( 'Search' ),
245 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
246 ($highestNum < $this->limit)
247 );
248 $wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
249 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
250 } else {
251 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
252 }
253
254 $wgOut->addHtml( "<div class='searchresults'>" );
255
256 if( $titleMatches ) {
257 if( $titleMatches->numRows() ) {
258 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
259 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
260 }
261 $titleMatches->free();
262 }
263
264 if( $textMatches ) {
265 // output appropriate heading
266 if( $textMatches->numRows() ) {
267 if($titleMatches)
268 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
269 else // if no title matches the heading is redundant
270 $wgOut->addHTML("<hr/>");
271 } elseif( $num == 0 ) {
272 # Don't show the 'no text matches' if we received title matches
273 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
274 }
275 // show interwiki results if any
276 if( $textMatches->hasInterwikiResults() )
277 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ));
278 // show results
279 if( $textMatches->numRows() )
280 $wgOut->addHTML( $this->showMatches( $textMatches ) );
281
282 $textMatches->free();
283 }
284
285 if( $num == 0 ) {
286 $wgOut->addWikiMsg( 'search-nonefound' );
287 }
288
289 $wgOut->addHtml( "</div>" );
290
291 if( $num || $this->offset ) {
292 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
293 }
294 wfProfileOut( $fname );
295 }
296
297 /**
298 *
299 */
300 protected function setupPage( $term ) {
301 global $wgOut;
302 if( !empty( $term ) ) {
303 $wgOut->setPageTitle( wfMsg( 'searchresults') );
304 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term) ) );
305 }
306 $wgOut->setArticleRelated( false );
307 $wgOut->setRobotPolicy( 'noindex,nofollow' );
308 }
309
310 /**
311 * Extract "power search" namespace settings from the request object,
312 * returning a list of index numbers to search.
313 *
314 * @param WebRequest $request
315 * @return array
316 */
317 protected function powerSearch( &$request ) {
318 $arr = array();
319 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
320 if( $request->getCheck( 'ns' . $ns ) ) {
321 $arr[] = $ns;
322 }
323 }
324 return $arr;
325 }
326
327 /**
328 * Reconstruct the 'power search' options for links
329 * @return array
330 */
331 protected function powerSearchOptions() {
332 $opt = array();
333 foreach( $this->namespaces as $n ) {
334 $opt['ns' . $n] = 1;
335 }
336 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
337 if( $this->searchAdvanced )
338 $opt['advanced'] = $this->searchAdvanced;
339 return $opt;
340 }
341
342 /**
343 * Show whole set of results
344 *
345 * @param SearchResultSet $matches
346 */
347 protected function showMatches( &$matches ) {
348 global $wgContLang;
349 $fname = 'SpecialSearch::showMatches';
350 wfProfileIn( $fname );
351
352 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
353
354 $out = "";
355
356 $infoLine = $matches->getInfo();
357 if( !is_null($infoLine) )
358 $out .= "\n<!-- {$infoLine} -->\n";
359
360
361 $off = $this->offset + 1;
362 $out .= "<ul class='mw-search-results'>\n";
363 while( $result = $matches->next() ) {
364 $out .= $this->showHit( $result, $terms );
365 }
366 $out .= "</ul>\n";
367
368 // convert the whole thing to desired language variant
369 $out = $wgContLang->convert( $out );
370 wfProfileOut( $fname );
371 return $out;
372 }
373
374 /**
375 * Format a single hit result
376 * @param SearchResult $result
377 * @param array $terms terms to highlight
378 */
379 protected function showHit( $result, $terms ) {
380 $fname = 'SpecialSearch::showHit';
381 wfProfileIn( $fname );
382 global $wgUser, $wgContLang, $wgLang;
383
384 if( $result->isBrokenTitle() ) {
385 wfProfileOut( $fname );
386 return "<!-- Broken link in search result -->\n";
387 }
388
389 $t = $result->getTitle();
390 $sk = $wgUser->getSkin();
391
392 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
393
394 //If page content is not readable, just return the title.
395 //This is not quite safe, but better than showing excerpts from non-readable pages
396 //Note that hiding the entry entirely would screw up paging.
397 if(!$t->userCanRead()) {
398 wfProfileOut( $fname );
399 return "<li>{$link}</li>\n";
400 }
401
402 // If the page doesn't *exist*... our search index is out of date.
403 // The least confusing at this point is to drop the result.
404 // You may get less results, but... oh well. :P
405 if( $result->isMissingRevision() ) {
406 wfProfileOut( $fname );
407 return "<!-- missing page " .
408 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
409 }
410
411 // format redirects / relevant sections
412 $redirectTitle = $result->getRedirectTitle();
413 $redirectText = $result->getRedirectSnippet($terms);
414 $sectionTitle = $result->getSectionTitle();
415 $sectionText = $result->getSectionSnippet($terms);
416 $redirect = '';
417 if( !is_null($redirectTitle) )
418 $redirect = "<span class='searchalttitle'>"
419 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
420 ."</span>";
421 $section = '';
422 if( !is_null($sectionTitle) )
423 $section = "<span class='searchalttitle'>"
424 .wfMsg('search-section', $sk->makeKnownLinkObj( $sectionTitle, $sectionText))
425 ."</span>";
426
427 // format text extract
428 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
429
430 // format score
431 if( is_null( $result->getScore() ) ) {
432 // Search engine doesn't report scoring info
433 $score = '';
434 } else {
435 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
436 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
437 . ' - ';
438 }
439
440 // format description
441 $byteSize = $result->getByteSize();
442 $wordCount = $result->getWordCount();
443 $timestamp = $result->getTimestamp();
444 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
445 $sk->formatSize( $byteSize ),
446 $wordCount );
447 $date = $wgLang->timeanddate( $timestamp );
448
449 // link to related articles if supported
450 $related = '';
451 if( $result->hasRelated() ) {
452 $st = SpecialPage::getTitleFor( 'Search' );
453 $stParams = wfArrayToCGI( $this->powerSearchOptions(),
454 array('search' => wfMsgForContent('searchrelated').':'.$t->getPrefixedText(),
455 'fulltext' => wfMsg('search') ));
456
457 $related = ' -- <a href="'.$st->escapeLocalURL($stParams).'">'.
458 wfMsg('search-relatedarticle').'</a>';
459 }
460
461 // Include a thumbnail for media files...
462 if( $t->getNamespace() == NS_IMAGE ) {
463 $img = wfFindFile( $t );
464 if( $img ) {
465 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
466 if( $thumb ) {
467 $desc = $img->getShortDesc();
468 wfProfileOut( $fname );
469 // Float doesn't seem to interact well with the bullets.
470 // Table messes up vertical alignment of the bullets.
471 // Bullets are therefore disabled (didn't look great anyway).
472 return "<li>" .
473 '<table class="searchResultImage">' .
474 '<tr>' .
475 '<td width="120" align="center">' .
476 $thumb->toHtml( array( 'desc-link' => true ) ) .
477 '</td>' .
478 '<td valign="top">' .
479 $link .
480 $extract .
481 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
482 '</td>' .
483 '</tr>' .
484 '</table>' .
485 "</li>\n";
486 }
487 }
488 }
489
490 wfProfileOut( $fname );
491 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
492 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
493 "</li>\n";
494
495 }
496
497 /**
498 * Show results from other wikis
499 *
500 * @param SearchResultSet $matches
501 */
502 protected function showInterwiki( &$matches, $query ) {
503 $fname = 'SpecialSearch::showInterwiki';
504 wfProfileIn( $fname );
505
506 global $wgContLang;
507 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
508
509 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
510 wfMsg('search-interwiki-caption')."</div>\n";
511 $off = $this->offset + 1;
512 $out .= "<ul start='{$off}' class='mw-search-iwresults'>\n";
513
514 // work out custom project captions
515 $customCaptions = array();
516 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
517 foreach($customLines as $line) {
518 $parts = explode(":",$line,2);
519 if(count($parts) == 2) // validate line
520 $customCaptions[$parts[0]] = $parts[1];
521 }
522
523
524 $prev = null;
525 while( $result = $matches->next() ) {
526 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
527 $prev = $result->getInterwikiPrefix();
528 }
529 // FIXME: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
530 $out .= "</ul></div>\n";
531
532 // convert the whole thing to desired language variant
533 global $wgContLang;
534 $out = $wgContLang->convert( $out );
535 wfProfileOut( $fname );
536 return $out;
537 }
538
539 /**
540 * Show single interwiki link
541 *
542 * @param SearchResult $result
543 * @param string $lastInterwiki
544 * @param array $terms
545 * @param string $query
546 * @param array $customCaptions iw prefix -> caption
547 */
548 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
549 $fname = 'SpecialSearch::showInterwikiHit';
550 wfProfileIn( $fname );
551 global $wgUser, $wgContLang, $wgLang;
552
553 if( $result->isBrokenTitle() ) {
554 wfProfileOut( $fname );
555 return "<!-- Broken link in search result -->\n";
556 }
557
558 $t = $result->getTitle();
559 $sk = $wgUser->getSkin();
560
561 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
562
563 // format redirect if any
564 $redirectTitle = $result->getRedirectTitle();
565 $redirectText = $result->getRedirectSnippet($terms);
566 $redirect = '';
567 if( !is_null($redirectTitle) )
568 $redirect = "<span class='searchalttitle'>"
569 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
570 ."</span>";
571
572 $out = "";
573 // display project name
574 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
575 if( key_exists($t->getInterwiki(),$customCaptions) )
576 // captions from 'search-interwiki-custom'
577 $caption = $customCaptions[$t->getInterwiki()];
578 else{
579 // default is to show the hostname of the other wiki which might suck
580 // if there are many wikis on one hostname
581 $parsed = parse_url($t->getFullURL());
582 $caption = wfMsg('search-interwiki-default', $parsed['host']);
583 }
584 // "more results" link (special page stuff could be localized, but we might not know target lang)
585 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
586 $searchLink = $sk->makeKnownLinkObj( $searchTitle, wfMsg('search-interwiki-more'),
587 wfArrayToCGI(array('search' => $query, 'fulltext' => 'Search')));
588 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
589 {$searchLink}</span>{$caption}</div>\n<ul>";
590 }
591
592 $out .= "<li>{$link} {$redirect}</li>\n";
593 wfProfileOut( $fname );
594 return $out;
595 }
596
597
598 /**
599 * Generates the power search box at bottom of [[Special:Search]]
600 * @param $term string: search term
601 * @return $out string: HTML form
602 */
603 protected function powerSearchBox( $term ) {
604 global $wgScript;
605
606 $namespaces = '';
607 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
608 $name = str_replace( '_', ' ', $name );
609 if( '' == $name ) {
610 $name = wfMsg( 'blanknamespace' );
611 }
612 $namespaces .= Xml::openElement( 'span', array( 'style' => 'white-space: nowrap' ) ) .
613 Xml::checkLabel( $name, "ns{$ns}", "mw-search-ns{$ns}", in_array( $ns, $this->namespaces ) ) .
614 Xml::closeElement( 'span' ) . "\n";
615 }
616
617 if( $this->searchEngine->acceptListRedirects() ) {
618 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' ) );
619 $redirectLabel = Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
620 } else{
621 $redirect = '';
622 $redirectLabel = '';
623 }
624 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
625 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'fulltext' ) ) . "\n";
626 $searchTitle = SpecialPage::getTitleFor( 'Search' );
627
628 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
629 Xml::hidden( 'title', $searchTitle->getPrefixedText() ) .
630 Xml::hidden( 'advanced', 1 ) .
631 "<p>" .
632 wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) .
633 "<br />" .
634 $namespaces .
635 "</p>" .
636 "<p>" .
637 $redirect . " " . $redirectLabel .
638 "</p>" .
639 wfMsgExt( 'powersearch-field', array( 'parseinline' ) ) .
640 "&nbsp;" .
641 $searchField .
642 "&nbsp;" .
643 $searchButton .
644 ' (' . wfMsgExt('searchmenu-help',array('parseinline') ) . ')' .
645 "</form>";
646 if( $term )
647 $out .= wfMsgExt( 'searchmenu-prefix', array('parseinline'), $term );
648
649 return Xml::openElement( 'fieldset', array('id' => 'mw-searchoptions','style' => 'margin:0em;') ) .
650 Xml::element( 'legend', null, wfMsg('searchmenu-legend') ) .
651 $this->formHeader($term) . $out .
652 Xml::closeElement( 'fieldset' );
653 }
654
655 protected function powerSearchFocus() {
656 global $wgJsMimeType;
657 return "<script type=\"$wgJsMimeType\">" .
658 "hookEvent(\"load\", function() {" .
659 "document.getElementById('powerSearchText').focus();" .
660 "});" .
661 "</script>";
662 }
663
664 /** Make a search link with some target namespaces */
665 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params=array() ) {
666 $opt = $params;
667 foreach( $namespaces as $n ) {
668 $opt['ns' . $n] = 1;
669 }
670 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
671
672 $st = SpecialPage::getTitleFor( 'Search' );
673 $stParams = wfArrayToCGI( array( 'search' => $term, 'fulltext' => wfMsg( 'search' ) ), $opt );
674
675 return Xml::element( 'a',
676 array( 'href'=> $st->getLocalURL( $stParams ), 'title' => $tooltip ),
677 $label );
678 }
679
680 /** Check if query starts with image: prefix */
681 protected function startsWithImage( $term ) {
682 global $wgContLang;
683
684 $p = explode( ':', $term );
685 if( count( $p ) > 1 ) {
686 return $wgContLang->getNsIndex( $p[0] ) == NS_IMAGE;
687 }
688 return false;
689 }
690
691 protected function formHeader( $term ) {
692 global $wgContLang, $wgCanonicalNamespaceNames;
693
694 $sep = '&nbsp;&nbsp;&nbsp;';
695 $out = Xml::openElement('div', array( 'style' => 'padding-bottom:0.5em;' ) );
696
697 $bareterm = $term;
698 if( $this->startsWithImage( $term ) )
699 $bareterm = substr( $term, strpos( $term, ':' ) + 1 ); // delete all/image prefix
700
701 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
702 // figure out the active search profile header
703 if( $this->searchAdvanced )
704 $active = 'advanced';
705 else if( $this->namespaces === NS_IMAGE || $this->startsWithImage( $term ) )
706 $active = 'images';
707 elseif( $this->namespaces === $nsAllSet )
708 $active = 'all';
709 elseif( $this->namespaces === SearchEngine::defaultNamespaces() )
710 $active = 'default';
711 elseif( $this->namespaces === SearchEngine::defaultAndProjectNamespaces() )
712 $active = 'withproject';
713 elseif( $this->namespaces === SearchEngine::projectNamespaces() )
714 $active = 'project';
715 else
716 $active = 'advanced';
717
718
719 // search profiles headers
720 $m = wfMsg( 'searchprofile-articles' );
721 $tt = wfMsg( 'searchprofile-articles-tooltip',
722 implode( ', ', SearchEngine::namespacesAsText( SearchEngine::defaultNamespaces() ) ) );
723 if( $active == 'default' ) {
724 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
725 } else {
726 $out .= $this->makeSearchLink( $bareterm, SearchEngine::defaultNamespaces(), $m, $tt );
727 }
728 $out .= $sep;
729
730 $m = wfMsg( 'searchprofile-images' );
731 $tt = wfMsg( 'searchprofile-images-tooltip' );
732 if( $active == 'images' ) {
733 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
734 } else {
735 $out .= $this->makeSearchLink( $wgContLang->getFormattedNsText(NS_IMAGE).':'.$bareterm, array() , $m, $tt );
736 }
737 $out .= $sep;
738
739 $m = wfMsg( 'searchprofile-articles-and-proj' );
740 $tt = wfMsg( 'searchprofile-project-tooltip',
741 implode( ', ', SearchEngine::namespacesAsText( SearchEngine::defaultAndProjectNamespaces() ) ) );
742 if( $active == 'withproject' ) {
743 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
744 } else {
745 $out .= $this->makeSearchLink( $bareterm, SearchEngine::defaultAndProjectNamespaces(), $m, $tt );
746 }
747 $out .= $sep;
748
749 $m = wfMsg( 'searchprofile-project' );
750 $tt = wfMsg( 'searchprofile-project-tooltip',
751 implode( ', ', SearchEngine::namespacesAsText( SearchEngine::projectNamespaces() ) ) );
752 if( $active == 'project' ) {
753 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
754 } else {
755 $out .= $this->makeSearchLink( $bareterm, SearchEngine::projectNamespaces(), $m, $tt );
756 }
757 $out .= $sep;
758
759 $m = wfMsg( 'searchprofile-everything' );
760 $tt = wfMsg( 'searchprofile-everything-tooltip' );
761 if( $active == 'all' ) {
762 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
763 } else {
764 $out .= $this->makeSearchLink( $bareterm, $nsAllSet, $m, $tt );
765 }
766 $out .= $sep;
767
768 $m = wfMsg( 'searchprofile-advanced' );
769 $tt = wfMsg( 'searchprofile-advanced-tooltip' );
770 if( $active == 'advanced' ) {
771 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
772 } else {
773 $out .= $this->makeSearchLink( $bareterm, $this->namespaces, $m, $tt, array( 'advanced' => '1' ) );
774 }
775 $out .= Xml::closeElement('div') ;
776
777 return $out;
778 }
779
780 protected function shortDialog( $term ) {
781 global $wgScript;
782 $out = Xml::openElement( 'form', array( 'id' => 'search', 'method' => 'get', 'action' => $wgScript ) );
783 $searchTitle = SpecialPage::getTitleFor( 'Search' );
784 $out .= Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
785 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . "\n";
786 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
787 if( in_array( $ns, $this->namespaces ) ) {
788 $out .= Xml::hidden( "ns{$ns}", '1' );
789 }
790 }
791 $out .= Xml::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
792 $out .= ' (' . wfMsgExt('searchmenu-help',array('parseinline') ) . ')';
793 $out .= Xml::closeElement( 'form' );
794 if( $term )
795 $out .= wfMsgExt( 'searchmenu-prefix', array('parseinline'), $term );
796 return Xml::openElement( 'fieldset', array('id' => 'mw-searchoptions','style' => 'margin:0em;') ) .
797 Xml::element( 'legend', null, wfMsg('searchmenu-legend') ) .
798 $this->formHeader($term) . $out .
799 Xml::closeElement( 'fieldset' );
800 }
801 }