Fix archiveName to archiveNames (wrong declaration)
[lhc/web/wiklou.git] / includes / specials / SpecialSearch.php
1 <?php
2 /**
3 * Copyright (C) 2004 Brion Vibber <brion@pobox.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 */
20
21 /**
22 * Run text & title search and display the output
23 * @file
24 * @ingroup SpecialPage
25 */
26
27 /**
28 * Entry point
29 *
30 * @param $par String: (default '')
31 */
32 function wfSpecialSearch( $par = '' ) {
33 global $wgRequest, $wgUser;
34 // Strip underscores from title parameter; most of the time we'll want
35 // text form here. But don't strip underscores from actual text params!
36 $titleParam = str_replace( '_', ' ', $par );
37 // Fetch the search term
38 $search = str_replace( "\n", " ", $wgRequest->getText( 'search', $titleParam ) );
39 $searchPage = new SpecialSearch( $wgRequest, $wgUser );
40 if( $wgRequest->getVal( 'fulltext' )
41 || !is_null( $wgRequest->getVal( 'offset' ))
42 || !is_null( $wgRequest->getVal( 'searchx' )) )
43 {
44 $searchPage->showResults( $search );
45 } else {
46 $searchPage->goResult( $search );
47 }
48 }
49
50 /**
51 * implements Special:Search - Run text & title search and display the output
52 * @ingroup SpecialPage
53 */
54 class SpecialSearch {
55
56 /**
57 * Set up basic search parameters from the request and user settings.
58 * Typically you'll pass $wgRequest and $wgUser.
59 *
60 * @param $request WebRequest
61 * @param $user User
62 */
63 public function __construct( &$request, &$user ) {
64 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
65 $this->mPrefix = $request->getVal('prefix', '');
66 # Extract requested namespaces
67 $this->namespaces = $this->powerSearch( $request );
68 if( empty( $this->namespaces ) ) {
69 $this->namespaces = SearchEngine::userNamespaces( $user );
70 }
71 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
72 $this->searchAdvanced = $request->getVal( 'advanced' );
73 $this->active = 'advanced';
74 $this->sk = $user->getSkin();
75 $this->didYouMeanHtml = ''; # html of did you mean... link
76 $this->fulltext = $request->getVal('fulltext');
77 }
78
79 /**
80 * If an exact title match can be found, jump straight ahead to it.
81 *
82 * @param $term String
83 */
84 public function goResult( $term ) {
85 global $wgOut;
86 $this->setupPage( $term );
87 # Try to go to page as entered.
88 $t = Title::newFromText( $term );
89 # If the string cannot be used to create a title
90 if( is_null( $t ) ) {
91 return $this->showResults( $term );
92 }
93 # If there's an exact or very near match, jump right there.
94 $t = SearchEngine::getNearMatch( $term );
95 if( !is_null( $t ) ) {
96 wfRunHooks( 'SpecialSearchGomatch', array( &$t ) );
97 $wgOut->redirect( $t->getFullURL() );
98 return;
99 }
100 # No match, generate an edit URL
101 $t = Title::newFromText( $term );
102 if( !is_null( $t ) ) {
103 global $wgGoToEdit;
104 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
105 # If the feature is enabled, go straight to the edit page
106 if( $wgGoToEdit ) {
107 $wgOut->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
108 return;
109 }
110 }
111 return $this->showResults( $term );
112 }
113
114 /**
115 * @param $term String
116 */
117 public function showResults( $term ) {
118 global $wgOut, $wgUser, $wgDisableTextSearch, $wgContLang, $wgScript;
119 wfProfileIn( __METHOD__ );
120
121 $sk = $wgUser->getSkin();
122
123 $this->searchEngine = SearchEngine::create();
124 $search =& $this->searchEngine;
125 $search->setLimitOffset( $this->limit, $this->offset );
126 $search->setNamespaces( $this->namespaces );
127 $search->showRedirects = $this->searchRedirects;
128 $search->prefix = $this->mPrefix;
129 $term = $search->transformSearchTerm($term);
130
131 $this->setupPage( $term );
132
133 if( $wgDisableTextSearch ) {
134 global $wgSearchForwardUrl;
135 if( $wgSearchForwardUrl ) {
136 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
137 $wgOut->redirect( $url );
138 wfProfileOut( __METHOD__ );
139 return;
140 }
141 global $wgInputEncoding;
142 $wgOut->addHTML(
143 Xml::openElement( 'fieldset' ) .
144 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
145 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
146 wfMsg( 'googlesearch',
147 htmlspecialchars( $term ),
148 htmlspecialchars( $wgInputEncoding ),
149 htmlspecialchars( wfMsg( 'searchbutton' ) )
150 ) .
151 Xml::closeElement( 'fieldset' )
152 );
153 wfProfileOut( __METHOD__ );
154 return;
155 }
156
157 $t = Title::newFromText( $term );
158
159 // fetch search results
160 $rewritten = $search->replacePrefixes($term);
161
162 $titleMatches = $search->searchTitle( $rewritten );
163 if( !($titleMatches instanceof SearchResultTooMany))
164 $textMatches = $search->searchText( $rewritten );
165
166 // did you mean... suggestions
167 if( $textMatches && $textMatches->hasSuggestion() ) {
168 $st = SpecialPage::getTitleFor( 'Search' );
169
170 # mirror Go/Search behaviour of original request ..
171 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
172
173 if($this->fulltext != null)
174 $didYouMeanParams['fulltext'] = $this->fulltext;
175
176 $stParams = array_merge(
177 $didYouMeanParams,
178 $this->powerSearchOptions()
179 );
180
181 $suggestionSnippet = $textMatches->getSuggestionSnippet();
182
183 if( $suggestionSnippet == '' )
184 $suggestionSnippet = null;
185
186 $suggestLink = $sk->linkKnown(
187 $st,
188 $suggestionSnippet,
189 array(),
190 $stParams
191 );
192
193 $this->didYouMeanHtml = '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
194 }
195 // start rendering the page
196 $wgOut->addHtml(
197 Xml::openElement(
198 'form',
199 array(
200 'id' => ( $this->searchAdvanced ? 'powersearch' : 'search' ),
201 'method' => 'get',
202 'action' => $wgScript
203 )
204 )
205 );
206 $wgOut->addHtml(
207 Xml::openElement( 'table', array( 'id'=>'mw-search-top-table', 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
208 Xml::openElement( 'tr' ) .
209 Xml::openElement( 'td' ) . "\n" .
210 $this->shortDialog( $term ) .
211 Xml::closeElement('td') .
212 Xml::closeElement('tr') .
213 Xml::closeElement('table')
214 );
215
216 // Sometimes the search engine knows there are too many hits
217 if( $titleMatches instanceof SearchResultTooMany ) {
218 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
219 wfProfileOut( __METHOD__ );
220 return;
221 }
222
223 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE).':';
224 if( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
225 $wgOut->addHTML( $this->searchFocus() );
226 $wgOut->addHTML( $this->formHeader($term, 0, 0));
227 if( $this->searchAdvanced ) {
228 $wgOut->addHTML( $this->powerSearchBox( $term ) );
229 }
230 $wgOut->addHTML( '</form>' );
231 // Empty query -- straight view of search form
232 wfProfileOut( __METHOD__ );
233 return;
234 }
235
236 // Get number of results
237 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
238 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
239 // Total initial query matches (possible false positives)
240 $num = $titleMatchesNum + $textMatchesNum;
241
242 // Get total actual results (after second filtering, if any)
243 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
244 $titleMatches->getTotalHits() : $titleMatchesNum;
245 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
246 $textMatches->getTotalHits() : $textMatchesNum;
247
248 // get total number of results if backend can calculate it
249 $totalRes = 0;
250 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
251 $totalRes += $titleMatches->getTotalHits();
252 if($textMatches && !is_null( $textMatches->getTotalHits() ))
253 $totalRes += $textMatches->getTotalHits();
254
255 // show number of results and current offset
256 $wgOut->addHTML( $this->formHeader($term, $num, $totalRes));
257 if( $this->searchAdvanced ) {
258 $wgOut->addHTML( $this->powerSearchBox( $term ) );
259 }
260
261 $wgOut->addHtml( Xml::closeElement( 'form' ) );
262 $wgOut->addHtml( "<div class='searchresults'>" );
263
264 // prev/next links
265 if( $num || $this->offset ) {
266 // Show the create link ahead
267 $this->showCreateLink( $t );
268 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
269 SpecialPage::getTitleFor( 'Search' ),
270 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
271 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
272 );
273 //$wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
274 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
275 } else {
276 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
277 }
278
279 if( $titleMatches ) {
280 if( $numTitleMatches > 0 ) {
281 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
282 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
283 }
284 $titleMatches->free();
285 }
286 if( $textMatches ) {
287 // output appropriate heading
288 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
289 // if no title matches the heading is redundant
290 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
291 } elseif( $totalRes == 0 ) {
292 # Don't show the 'no text matches' if we received title matches
293 # $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
294 }
295 // show interwiki results if any
296 if( $textMatches->hasInterwikiResults() ) {
297 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
298 }
299 // show results
300 if( $numTextMatches > 0 ) {
301 $wgOut->addHTML( $this->showMatches( $textMatches ) );
302 }
303
304 $textMatches->free();
305 }
306 if( $num === 0 ) {
307 $wgOut->addWikiMsg( 'search-nonefound', wfEscapeWikiText( $term ) );
308 $this->showCreateLink( $t );
309 }
310 $wgOut->addHtml( "</div>" );
311 if( $num === 0 ) {
312 $wgOut->addHTML( $this->searchFocus() );
313 }
314
315 if( $num || $this->offset ) {
316 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
317 }
318 wfProfileOut( __METHOD__ );
319 }
320
321 protected function showCreateLink( $t ) {
322 global $wgOut;
323
324 // show direct page/create link if applicable
325 $messageName = null;
326 if( !is_null($t) ) {
327 if( $t->isKnown() ) {
328 $messageName = 'searchmenu-exists';
329 } elseif( $t->userCan( 'create' ) ) {
330 $messageName = 'searchmenu-new';
331 } else {
332 $messageName = 'searchmenu-new-nocreate';
333 }
334 }
335 if( $messageName ) {
336 $wgOut->addWikiMsg( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) );
337 } else {
338 // preserve the paragraph for margins etc...
339 $wgOut->addHtml( '<p></p>' );
340 }
341 }
342
343 /**
344 *
345 */
346 protected function setupPage( $term ) {
347 global $wgOut;
348 // Figure out the active search profile header
349 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
350 if( $this->searchAdvanced )
351 $this->active = 'advanced';
352 else {
353 $profiles = $this->getSearchProfiles();
354
355 foreach( $profiles as $key => $data ) {
356 if ( $this->namespaces == $data['namespaces'] && $key != 'advanced')
357 $this->active = $key;
358 }
359
360 }
361 # Should advanced UI be used?
362 $this->searchAdvanced = ($this->active === 'advanced');
363 if( !empty( $term ) ) {
364 $wgOut->setPageTitle( wfMsg( 'searchresults') );
365 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
366 }
367 $wgOut->setArticleRelated( false );
368 $wgOut->setRobotPolicy( 'noindex,nofollow' );
369 // add javascript specific to special:search
370 $wgOut->addScriptFile( 'search.js' );
371
372 // Bug #16886: Sister projects box moves down the first extract on IE7
373 $wgOut->addStyle( 'common/IE70Fixes.css', 'screen', 'IE 7' );
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 $off = $this->offset + 1;
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 $off = $this->offset + 1;
634 $out .= "<ul class='mw-search-iwresults'>\n";
635
636 // work out custom project captions
637 $customCaptions = array();
638 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
639 foreach($customLines as $line) {
640 $parts = explode(":",$line,2);
641 if(count($parts) == 2) // validate line
642 $customCaptions[$parts[0]] = $parts[1];
643 }
644
645 $prev = null;
646 while( $result = $matches->next() ) {
647 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
648 $prev = $result->getInterwikiPrefix();
649 }
650 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
651 $out .= "</ul></div>\n";
652
653 // convert the whole thing to desired language variant
654 $out = $wgContLang->convert( $out );
655 wfProfileOut( __METHOD__ );
656 return $out;
657 }
658
659 /**
660 * Show single interwiki link
661 *
662 * @param $result SearchResult
663 * @param $lastInterwiki String
664 * @param $terms Array
665 * @param $query String
666 * @param $customCaptions Array: iw prefix -> caption
667 */
668 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
669 wfProfileIn( __METHOD__ );
670
671 if( $result->isBrokenTitle() ) {
672 wfProfileOut( __METHOD__ );
673 return "<!-- Broken link in search result -->\n";
674 }
675
676 $t = $result->getTitle();
677
678 $titleSnippet = $result->getTitleSnippet($terms);
679
680 if( $titleSnippet == '' )
681 $titleSnippet = null;
682
683 $link = $this->sk->linkKnown(
684 $t,
685 $titleSnippet
686 );
687
688 // format redirect if any
689 $redirectTitle = $result->getRedirectTitle();
690 $redirectText = $result->getRedirectSnippet($terms);
691 $redirect = '';
692 if( !is_null($redirectTitle) ) {
693 if( $redirectText == '' )
694 $redirectText = null;
695
696 $redirect = "<span class='searchalttitle'>" .
697 wfMsg(
698 'search-redirect',
699 $this->sk->linkKnown(
700 $redirectTitle,
701 $redirectText
702 )
703 ) .
704 "</span>";
705 }
706
707 $out = "";
708 // display project name
709 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
710 if( key_exists($t->getInterwiki(),$customCaptions) )
711 // captions from 'search-interwiki-custom'
712 $caption = $customCaptions[$t->getInterwiki()];
713 else{
714 // default is to show the hostname of the other wiki which might suck
715 // if there are many wikis on one hostname
716 $parsed = parse_url($t->getFullURL());
717 $caption = wfMsg('search-interwiki-default', $parsed['host']);
718 }
719 // "more results" link (special page stuff could be localized, but we might not know target lang)
720 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
721 $searchLink = $this->sk->linkKnown(
722 $searchTitle,
723 wfMsg('search-interwiki-more'),
724 array(),
725 array(
726 'search' => $query,
727 'fulltext' => 'Search'
728 )
729 );
730 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
731 {$searchLink}</span>{$caption}</div>\n<ul>";
732 }
733
734 $out .= "<li>{$link} {$redirect}</li>\n";
735 wfProfileOut( __METHOD__ );
736 return $out;
737 }
738
739
740 /**
741 * Generates the power search box at bottom of [[Special:Search]]
742 *
743 * @param $term String: search term
744 * @return String: HTML form
745 */
746 protected function powerSearchBox( $term ) {
747 // Groups namespaces into rows according to subject
748 $rows = array();
749 foreach( SearchEngine::searchableNamespaces() as $namespace => $name ) {
750 $subject = MWNamespace::getSubject( $namespace );
751 if( !array_key_exists( $subject, $rows ) ) {
752 $rows[$subject] = "";
753 }
754 $name = str_replace( '_', ' ', $name );
755 if( $name == '' ) {
756 $name = wfMsg( 'blanknamespace' );
757 }
758 $rows[$subject] .=
759 Xml::openElement(
760 'td', array( 'style' => 'white-space: nowrap' )
761 ) .
762 Xml::checkLabel(
763 $name,
764 "ns{$namespace}",
765 "mw-search-ns{$namespace}",
766 in_array( $namespace, $this->namespaces )
767 ) .
768 Xml::closeElement( 'td' );
769 }
770 $rows = array_values( $rows );
771 $numRows = count( $rows );
772
773 // Lays out namespaces in multiple floating two-column tables so they'll
774 // be arranged nicely while still accommodating different screen widths
775 $namespaceTables = '';
776 for( $i = 0; $i < $numRows; $i += 4 ) {
777 $namespaceTables .= Xml::openElement(
778 'table',
779 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
780 );
781 for( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
782 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
783 }
784 $namespaceTables .= Xml::closeElement( 'table' );
785 }
786 // Show redirects check only if backend supports it
787 $redirects = '';
788 if( $this->searchEngine->acceptListRedirects() ) {
789 $redirects =
790 Xml::check(
791 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' )
792 ) .
793 ' ' .
794 Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
795 }
796 // Return final output
797 return
798 Xml::openElement(
799 'fieldset',
800 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
801 ) .
802 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
803 Xml::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
804 Xml::tags(
805 'div',
806 array( 'id' => 'mw-search-togglebox' ),
807 Xml::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
808 Xml::element(
809 'input',
810 array(
811 'type'=>'button',
812 'id' => 'mw-search-toggleall',
813 'onclick' => 'mwToggleSearchCheckboxes("all");',
814 'value' => wfMsg( 'powersearch-toggleall' )
815 )
816 ) .
817 Xml::element(
818 'input',
819 array(
820 'type'=>'button',
821 'id' => 'mw-search-togglenone',
822 'onclick' => 'mwToggleSearchCheckboxes("none");',
823 'value' => wfMsg( 'powersearch-togglenone' )
824 )
825 )
826 ) .
827 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
828 $namespaceTables .
829 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
830 $redirects .
831 Xml::hidden( 'title', SpecialPage::getTitleFor( 'Search' )->getPrefixedText() ) .
832 Xml::hidden( 'advanced', $this->searchAdvanced ) .
833 Xml::hidden( 'fulltext', 'Advanced search' ) .
834 Xml::closeElement( 'fieldset' );
835 }
836
837 protected function searchFocus() {
838 $id = $this->searchAdvanced ? 'powerSearchText' : 'searchText';
839 return Html::inlineScript(
840 "hookEvent(\"load\", function() {" .
841 "document.getElementById('$id').focus();" .
842 "});" );
843 }
844
845 protected function getSearchProfiles() {
846 // Builds list of Search Types (profiles)
847 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
848
849 $profiles = array(
850 'default' => array(
851 'message' => 'searchprofile-articles',
852 'tooltip' => 'searchprofile-articles-tooltip',
853 'namespaces' => SearchEngine::defaultNamespaces(),
854 'namespace-messages' => SearchEngine::namespacesAsText(
855 SearchEngine::defaultNamespaces()
856 ),
857 ),
858 'images' => array(
859 'message' => 'searchprofile-images',
860 'tooltip' => 'searchprofile-images-tooltip',
861 'namespaces' => array( NS_FILE ),
862 ),
863 'help' => array(
864 'message' => 'searchprofile-project',
865 'tooltip' => 'searchprofile-project-tooltip',
866 'namespaces' => SearchEngine::helpNamespaces(),
867 'namespace-messages' => SearchEngine::namespacesAsText(
868 SearchEngine::helpNamespaces()
869 ),
870 ),
871 'all' => array(
872 'message' => 'searchprofile-everything',
873 'tooltip' => 'searchprofile-everything-tooltip',
874 'namespaces' => $nsAllSet,
875 ),
876 'advanced' => array(
877 'message' => 'searchprofile-advanced',
878 'tooltip' => 'searchprofile-advanced-tooltip',
879 'namespaces' => $this->namespaces,
880 'parameters' => array( 'advanced' => 1 ),
881 )
882 );
883
884 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
885
886 foreach( $profiles as $key => &$data ) {
887 sort($data['namespaces']);
888 }
889
890 return $profiles;
891 }
892
893 protected function formHeader( $term, $resultsShown, $totalNum ) {
894 global $wgLang;
895
896 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
897
898 $bareterm = $term;
899 if( $this->startsWithImage( $term ) ) {
900 // Deletes prefixes
901 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
902 }
903
904 $profiles = $this->getSearchProfiles();
905
906 // Outputs XML for Search Types
907 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
908 $out .= Xml::openElement( 'ul' );
909 foreach ( $profiles as $id => $profile ) {
910 $tooltipParam = isset( $profile['namespace-messages'] ) ?
911 $wgLang->commaList( $profile['namespace-messages'] ) : null;
912 $out .= Xml::tags(
913 'li',
914 array(
915 'class' => $this->active == $id ? 'current' : 'normal'
916 ),
917 $this->makeSearchLink(
918 $bareterm,
919 $profile['namespaces'],
920 wfMsg( $profile['message'] ),
921 wfMsg( $profile['tooltip'], $tooltipParam ),
922 isset( $profile['parameters'] ) ? $profile['parameters'] : array()
923 )
924 );
925 }
926 $out .= Xml::closeElement( 'ul' );
927 $out .= Xml::closeElement('div') ;
928
929 // Results-info
930 if ( $resultsShown > 0 ) {
931 if ( $totalNum > 0 ){
932 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
933 $wgLang->formatNum( $this->offset + 1 ),
934 $wgLang->formatNum( $this->offset + $resultsShown ),
935 $wgLang->formatNum( $totalNum ),
936 wfEscapeWikiText( $term ),
937 $wgLang->formatNum( $resultsShown )
938 );
939 } elseif ( $resultsShown >= $this->limit ) {
940 $top = wfShowingResults( $this->offset, $this->limit );
941 } else {
942 $top = wfShowingResultsNum( $this->offset, $this->limit, $resultsShown );
943 }
944 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
945 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
946 );
947 }
948
949 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
950 $out .= Xml::closeElement('div');
951
952 // Adds hidden namespace fields
953 if ( !$this->searchAdvanced ) {
954 foreach( $this->namespaces as $ns ) {
955 $out .= Xml::hidden( "ns{$ns}", '1' );
956 }
957 }
958
959 return $out;
960 }
961
962 protected function shortDialog( $term ) {
963 $searchTitle = SpecialPage::getTitleFor( 'Search' );
964 $out = Html::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
965 // Keep redirect setting
966 $out .= Html::hidden( "redirs", (int)$this->searchRedirects ) . "\n";
967 // Term box
968 $out .= Html::input( 'search', $term, 'search', array(
969 'id' => $this->searchAdvanced ? 'powerSearchText' : 'searchText',
970 'size' => '50',
971 'autofocus'
972 ) ) . "\n";
973 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
974 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
975 return $out . $this->didYouMeanHtml;
976 }
977
978 /**
979 * Make a search link with some target namespaces
980 *
981 * @param $term String
982 * @param $namespaces Array
983 * @param $label String: link's text
984 * @param $tooltip String: link's tooltip
985 * @param $params Array: query string parameters
986 * @return String: HTML fragment
987 */
988 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params=array() ) {
989 $opt = $params;
990 foreach( $namespaces as $n ) {
991 $opt['ns' . $n] = 1;
992 }
993 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
994
995 $st = SpecialPage::getTitleFor( 'Search' );
996 $stParams = array_merge(
997 array(
998 'search' => $term,
999 'fulltext' => wfMsg( 'search' )
1000 ),
1001 $opt
1002 );
1003
1004 return Xml::element(
1005 'a',
1006 array(
1007 'href' => $st->getLocalURL( $stParams ),
1008 'title' => $tooltip,
1009 'onmousedown' => 'mwSearchHeaderClick(this);',
1010 'onkeydown' => 'mwSearchHeaderClick(this);'),
1011 $label
1012 );
1013 }
1014
1015 /**
1016 * Check if query starts with image: prefix
1017 *
1018 * @param $term String: the string to check
1019 * @return Boolean
1020 */
1021 protected function startsWithImage( $term ) {
1022 global $wgContLang;
1023
1024 $p = explode( ':', $term );
1025 if( count( $p ) > 1 ) {
1026 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1027 }
1028 return false;
1029 }
1030
1031 /**
1032 * Check if query starts with all: prefix
1033 *
1034 * @param $term String: the string to check
1035 * @return Boolean
1036 */
1037 protected function startsWithAll( $term ) {
1038
1039 $allkeyword = wfMsgForContent('searchall');
1040
1041 $p = explode( ':', $term );
1042 if( count( $p ) > 1 ) {
1043 return $p[0] == $allkeyword;
1044 }
1045 return false;
1046 }
1047 }
1048