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