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