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