More reversion of r77297, 2 of 2 commits to keep it readable in CR (hopefully)
[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->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", array( '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->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", array( $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.special.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 $out .= "<ul class='mw-search-results'>\n";
420 while( $result = $matches->next() ) {
421 $out .= $this->showHit( $result, $terms );
422 }
423 $out .= "</ul>\n";
424
425 // convert the whole thing to desired language variant
426 $out = $wgContLang->convert( $out );
427 wfProfileOut( __METHOD__ );
428 return $out;
429 }
430
431 /**
432 * Format a single hit result
433 *
434 * @param $result SearchResult
435 * @param $terms Array: terms to highlight
436 */
437 protected function showHit( $result, $terms ) {
438 global $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
543 if( $t->getNamespace() == NS_CATEGORY ) {
544 $cat = Category::newFromTitle( $t );
545 $size = wfMsgExt(
546 'search-result-category-size',
547 array( 'parsemag', 'escape' ),
548 $wgLang->formatNum( $cat->getPageCount() ),
549 $wgLang->formatNum( $cat->getSubcatCount() ),
550 $wgLang->formatNum( $cat->getFileCount() )
551 );
552 }
553
554 $date = $wgLang->timeanddate( $timestamp );
555
556 // link to related articles if supported
557 $related = '';
558 if( $result->hasRelated() ) {
559 $st = SpecialPage::getTitleFor( 'Search' );
560 $stParams = array_merge(
561 $this->powerSearchOptions(),
562 array(
563 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
564 'fulltext' => wfMsg( 'search' )
565 )
566 );
567
568 $related = ' -- ' . $sk->linkKnown(
569 $st,
570 wfMsg('search-relatedarticle'),
571 array(),
572 $stParams
573 );
574 }
575
576 // Include a thumbnail for media files...
577 if( $t->getNamespace() == NS_FILE ) {
578 $img = wfFindFile( $t );
579 if( $img ) {
580 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
581 if( $thumb ) {
582 $desc = $img->getShortDesc();
583 wfProfileOut( __METHOD__ );
584 // Float doesn't seem to interact well with the bullets.
585 // Table messes up vertical alignment of the bullets.
586 // Bullets are therefore disabled (didn't look great anyway).
587 return "<li>" .
588 '<table class="searchResultImage">' .
589 '<tr>' .
590 '<td width="120" align="center" valign="top">' .
591 $thumb->toHtml( array( 'desc-link' => true ) ) .
592 '</td>' .
593 '<td valign="top">' .
594 $link .
595 $extract .
596 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
597 '</td>' .
598 '</tr>' .
599 '</table>' .
600 "</li>\n";
601 }
602 }
603 }
604
605 wfProfileOut( __METHOD__ );
606 return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
607 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
608 "</li>\n";
609
610 }
611
612 /**
613 * Show results from other wikis
614 *
615 * @param $matches SearchResultSet
616 * @param $query String
617 */
618 protected function showInterwiki( &$matches, $query ) {
619 global $wgContLang;
620 wfProfileIn( __METHOD__ );
621 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
622
623 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
624 wfMsg('search-interwiki-caption')."</div>\n";
625 $out .= "<ul class='mw-search-iwresults'>\n";
626
627 // work out custom project captions
628 $customCaptions = array();
629 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
630 foreach($customLines as $line) {
631 $parts = explode(":",$line,2);
632 if(count($parts) == 2) // validate line
633 $customCaptions[$parts[0]] = $parts[1];
634 }
635
636 $prev = null;
637 while( $result = $matches->next() ) {
638 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
639 $prev = $result->getInterwikiPrefix();
640 }
641 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
642 $out .= "</ul></div>\n";
643
644 // convert the whole thing to desired language variant
645 $out = $wgContLang->convert( $out );
646 wfProfileOut( __METHOD__ );
647 return $out;
648 }
649
650 /**
651 * Show single interwiki link
652 *
653 * @param $result SearchResult
654 * @param $lastInterwiki String
655 * @param $terms Array
656 * @param $query String
657 * @param $customCaptions Array: iw prefix -> caption
658 */
659 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
660 wfProfileIn( __METHOD__ );
661
662 if( $result->isBrokenTitle() ) {
663 wfProfileOut( __METHOD__ );
664 return "<!-- Broken link in search result -->\n";
665 }
666
667 $t = $result->getTitle();
668
669 $titleSnippet = $result->getTitleSnippet($terms);
670
671 if( $titleSnippet == '' )
672 $titleSnippet = null;
673
674 $link = $this->sk->linkKnown(
675 $t,
676 $titleSnippet
677 );
678
679 // format redirect if any
680 $redirectTitle = $result->getRedirectTitle();
681 $redirectText = $result->getRedirectSnippet($terms);
682 $redirect = '';
683 if( !is_null($redirectTitle) ) {
684 if( $redirectText == '' )
685 $redirectText = null;
686
687 $redirect = "<span class='searchalttitle'>" .
688 wfMsg(
689 'search-redirect',
690 $this->sk->linkKnown(
691 $redirectTitle,
692 $redirectText
693 )
694 ) .
695 "</span>";
696 }
697
698 $out = "";
699 // display project name
700 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
701 if( key_exists($t->getInterwiki(),$customCaptions) )
702 // captions from 'search-interwiki-custom'
703 $caption = $customCaptions[$t->getInterwiki()];
704 else{
705 // default is to show the hostname of the other wiki which might suck
706 // if there are many wikis on one hostname
707 $parsed = parse_url($t->getFullURL());
708 $caption = wfMsg('search-interwiki-default', $parsed['host']);
709 }
710 // "more results" link (special page stuff could be localized, but we might not know target lang)
711 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
712 $searchLink = $this->sk->linkKnown(
713 $searchTitle,
714 wfMsg('search-interwiki-more'),
715 array(),
716 array(
717 'search' => $query,
718 'fulltext' => 'Search'
719 )
720 );
721 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
722 {$searchLink}</span>{$caption}</div>\n<ul>";
723 }
724
725 $out .= "<li>{$link} {$redirect}</li>\n";
726 wfProfileOut( __METHOD__ );
727 return $out;
728 }
729
730
731 /**
732 * Generates the power search box at bottom of [[Special:Search]]
733 *
734 * @param $term String: search term
735 * @return String: HTML form
736 */
737 protected function powerSearchBox( $term ) {
738 // Groups namespaces into rows according to subject
739 $rows = array();
740 foreach( SearchEngine::searchableNamespaces() as $namespace => $name ) {
741 $subject = MWNamespace::getSubject( $namespace );
742 if( !array_key_exists( $subject, $rows ) ) {
743 $rows[$subject] = "";
744 }
745 $name = str_replace( '_', ' ', $name );
746 if( $name == '' ) {
747 $name = wfMsg( 'blanknamespace' );
748 }
749 $rows[$subject] .=
750 Xml::openElement(
751 'td', array( 'style' => 'white-space: nowrap' )
752 ) .
753 Xml::checkLabel(
754 $name,
755 "ns{$namespace}",
756 "mw-search-ns{$namespace}",
757 in_array( $namespace, $this->namespaces )
758 ) .
759 Xml::closeElement( 'td' );
760 }
761 $rows = array_values( $rows );
762 $numRows = count( $rows );
763
764 // Lays out namespaces in multiple floating two-column tables so they'll
765 // be arranged nicely while still accommodating different screen widths
766 $namespaceTables = '';
767 for( $i = 0; $i < $numRows; $i += 4 ) {
768 $namespaceTables .= Xml::openElement(
769 'table',
770 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
771 );
772 for( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
773 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
774 }
775 $namespaceTables .= Xml::closeElement( 'table' );
776 }
777 // Show redirects check only if backend supports it
778 $redirects = '';
779 if( $this->searchEngine->acceptListRedirects() ) {
780 $redirects =
781 Xml::check(
782 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' )
783 ) .
784 ' ' .
785 Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
786 }
787 // Return final output
788 return
789 Xml::openElement(
790 'fieldset',
791 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
792 ) .
793 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
794 Xml::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
795 Xml::tags(
796 'div',
797 array( 'id' => 'mw-search-togglebox' ),
798 Xml::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
799 Xml::element(
800 'input',
801 array(
802 'type'=>'button',
803 'id' => 'mw-search-toggleall',
804 'onclick' => 'mwToggleSearchCheckboxes("all");',
805 'value' => wfMsg( 'powersearch-toggleall' )
806 )
807 ) .
808 Xml::element(
809 'input',
810 array(
811 'type'=>'button',
812 'id' => 'mw-search-togglenone',
813 'onclick' => 'mwToggleSearchCheckboxes("none");',
814 'value' => wfMsg( 'powersearch-togglenone' )
815 )
816 )
817 ) .
818 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
819 $namespaceTables .
820 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
821 $redirects .
822 Html::hidden( 'title', SpecialPage::getTitleFor( 'Search' )->getPrefixedText() ) .
823 Html::hidden( 'advanced', $this->searchAdvanced ) .
824 Html::hidden( 'fulltext', 'Advanced search' ) .
825 Xml::closeElement( 'fieldset' );
826 }
827
828 protected function getSearchProfiles() {
829 // Builds list of Search Types (profiles)
830 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
831
832 $profiles = array(
833 'default' => array(
834 'message' => 'searchprofile-articles',
835 'tooltip' => 'searchprofile-articles-tooltip',
836 'namespaces' => SearchEngine::defaultNamespaces(),
837 'namespace-messages' => SearchEngine::namespacesAsText(
838 SearchEngine::defaultNamespaces()
839 ),
840 ),
841 'images' => array(
842 'message' => 'searchprofile-images',
843 'tooltip' => 'searchprofile-images-tooltip',
844 'namespaces' => array( NS_FILE ),
845 ),
846 'help' => array(
847 'message' => 'searchprofile-project',
848 'tooltip' => 'searchprofile-project-tooltip',
849 'namespaces' => SearchEngine::helpNamespaces(),
850 'namespace-messages' => SearchEngine::namespacesAsText(
851 SearchEngine::helpNamespaces()
852 ),
853 ),
854 'all' => array(
855 'message' => 'searchprofile-everything',
856 'tooltip' => 'searchprofile-everything-tooltip',
857 'namespaces' => $nsAllSet,
858 ),
859 'advanced' => array(
860 'message' => 'searchprofile-advanced',
861 'tooltip' => 'searchprofile-advanced-tooltip',
862 'namespaces' => $this->namespaces,
863 'parameters' => array( 'advanced' => 1 ),
864 )
865 );
866
867 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
868
869 foreach( $profiles as &$data ) {
870 sort($data['namespaces']);
871 }
872
873 return $profiles;
874 }
875
876 protected function formHeader( $term, $resultsShown, $totalNum ) {
877 global $wgLang;
878
879 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
880
881 $bareterm = $term;
882 if( $this->startsWithImage( $term ) ) {
883 // Deletes prefixes
884 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
885 }
886
887 $profiles = $this->getSearchProfiles();
888
889 // Outputs XML for Search Types
890 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
891 $out .= Xml::openElement( 'ul' );
892 foreach ( $profiles as $id => $profile ) {
893 $tooltipParam = isset( $profile['namespace-messages'] ) ?
894 $wgLang->commaList( $profile['namespace-messages'] ) : null;
895 $out .= Xml::tags(
896 'li',
897 array(
898 'class' => $this->active == $id ? 'current' : 'normal'
899 ),
900 $this->makeSearchLink(
901 $bareterm,
902 $profile['namespaces'],
903 wfMsg( $profile['message'] ),
904 wfMsg( $profile['tooltip'], $tooltipParam ),
905 isset( $profile['parameters'] ) ? $profile['parameters'] : array()
906 )
907 );
908 }
909 $out .= Xml::closeElement( 'ul' );
910 $out .= Xml::closeElement('div') ;
911
912 // Results-info
913 if ( $resultsShown > 0 ) {
914 if ( $totalNum > 0 ){
915 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
916 $wgLang->formatNum( $this->offset + 1 ),
917 $wgLang->formatNum( $this->offset + $resultsShown ),
918 $wgLang->formatNum( $totalNum ),
919 wfEscapeWikiText( $term ),
920 $wgLang->formatNum( $resultsShown )
921 );
922 } elseif ( $resultsShown >= $this->limit ) {
923 $top = wfShowingResults( $this->offset, $this->limit );
924 } else {
925 $top = wfShowingResultsNum( $this->offset, $this->limit, $resultsShown );
926 }
927 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
928 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
929 );
930 }
931
932 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
933 $out .= Xml::closeElement('div');
934
935 // Adds hidden namespace fields
936 if ( !$this->searchAdvanced ) {
937 foreach( $this->namespaces as $ns ) {
938 $out .= Html::hidden( "ns{$ns}", '1' );
939 }
940 }
941
942 return $out;
943 }
944
945 protected function shortDialog( $term ) {
946 $searchTitle = SpecialPage::getTitleFor( 'Search' );
947 $out = Html::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
948 // Keep redirect setting
949 $out .= Html::hidden( "redirs", (int)$this->searchRedirects ) . "\n";
950 // Term box
951 $out .= Html::input( 'search', $term, 'search', array(
952 'id' => $this->searchAdvanced ? 'powerSearchText' : 'searchText',
953 'size' => '50',
954 'autofocus'
955 ) ) . "\n";
956 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
957 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
958 return $out . $this->didYouMeanHtml;
959 }
960
961 /**
962 * Make a search link with some target namespaces
963 *
964 * @param $term String
965 * @param $namespaces Array
966 * @param $label String: link's text
967 * @param $tooltip String: link's tooltip
968 * @param $params Array: query string parameters
969 * @return String: HTML fragment
970 */
971 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params=array() ) {
972 $opt = $params;
973 foreach( $namespaces as $n ) {
974 $opt['ns' . $n] = 1;
975 }
976 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
977
978 $st = SpecialPage::getTitleFor( 'Search' );
979 $stParams = array_merge(
980 array(
981 'search' => $term,
982 'fulltext' => wfMsg( 'search' )
983 ),
984 $opt
985 );
986
987 return Xml::element(
988 'a',
989 array(
990 'href' => $st->getLocalURL( $stParams ),
991 'title' => $tooltip,
992 'onmousedown' => 'mwSearchHeaderClick(this);',
993 'onkeydown' => 'mwSearchHeaderClick(this);'),
994 $label
995 );
996 }
997
998 /**
999 * Check if query starts with image: prefix
1000 *
1001 * @param $term String: the string to check
1002 * @return Boolean
1003 */
1004 protected function startsWithImage( $term ) {
1005 global $wgContLang;
1006
1007 $p = explode( ':', $term );
1008 if( count( $p ) > 1 ) {
1009 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1010 }
1011 return false;
1012 }
1013
1014 /**
1015 * Check if query starts with all: prefix
1016 *
1017 * @param $term String: the string to check
1018 * @return Boolean
1019 */
1020 protected function startsWithAll( $term ) {
1021
1022 $allkeyword = wfMsgForContent('searchall');
1023
1024 $p = explode( ':', $term );
1025 if( count( $p ) > 1 ) {
1026 return $p[0] == $allkeyword;
1027 }
1028 return false;
1029 }
1030 }
1031