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