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