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