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