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