* Use $wgLang->commaList( array ) instead of implode( ', ', array ) where possible
[lhc/web/wiklou.git] / includes / specials / SpecialSearch.php
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21 * Run text & title search and display the output
22 * @file
23 * @ingroup SpecialPage
24 */
25
26 /**
27 * Entry point
28 *
29 * @param $par String: (default '')
30 */
31 function wfSpecialSearch( $par = '' ) {
32 global $wgRequest, $wgUser, $wgUseOldSearchUI;
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 $class = $wgUseOldSearchUI ? 'SpecialSearchOld' : 'SpecialSearch';
39 $searchPage = new $class( $wgRequest, $wgUser );
40 if( $wgRequest->getVal( 'fulltext' )
41 || !is_null( $wgRequest->getVal( 'offset' ))
42 || !is_null( $wgRequest->getVal( 'searchx' )) )
43 {
44 $searchPage->showResults( $search );
45 } else {
46 $searchPage->goResult( $search );
47 }
48 }
49
50 /**
51 * implements Special:Search - Run text & title search and display the output
52 * @ingroup SpecialPage
53 */
54 class SpecialSearch {
55
56 /**
57 * Set up basic search parameters from the request and user settings.
58 * Typically you'll pass $wgRequest and $wgUser.
59 *
60 * @param WebRequest $request
61 * @param User $user
62 * @public
63 */
64 function __construct( &$request, &$user ) {
65 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
66 $this->mPrefix = $request->getVal('prefix', '');
67 # Extract requested namespaces
68 $this->namespaces = $this->powerSearch( $request );
69 if( empty( $this->namespaces ) ) {
70 $this->namespaces = SearchEngine::userNamespaces( $user );
71 }
72 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
73 $this->searchAdvanced = $request->getVal( 'advanced' );
74 $this->active = 'advanced';
75 $this->sk = $user->getSkin();
76 $this->didYouMeanHtml = ''; # html of did you mean... link
77 }
78
79 /**
80 * If an exact title match can be found, jump straight ahead to it.
81 * @param string $term
82 */
83 public function goResult( $term ) {
84 global $wgOut;
85 $this->setupPage( $term );
86 # Try to go to page as entered.
87 $t = Title::newFromText( $term );
88 # If the string cannot be used to create a title
89 if( is_null( $t ) ) {
90 return $this->showResults( $term );
91 }
92 # If there's an exact or very near match, jump right there.
93 $t = SearchEngine::getNearMatch( $term );
94 if( !is_null( $t ) ) {
95 $wgOut->redirect( $t->getFullURL() );
96 return;
97 }
98 # No match, generate an edit URL
99 $t = Title::newFromText( $term );
100 if( !is_null( $t ) ) {
101 global $wgGoToEdit;
102 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
103 # If the feature is enabled, go straight to the edit page
104 if( $wgGoToEdit ) {
105 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
106 return;
107 }
108 }
109 return $this->showResults( $term );
110 }
111
112 /**
113 * @param string $term
114 */
115 public function showResults( $term ) {
116 global $wgOut, $wgUser, $wgDisableTextSearch, $wgContLang;
117 wfProfileIn( __METHOD__ );
118
119 $sk = $wgUser->getSkin();
120
121 $this->searchEngine = SearchEngine::create();
122 $search =& $this->searchEngine;
123 $search->setLimitOffset( $this->limit, $this->offset );
124 $search->setNamespaces( $this->namespaces );
125 $search->showRedirects = $this->searchRedirects;
126 $search->prefix = $this->mPrefix;
127 $term = $search->transformSearchTerm($term);
128
129 $this->setupPage( $term );
130
131 if( $wgDisableTextSearch ) {
132 global $wgSearchForwardUrl;
133 if( $wgSearchForwardUrl ) {
134 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
135 $wgOut->redirect( $url );
136 wfProfileOut( __METHOD__ );
137 return;
138 }
139 global $wgInputEncoding;
140 $wgOut->addHTML(
141 Xml::openElement( 'fieldset' ) .
142 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
143 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
144 wfMsg( 'googlesearch',
145 htmlspecialchars( $term ),
146 htmlspecialchars( $wgInputEncoding ),
147 htmlspecialchars( wfMsg( 'searchbutton' ) )
148 ) .
149 Xml::closeElement( 'fieldset' )
150 );
151 wfProfileOut( __METHOD__ );
152 return;
153 }
154
155 $t = Title::newFromText( $term );
156
157 // fetch search results
158 $rewritten = $search->replacePrefixes($term);
159
160 $titleMatches = $search->searchTitle( $rewritten );
161 if( !($titleMatches instanceof SearchResultTooMany))
162 $textMatches = $search->searchText( $rewritten );
163
164 // did you mean... suggestions
165 if( $textMatches && $textMatches->hasSuggestion() ) {
166 $st = SpecialPage::getTitleFor( 'Search' );
167 $stParams = wfArrayToCGI(
168 array( 'search' => $textMatches->getSuggestionQuery(), 'fulltext' => wfMsg('search') ),
169 $this->powerSearchOptions()
170 );
171 $suggestLink = $sk->makeKnownLinkObj( $st,
172 $textMatches->getSuggestionSnippet(),
173 $stParams );
174
175 $this->didYouMeanHtml = '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
176 }
177
178 // start rendering the page
179 $wgOut->addHtml(
180 Xml::openElement( 'table', array( 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
181 Xml::openElement( 'tr' ) .
182 Xml::openElement( 'td' ) . "\n" .
183 ( $this->searchAdvanced ? $this->powerSearchBox( $term ) : $this->shortDialog( $term ) ) .
184 Xml::closeElement('td') .
185 Xml::closeElement('tr') .
186 Xml::closeElement('table')
187 );
188
189 // Sometimes the search engine knows there are too many hits
190 if( $titleMatches instanceof SearchResultTooMany ) {
191 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
192 wfProfileOut( __METHOD__ );
193 return;
194 }
195
196 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE).':';
197 if( '' === trim( $term ) || $filePrefix === trim( $term ) ) {
198 $wgOut->addHTML( $this->searchAdvanced ? $this->powerSearchFocus() : $this->searchFocus() );
199 // Empty query -- straight view of search form
200 wfProfileOut( __METHOD__ );
201 return;
202 }
203
204 // show direct page/create link
205 if( !is_null($t) ) {
206 if( !$t->exists() ) {
207 $wgOut->addWikiMsg( 'searchmenu-new', wfEscapeWikiText( $t->getPrefixedText() ) );
208 } else {
209 $wgOut->addWikiMsg( 'searchmenu-exists', wfEscapeWikiText( $t->getPrefixedText() ) );
210 }
211 }
212
213 // Get number of results
214 $titleMatchesSQL = $titleMatches ? $titleMatches->numRows() : 0;
215 $textMatchesSQL = $textMatches ? $textMatches->numRows() : 0;
216 // Total initial query matches (possible false positives)
217 $numSQL = $titleMatchesSQL + $textMatchesSQL;
218 // Get total actual results (after second filtering, if any)
219 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
220 $titleMatches->getTotalHits() : $titleMatchesSQL;
221 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
222 $textMatches->getTotalHits() : $textMatchesSQL;
223 $totalRes = $numTitleMatches + $numTextMatches;
224
225 // show number of results and current offset
226 if( $numSQL > 0 ) {
227 if( $numSQL > 0 ) {
228 $top = wfMsgExt('showingresultstotal', array( 'parseinline' ),
229 $this->offset+1, $this->offset+$numSQL, $totalRes, $numSQL );
230 } elseif( $numSQL >= $this->limit ) {
231 $top = wfShowingResults( $this->offset, $this->limit );
232 } else {
233 $top = wfShowingResultsNum( $this->offset, $this->limit, $numSQL );
234 }
235 $wgOut->addHTML( "<p class='mw-search-numberresults'>{$top}</p>\n" );
236 }
237
238 // prev/next links
239 if( $numSQL || $this->offset ) {
240 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
241 SpecialPage::getTitleFor( 'Search' ),
242 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
243 max( $titleMatchesSQL, $textMatchesSQL ) < $this->limit
244 );
245 $wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
246 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
247 } else {
248 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
249 }
250
251 $wgOut->addHtml( "<div class='searchresults'>" );
252 if( $titleMatches ) {
253 if( $numTitleMatches > 0 ) {
254 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
255 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
256 }
257 $titleMatches->free();
258 }
259 if( $textMatches ) {
260 // output appropriate heading
261 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
262 // if no title matches the heading is redundant
263 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
264 } elseif( $totalRes == 0 ) {
265 # Don't show the 'no text matches' if we received title matches
266 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
267 }
268 // show interwiki results if any
269 if( $textMatches->hasInterwikiResults() ) {
270 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
271 }
272 // show results
273 if( $numTextMatches > 0 ) {
274 $wgOut->addHTML( $this->showMatches( $textMatches ) );
275 }
276
277 $textMatches->free();
278 }
279 if( $totalRes === 0 ) {
280 $wgOut->addWikiMsg( 'search-nonefound' );
281 }
282 $wgOut->addHtml( "</div>" );
283 if( $totalRes === 0 ) {
284 $wgOut->addHTML( $this->searchAdvanced ? $this->powerSearchFocus() : $this->searchFocus() );
285 }
286
287 if( $numSQL || $this->offset ) {
288 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
289 }
290 wfProfileOut( __METHOD__ );
291 }
292
293 /**
294 *
295 */
296 protected function setupPage( $term ) {
297 global $wgOut;
298 // Figure out the active search profile header
299 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
300 if( $this->searchAdvanced )
301 $this->active = 'advanced';
302 else if( $this->namespaces === NS_FILE || $this->startsWithImage( $term ) )
303 $this->active = 'images';
304 elseif( $this->namespaces === $nsAllSet )
305 $this->active = 'all';
306 elseif( $this->namespaces === SearchEngine::defaultNamespaces() )
307 $this->active = 'default';
308 elseif( $this->namespaces === SearchEngine::projectNamespaces() )
309 $this->active = 'project';
310 else
311 $this->active = 'advanced';
312 # Should advanced UI be used?
313 $this->searchAdvanced = ($this->active === 'advanced');
314 if( !empty( $term ) ) {
315 $wgOut->setPageTitle( wfMsg( 'searchresults') );
316 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
317 }
318 $wgOut->setArticleRelated( false );
319 $wgOut->setRobotPolicy( 'noindex,nofollow' );
320 }
321
322 /**
323 * Extract "power search" namespace settings from the request object,
324 * returning a list of index numbers to search.
325 *
326 * @param WebRequest $request
327 * @return array
328 */
329 protected function powerSearch( &$request ) {
330 $arr = array();
331 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
332 if( $request->getCheck( 'ns' . $ns ) ) {
333 $arr[] = $ns;
334 }
335 }
336 return $arr;
337 }
338
339 /**
340 * Reconstruct the 'power search' options for links
341 * @return array
342 */
343 protected function powerSearchOptions() {
344 $opt = array();
345 foreach( $this->namespaces as $n ) {
346 $opt['ns' . $n] = 1;
347 }
348 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
349 if( $this->searchAdvanced ) {
350 $opt['advanced'] = $this->searchAdvanced;
351 }
352 return $opt;
353 }
354
355 /**
356 * Show whole set of results
357 *
358 * @param SearchResultSet $matches
359 */
360 protected function showMatches( &$matches ) {
361 global $wgContLang;
362 wfProfileIn( __METHOD__ );
363
364 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
365
366 $out = "";
367 $infoLine = $matches->getInfo();
368 if( !is_null($infoLine) ) {
369 $out .= "\n<!-- {$infoLine} -->\n";
370 }
371 $off = $this->offset + 1;
372 $out .= "<ul class='mw-search-results'>\n";
373 while( $result = $matches->next() ) {
374 $out .= $this->showHit( $result, $terms );
375 }
376 $out .= "</ul>\n";
377
378 // convert the whole thing to desired language variant
379 $out = $wgContLang->convert( $out );
380 wfProfileOut( __METHOD__ );
381 return $out;
382 }
383
384 /**
385 * Format a single hit result
386 * @param SearchResult $result
387 * @param array $terms terms to highlight
388 */
389 protected function showHit( $result, $terms ) {
390 global $wgContLang, $wgLang, $wgUser;
391 wfProfileIn( __METHOD__ );
392
393 if( $result->isBrokenTitle() ) {
394 wfProfileOut( __METHOD__ );
395 return "<!-- Broken link in search result -->\n";
396 }
397
398 $sk = $wgUser->getSkin();
399 $t = $result->getTitle();
400
401 $link = $this->sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
402
403 //If page content is not readable, just return the title.
404 //This is not quite safe, but better than showing excerpts from non-readable pages
405 //Note that hiding the entry entirely would screw up paging.
406 if( !$t->userCanRead() ) {
407 wfProfileOut( __METHOD__ );
408 return "<li>{$link}</li>\n";
409 }
410
411 // If the page doesn't *exist*... our search index is out of date.
412 // The least confusing at this point is to drop the result.
413 // You may get less results, but... oh well. :P
414 if( $result->isMissingRevision() ) {
415 wfProfileOut( __METHOD__ );
416 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
417 }
418
419 // format redirects / relevant sections
420 $redirectTitle = $result->getRedirectTitle();
421 $redirectText = $result->getRedirectSnippet($terms);
422 $sectionTitle = $result->getSectionTitle();
423 $sectionText = $result->getSectionSnippet($terms);
424 $redirect = '';
425 if( !is_null($redirectTitle) )
426 $redirect = "<span class='searchalttitle'>"
427 .wfMsg('search-redirect',$this->sk->makeKnownLinkObj( $redirectTitle, $redirectText))
428 ."</span>";
429 $section = '';
430 if( !is_null($sectionTitle) )
431 $section = "<span class='searchalttitle'>"
432 .wfMsg('search-section', $this->sk->makeKnownLinkObj( $sectionTitle, $sectionText))
433 ."</span>";
434
435 // format text extract
436 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
437
438 // format score
439 if( is_null( $result->getScore() ) ) {
440 // Search engine doesn't report scoring info
441 $score = '';
442 } else {
443 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
444 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
445 . ' - ';
446 }
447
448 // format description
449 $byteSize = $result->getByteSize();
450 $wordCount = $result->getWordCount();
451 $timestamp = $result->getTimestamp();
452 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
453 $this->sk->formatSize( $byteSize ), $wordCount );
454 $date = $wgLang->timeanddate( $timestamp );
455
456 // link to related articles if supported
457 $related = '';
458 if( $result->hasRelated() ) {
459 $st = SpecialPage::getTitleFor( 'Search' );
460 $stParams = wfArrayToCGI( $this->powerSearchOptions(),
461 array('search' => wfMsgForContent('searchrelated').':'.$t->getPrefixedText(),
462 'fulltext' => wfMsg('search') ));
463
464 $related = ' -- ' . $sk->makeKnownLinkObj( $st,
465 wfMsg('search-relatedarticle'), $stParams );
466 }
467
468 // Include a thumbnail for media files...
469 if( $t->getNamespace() == NS_FILE ) {
470 $img = wfFindFile( $t );
471 if( $img ) {
472 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
473 if( $thumb ) {
474 $desc = $img->getShortDesc();
475 wfProfileOut( __METHOD__ );
476 // Float doesn't seem to interact well with the bullets.
477 // Table messes up vertical alignment of the bullets.
478 // Bullets are therefore disabled (didn't look great anyway).
479 return "<li>" .
480 '<table class="searchResultImage">' .
481 '<tr>' .
482 '<td width="120" align="center" valign="top">' .
483 $thumb->toHtml( array( 'desc-link' => true ) ) .
484 '</td>' .
485 '<td valign="top">' .
486 $link .
487 $extract .
488 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
489 '</td>' .
490 '</tr>' .
491 '</table>' .
492 "</li>\n";
493 }
494 }
495 }
496
497 wfProfileOut( __METHOD__ );
498 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
499 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
500 "</li>\n";
501
502 }
503
504 /**
505 * Show results from other wikis
506 *
507 * @param SearchResultSet $matches
508 */
509 protected function showInterwiki( &$matches, $query ) {
510 global $wgContLang;
511 wfProfileIn( __METHOD__ );
512 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
513
514 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
515 wfMsg('search-interwiki-caption')."</div>\n";
516 $off = $this->offset + 1;
517 $out .= "<ul class='mw-search-iwresults'>\n";
518
519 // work out custom project captions
520 $customCaptions = array();
521 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
522 foreach($customLines as $line) {
523 $parts = explode(":",$line,2);
524 if(count($parts) == 2) // validate line
525 $customCaptions[$parts[0]] = $parts[1];
526 }
527
528 $prev = null;
529 while( $result = $matches->next() ) {
530 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
531 $prev = $result->getInterwikiPrefix();
532 }
533 // FIXME: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
534 $out .= "</ul></div>\n";
535
536 // convert the whole thing to desired language variant
537 $out = $wgContLang->convert( $out );
538 wfProfileOut( __METHOD__ );
539 return $out;
540 }
541
542 /**
543 * Show single interwiki link
544 *
545 * @param SearchResult $result
546 * @param string $lastInterwiki
547 * @param array $terms
548 * @param string $query
549 * @param array $customCaptions iw prefix -> caption
550 */
551 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
552 wfProfileIn( __METHOD__ );
553 global $wgContLang, $wgLang;
554
555 if( $result->isBrokenTitle() ) {
556 wfProfileOut( __METHOD__ );
557 return "<!-- Broken link in search result -->\n";
558 }
559
560 $t = $result->getTitle();
561
562 $link = $this->sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
563
564 // format redirect if any
565 $redirectTitle = $result->getRedirectTitle();
566 $redirectText = $result->getRedirectSnippet($terms);
567 $redirect = '';
568 if( !is_null($redirectTitle) )
569 $redirect = "<span class='searchalttitle'>"
570 .wfMsg('search-redirect',$this->sk->makeKnownLinkObj( $redirectTitle, $redirectText))
571 ."</span>";
572
573 $out = "";
574 // display project name
575 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
576 if( key_exists($t->getInterwiki(),$customCaptions) )
577 // captions from 'search-interwiki-custom'
578 $caption = $customCaptions[$t->getInterwiki()];
579 else{
580 // default is to show the hostname of the other wiki which might suck
581 // if there are many wikis on one hostname
582 $parsed = parse_url($t->getFullURL());
583 $caption = wfMsg('search-interwiki-default', $parsed['host']);
584 }
585 // "more results" link (special page stuff could be localized, but we might not know target lang)
586 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
587 $searchLink = $this->sk->makeKnownLinkObj( $searchTitle, wfMsg('search-interwiki-more'),
588 wfArrayToCGI(array('search' => $query, 'fulltext' => 'Search')));
589 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
590 {$searchLink}</span>{$caption}</div>\n<ul>";
591 }
592
593 $out .= "<li>{$link} {$redirect}</li>\n";
594 wfProfileOut( __METHOD__ );
595 return $out;
596 }
597
598
599 /**
600 * Generates the power search box at bottom of [[Special:Search]]
601 * @param $term string: search term
602 * @return $out string: HTML form
603 */
604 protected function powerSearchBox( $term ) {
605 global $wgScript;
606
607 $namespaces = SearchEngine::searchableNamespaces();
608
609 $tables = $this->namespaceTables( $namespaces );
610
611 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' ) );
612 $redirectLabel = Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
613 $searchField = Xml::inputLabel( wfMsg('powersearch-field'), 'search', 'powerSearchText', 50, $term,
614 array( 'type' => 'text') );
615 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'fulltext' )) . "\n";
616 $searchTitle = SpecialPage::getTitleFor( 'Search' );
617
618 $redirectText = '';
619 // show redirects check only if backend supports it
620 if( $this->searchEngine->acceptListRedirects() ) {
621 $redirectText = "<p>". $redirect . " " . $redirectLabel ."</p>";
622 }
623
624 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
625 Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n" .
626 "<p>" .
627 wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) .
628 "</p>\n" .
629 '<input type="hidden" name="advanced" value="'.$this->searchAdvanced."\"/>\n".
630 $tables .
631 "<hr style=\"clear: both;\" />\n".
632 $redirectText ."\n".
633 "<div style=\"padding-top:2px;padding-bottom:2px;\">".
634 $searchField .
635 "&nbsp;" .
636 Xml::hidden( 'fulltext', 'Advanced search' ) . "\n" .
637 $searchButton .
638 "</div>".
639 "</form>";
640 $t = Title::newFromText( $term );
641 /* if( $t != null && count($this->namespaces) === 1 ) {
642 $out .= wfMsgExt( 'searchmenu-prefix', array('parseinline'), $term );
643 } */
644 return Xml::openElement( 'fieldset', array('id' => 'mw-searchoptions','style' => 'margin:0em;') ) .
645 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
646 $this->formHeader($term) . $out . $this->didYouMeanHtml .
647 Xml::closeElement( 'fieldset' );
648 }
649
650 protected function searchFocus() {
651 global $wgJsMimeType;
652 return "<script type=\"$wgJsMimeType\">" .
653 "hookEvent(\"load\", function() {" .
654 "document.getElementById('searchText').focus();" .
655 "});" .
656 "</script>";
657 }
658
659 protected function powerSearchFocus() {
660 global $wgJsMimeType;
661 return "<script type=\"$wgJsMimeType\">" .
662 "hookEvent(\"load\", function() {" .
663 "document.getElementById('powerSearchText').focus();" .
664 "});" .
665 "</script>";
666 }
667
668 protected function formHeader( $term ) {
669 global $wgContLang, $wgCanonicalNamespaceNames, $wgLang;
670
671 $sep = '&nbsp;&nbsp;&nbsp;';
672 $out = Xml::openElement('div', array( 'style' => 'padding-bottom:0.5em;' ) );
673
674 $bareterm = $term;
675 if( $this->startsWithImage( $term ) )
676 $bareterm = substr( $term, strpos( $term, ':' ) + 1 ); // delete all/image prefix
677
678 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
679
680 // search profiles headers
681 $m = wfMsg( 'searchprofile-articles' );
682 $tt = wfMsg( 'searchprofile-articles-tooltip',
683 $wgLang->commaList( SearchEngine::namespacesAsText( SearchEngine::defaultNamespaces() ) ) );
684 if( $this->active == 'default' ) {
685 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
686 } else {
687 $out .= $this->makeSearchLink( $bareterm, SearchEngine::defaultNamespaces(), $m, $tt );
688 }
689 $out .= $sep;
690
691 $m = wfMsg( 'searchprofile-images' );
692 $tt = wfMsg( 'searchprofile-images-tooltip' );
693 if( $this->active == 'images' ) {
694 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
695 } else {
696 $imageTextForm = $wgContLang->getFormattedNsText(NS_FILE).':'.$bareterm;
697 $out .= $this->makeSearchLink( $imageTextForm, array( NS_FILE ) , $m, $tt );
698 }
699 $out .= $sep;
700
701 $m = wfMsg( 'searchprofile-project' );
702 $tt = wfMsg( 'searchprofile-project-tooltip',
703 $wgLang->commaList( SearchEngine::namespacesAsText( SearchEngine::projectNamespaces() ) ) );
704 if( $this->active == 'project' ) {
705 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
706 } else {
707 $out .= $this->makeSearchLink( $bareterm, SearchEngine::projectNamespaces(), $m, $tt );
708 }
709 $out .= $sep;
710
711 $m = wfMsg( 'searchprofile-everything' );
712 $tt = wfMsg( 'searchprofile-everything-tooltip' );
713 if( $this->active == 'all' ) {
714 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
715 } else {
716 $out .= $this->makeSearchLink( $bareterm, $nsAllSet, $m, $tt );
717 }
718 $out .= $sep;
719
720 $m = wfMsg( 'searchprofile-advanced' );
721 $tt = wfMsg( 'searchprofile-advanced-tooltip' );
722 if( $this->active == 'advanced' ) {
723 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
724 } else {
725 $out .= $this->makeSearchLink( $bareterm, $this->namespaces, $m, $tt, array( 'advanced' => '1' ) );
726 }
727 $out .= Xml::closeElement('div') ;
728
729 return $out;
730 }
731
732 protected function shortDialog( $term ) {
733 global $wgScript;
734 $searchTitle = SpecialPage::getTitleFor( 'Search' );
735 $searchable = SearchEngine::searchableNamespaces();
736 $out = Xml::openElement( 'form', array( 'id' => 'search', 'method' => 'get', 'action' => $wgScript ) );
737 $out .= Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
738 // show namespaces only for advanced search
739 if( $this->active == 'advanced' ) {
740 $active = array();
741 foreach( $this->namespaces as $ns ) {
742 $active[$ns] = $searchable[$ns];
743 }
744 $out .= wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) . "<br/>\n";
745 $out .= $this->namespaceTables( $active, 1 )."<br/>\n";
746 // Still keep namespace settings otherwise, but don't show them
747 } else {
748 foreach( $this->namespaces as $ns ) {
749 $out .= Xml::hidden( "ns{$ns}", '1' );
750 }
751 }
752 // Keep redirect setting
753 $out .= Xml::hidden( "redirs", (int)$this->searchRedirects );
754 // Term box
755 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . "\n";
756 $out .= Xml::hidden( 'fulltext', 'Search' );
757 $out .= Xml::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
758 $out .= ' (' . wfMsgExt('searchmenu-help',array('parseinline') ) . ')';
759 $out .= Xml::closeElement( 'form' );
760 // Add prefix link for single-namespace searches
761 $t = Title::newFromText( $term );
762 /*if( $t != null && count($this->namespaces) === 1 ) {
763 $out .= wfMsgExt( 'searchmenu-prefix', array('parseinline'), $term );
764 }*/
765 return Xml::openElement( 'fieldset', array('id' => 'mw-searchoptions','style' => 'margin:0em;') ) .
766 Xml::element( 'legend', null, wfMsg('searchmenu-legend') ) .
767 $this->formHeader($term) . $out . $this->didYouMeanHtml .
768 Xml::closeElement( 'fieldset' );
769 }
770
771 /** Make a search link with some target namespaces */
772 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params=array() ) {
773 $opt = $params;
774 foreach( $namespaces as $n ) {
775 $opt['ns' . $n] = 1;
776 }
777 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
778
779 $st = SpecialPage::getTitleFor( 'Search' );
780 $stParams = wfArrayToCGI( array( 'search' => $term, 'fulltext' => wfMsg( 'search' ) ), $opt );
781
782 return Xml::element( 'a',
783 array( 'href'=> $st->getLocalURL( $stParams ), 'title' => $tooltip ),
784 $label );
785 }
786
787 /** Check if query starts with image: prefix */
788 protected function startsWithImage( $term ) {
789 global $wgContLang;
790
791 $p = explode( ':', $term );
792 if( count( $p ) > 1 ) {
793 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
794 }
795 return false;
796 }
797
798 protected function namespaceTables( $namespaces, $rowsPerTable = 3 ) {
799 global $wgContLang;
800 // Group namespaces into rows according to subject.
801 // Try not to make too many assumptions about namespace numbering.
802 $rows = array();
803 $tables = "";
804 foreach( $namespaces as $ns => $name ) {
805 $subj = MWNamespace::getSubject( $ns );
806 if( !array_key_exists( $subj, $rows ) ) {
807 $rows[$subj] = "";
808 }
809 $name = str_replace( '_', ' ', $name );
810 if( '' == $name ) {
811 $name = wfMsg( 'blanknamespace' );
812 }
813 $rows[$subj] .= Xml::openElement( 'td', array( 'style' => 'white-space: nowrap' ) ) .
814 Xml::checkLabel( $name, "ns{$ns}", "mw-search-ns{$ns}", in_array( $ns, $this->namespaces ) ) .
815 Xml::closeElement( 'td' ) . "\n";
816 }
817 $rows = array_values( $rows );
818 $numRows = count( $rows );
819 // Lay out namespaces in multiple floating two-column tables so they'll
820 // be arranged nicely while still accommodating different screen widths
821 // Float to the right on RTL wikis
822 $tableStyle = $wgContLang->isRTL() ?
823 'float: right; margin: 0 0 0em 1em' : 'float: left; margin: 0 1em 0em 0';
824 // Build the final HTML table...
825 for( $i = 0; $i < $numRows; $i += $rowsPerTable ) {
826 $tables .= Xml::openElement( 'table', array( 'style' => $tableStyle ) );
827 for( $j = $i; $j < $i + $rowsPerTable && $j < $numRows; $j++ ) {
828 $tables .= "<tr>\n" . $rows[$j] . "</tr>";
829 }
830 $tables .= Xml::closeElement( 'table' ) . "\n";
831 }
832 return $tables;
833 }
834 }
835
836 /**
837 * implements Special:Search - Run text & title search and display the output
838 * @ingroup SpecialPage
839 */
840 class SpecialSearchOld {
841
842 /**
843 * Set up basic search parameters from the request and user settings.
844 * Typically you'll pass $wgRequest and $wgUser.
845 *
846 * @param WebRequest $request
847 * @param User $user
848 * @public
849 */
850 function __construct( &$request, &$user ) {
851 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
852 $this->mPrefix = $request->getVal('prefix', '');
853 $this->namespaces = $this->powerSearch( $request );
854 if( empty( $this->namespaces ) ) {
855 $this->namespaces = SearchEngine::userNamespaces( $user );
856 }
857
858 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
859 }
860
861 /**
862 * If an exact title match can be found, jump straight ahead to it.
863 * @param string $term
864 * @public
865 */
866 function goResult( $term ) {
867 global $wgOut;
868 global $wgGoToEdit;
869
870 $this->setupPage( $term );
871
872 # Try to go to page as entered.
873 $t = Title::newFromText( $term );
874
875 # If the string cannot be used to create a title
876 if( is_null( $t ) ){
877 return $this->showResults( $term );
878 }
879
880 # If there's an exact or very near match, jump right there.
881 $t = SearchEngine::getNearMatch( $term );
882 if( !is_null( $t ) ) {
883 $wgOut->redirect( $t->getFullURL() );
884 return;
885 }
886
887 # No match, generate an edit URL
888 $t = Title::newFromText( $term );
889 if( ! is_null( $t ) ) {
890 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
891 # If the feature is enabled, go straight to the edit page
892 if ( $wgGoToEdit ) {
893 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
894 return;
895 }
896 }
897
898 $extra = $wgOut->parse( '=='.wfMsgNoTrans( 'notitlematches' )."==\n" );
899 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
900 $extra .= wfMsgExt( 'noexactmatch', 'parse', wfEscapeWikiText( $term ) );
901 } else {
902 $extra .= wfMsgExt( 'noexactmatch-nocreate', 'parse', wfEscapeWikiText( $term ) );
903 }
904
905 $this->showResults( $term, $extra );
906 }
907
908 /**
909 * @param string $term
910 * @param string $extra Extra HTML to add after "did you mean"
911 */
912 public function showResults( $term, $extra = '' ) {
913 wfProfileIn( __METHOD__ );
914 global $wgOut, $wgUser;
915 $sk = $wgUser->getSkin();
916
917 $search = SearchEngine::create();
918 $search->setLimitOffset( $this->limit, $this->offset );
919 $search->setNamespaces( $this->namespaces );
920 $search->showRedirects = $this->searchRedirects;
921 $search->prefix = $this->mPrefix;
922 $term = $search->transformSearchTerm($term);
923
924 $this->setupPage( $term );
925
926 $rewritten = $search->replacePrefixes($term);
927 $titleMatches = $search->searchTitle( $rewritten );
928 $textMatches = $search->searchText( $rewritten );
929
930 // did you mean... suggestions
931 if($textMatches && $textMatches->hasSuggestion()){
932 $st = SpecialPage::getTitleFor( 'Search' );
933 $stParams = wfArrayToCGI( array(
934 'search' => $textMatches->getSuggestionQuery(),
935 'fulltext' => wfMsg('search')),
936 $this->powerSearchOptions());
937
938 $suggestLink = $sk->makeKnownLinkObj( $st,
939 $textMatches->getSuggestionSnippet(),
940 $stParams );
941
942 $wgOut->addHTML('<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>');
943 }
944
945 $wgOut->addHTML( $extra );
946
947 $wgOut->wrapWikiMsg( "<div class='mw-searchresult'>\n$1</div>", 'searchresulttext' );
948
949 if( '' === trim( $term ) ) {
950 // Empty query -- straight view of search form
951 $wgOut->setSubtitle( '' );
952 $wgOut->addHTML( $this->powerSearchBox( $term ) );
953 $wgOut->addHTML( $this->powerSearchFocus() );
954 wfProfileOut( __METHOD__ );
955 return;
956 }
957
958 global $wgDisableTextSearch;
959 if ( $wgDisableTextSearch ) {
960 global $wgSearchForwardUrl;
961 if( $wgSearchForwardUrl ) {
962 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
963 $wgOut->redirect( $url );
964 wfProfileOut( __METHOD__ );
965 return;
966 }
967 global $wgInputEncoding;
968 $wgOut->addHTML(
969 Xml::openElement( 'fieldset' ) .
970 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
971 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
972 wfMsg( 'googlesearch',
973 htmlspecialchars( $term ),
974 htmlspecialchars( $wgInputEncoding ),
975 htmlspecialchars( wfMsg( 'searchbutton' ) )
976 ) .
977 Xml::closeElement( 'fieldset' )
978 );
979 wfProfileOut( __METHOD__ );
980 return;
981 }
982
983 $wgOut->addHTML( $this->shortDialog( $term ) );
984
985 // Sometimes the search engine knows there are too many hits
986 if ($titleMatches instanceof SearchResultTooMany) {
987 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
988 $wgOut->addHTML( $this->powerSearchBox( $term ) );
989 $wgOut->addHTML( $this->powerSearchFocus() );
990 wfProfileOut( __METHOD__ );
991 return;
992 }
993
994 // show number of results
995 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
996 + ( $textMatches ? $textMatches->numRows() : 0);
997 $totalNum = 0;
998 if($titleMatches && !is_null($titleMatches->getTotalHits()))
999 $totalNum += $titleMatches->getTotalHits();
1000 if($textMatches && !is_null($textMatches->getTotalHits()))
1001 $totalNum += $textMatches->getTotalHits();
1002 if ( $num > 0 ) {
1003 if ( $totalNum > 0 ){
1004 $top = wfMsgExt('showingresultstotal', array( 'parseinline' ),
1005 $this->offset+1, $this->offset+$num, $totalNum, $num );
1006 } elseif ( $num >= $this->limit ) {
1007 $top = wfShowingResults( $this->offset, $this->limit );
1008 } else {
1009 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
1010 }
1011 $wgOut->addHTML( "<p class='mw-search-numberresults'>{$top}</p>\n" );
1012 }
1013
1014 // prev/next links
1015 if( $num || $this->offset ) {
1016 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
1017 SpecialPage::getTitleFor( 'Search' ),
1018 wfArrayToCGI(
1019 $this->powerSearchOptions(),
1020 array( 'search' => $term ) ),
1021 ($num < $this->limit) );
1022 $wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
1023 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
1024 } else {
1025 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
1026 }
1027
1028 if( $titleMatches ) {
1029 if( $titleMatches->numRows() ) {
1030 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
1031 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
1032 }
1033 $titleMatches->free();
1034 }
1035
1036 if( $textMatches ) {
1037 // output appropriate heading
1038 if( $textMatches->numRows() ) {
1039 if($titleMatches)
1040 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
1041 else // if no title matches the heading is redundant
1042 $wgOut->addHTML("<hr/>");
1043 } elseif( $num == 0 ) {
1044 # Don't show the 'no text matches' if we received title matches
1045 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
1046 }
1047 // show interwiki results if any
1048 if( $textMatches->hasInterwikiResults() )
1049 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ));
1050 // show results
1051 if( $textMatches->numRows() )
1052 $wgOut->addHTML( $this->showMatches( $textMatches ) );
1053
1054 $textMatches->free();
1055 }
1056
1057 if ( $num == 0 ) {
1058 $wgOut->addWikiMsg( 'nonefound' );
1059 }
1060 if( $num || $this->offset ) {
1061 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
1062 }
1063 $wgOut->addHTML( $this->powerSearchBox( $term ) );
1064 wfProfileOut( __METHOD__ );
1065 }
1066
1067 #------------------------------------------------------------------
1068 # Private methods below this line
1069
1070 /**
1071 *
1072 */
1073 function setupPage( $term ) {
1074 global $wgOut;
1075 if( !empty( $term ) ){
1076 $wgOut->setPageTitle( wfMsg( 'searchresults') );
1077 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term) ) );
1078 }
1079 $subtitlemsg = ( Title::newFromText( $term ) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
1080 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
1081 $wgOut->setArticleRelated( false );
1082 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1083 }
1084
1085 /**
1086 * Extract "power search" namespace settings from the request object,
1087 * returning a list of index numbers to search.
1088 *
1089 * @param WebRequest $request
1090 * @return array
1091 * @private
1092 */
1093 function powerSearch( &$request ) {
1094 $arr = array();
1095 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
1096 if( $request->getCheck( 'ns' . $ns ) ) {
1097 $arr[] = $ns;
1098 }
1099 }
1100 return $arr;
1101 }
1102
1103 /**
1104 * Reconstruct the 'power search' options for links
1105 * @return array
1106 * @private
1107 */
1108 function powerSearchOptions() {
1109 $opt = array();
1110 foreach( $this->namespaces as $n ) {
1111 $opt['ns' . $n] = 1;
1112 }
1113 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
1114 return $opt;
1115 }
1116
1117 /**
1118 * Show whole set of results
1119 *
1120 * @param SearchResultSet $matches
1121 */
1122 function showMatches( &$matches ) {
1123 wfProfileIn( __METHOD__ );
1124
1125 global $wgContLang;
1126 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
1127
1128 $out = "";
1129
1130 $infoLine = $matches->getInfo();
1131 if( !is_null($infoLine) )
1132 $out .= "\n<!-- {$infoLine} -->\n";
1133
1134
1135 $off = $this->offset + 1;
1136 $out .= "<ul class='mw-search-results'>\n";
1137
1138 while( $result = $matches->next() ) {
1139 $out .= $this->showHit( $result, $terms );
1140 }
1141 $out .= "</ul>\n";
1142
1143 // convert the whole thing to desired language variant
1144 global $wgContLang;
1145 $out = $wgContLang->convert( $out );
1146 wfProfileOut( __METHOD__ );
1147 return $out;
1148 }
1149
1150 /**
1151 * Format a single hit result
1152 * @param SearchResult $result
1153 * @param array $terms terms to highlight
1154 */
1155 function showHit( $result, $terms ) {
1156 wfProfileIn( __METHOD__ );
1157 global $wgUser, $wgContLang, $wgLang;
1158
1159 if( $result->isBrokenTitle() ) {
1160 wfProfileOut( __METHOD__ );
1161 return "<!-- Broken link in search result -->\n";
1162 }
1163
1164 $t = $result->getTitle();
1165 $sk = $wgUser->getSkin();
1166
1167 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
1168
1169 //If page content is not readable, just return the title.
1170 //This is not quite safe, but better than showing excerpts from non-readable pages
1171 //Note that hiding the entry entirely would screw up paging.
1172 if (!$t->userCanRead()) {
1173 wfProfileOut( __METHOD__ );
1174 return "<li>{$link}</li>\n";
1175 }
1176
1177 // If the page doesn't *exist*... our search index is out of date.
1178 // The least confusing at this point is to drop the result.
1179 // You may get less results, but... oh well. :P
1180 if( $result->isMissingRevision() ) {
1181 wfProfileOut( __METHOD__ );
1182 return "<!-- missing page " .
1183 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
1184 }
1185
1186 // format redirects / relevant sections
1187 $redirectTitle = $result->getRedirectTitle();
1188 $redirectText = $result->getRedirectSnippet($terms);
1189 $sectionTitle = $result->getSectionTitle();
1190 $sectionText = $result->getSectionSnippet($terms);
1191 $redirect = '';
1192 if( !is_null($redirectTitle) )
1193 $redirect = "<span class='searchalttitle'>"
1194 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
1195 ."</span>";
1196 $section = '';
1197 if( !is_null($sectionTitle) )
1198 $section = "<span class='searchalttitle'>"
1199 .wfMsg('search-section', $sk->makeKnownLinkObj( $sectionTitle, $sectionText))
1200 ."</span>";
1201
1202 // format text extract
1203 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
1204
1205 // format score
1206 if( is_null( $result->getScore() ) ) {
1207 // Search engine doesn't report scoring info
1208 $score = '';
1209 } else {
1210 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
1211 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
1212 . ' - ';
1213 }
1214
1215 // format description
1216 $byteSize = $result->getByteSize();
1217 $wordCount = $result->getWordCount();
1218 $timestamp = $result->getTimestamp();
1219 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
1220 $sk->formatSize( $byteSize ),
1221 $wordCount );
1222 $date = $wgLang->timeanddate( $timestamp );
1223
1224 // link to related articles if supported
1225 $related = '';
1226 if( $result->hasRelated() ){
1227 $st = SpecialPage::getTitleFor( 'Search' );
1228 $stParams = wfArrayToCGI( $this->powerSearchOptions(),
1229 array('search' => wfMsgForContent('searchrelated').':'.$t->getPrefixedText(),
1230 'fulltext' => wfMsg('search') ));
1231
1232 $related = ' -- ' . $sk->makeKnownLinkObj( $st,
1233 wfMsg('search-relatedarticle'), $stParams );
1234 }
1235
1236 // Include a thumbnail for media files...
1237 if( $t->getNamespace() == NS_FILE ) {
1238 $img = wfFindFile( $t );
1239 if( $img ) {
1240 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
1241 if( $thumb ) {
1242 $desc = $img->getShortDesc();
1243 wfProfileOut( __METHOD__ );
1244 // Ugly table. :D
1245 // Float doesn't seem to interact well with the bullets.
1246 // Table messes up vertical alignment of the bullet, but I'm
1247 // not sure what more I can do about that. :(
1248 return "<li>" .
1249 '<table class="searchResultImage">' .
1250 '<tr>' .
1251 '<td width="120" align="center">' .
1252 $thumb->toHtml( array( 'desc-link' => true ) ) .
1253 '</td>' .
1254 '<td valign="top">' .
1255 $link .
1256 $extract .
1257 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
1258 '</td>' .
1259 '</tr>' .
1260 '</table>' .
1261 "</li>\n";
1262 }
1263 }
1264 }
1265
1266 wfProfileOut( __METHOD__ );
1267 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
1268 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
1269 "</li>\n";
1270
1271 }
1272
1273 /**
1274 * Show results from other wikis
1275 *
1276 * @param SearchResultSet $matches
1277 */
1278 function showInterwiki( &$matches, $query ) {
1279 wfProfileIn( __METHOD__ );
1280
1281 global $wgContLang;
1282 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
1283
1284 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".wfMsg('search-interwiki-caption')."</div>\n";
1285 $off = $this->offset + 1;
1286 $out .= "<ul start='{$off}' class='mw-search-iwresults'>\n";
1287
1288 // work out custom project captions
1289 $customCaptions = array();
1290 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
1291 foreach($customLines as $line){
1292 $parts = explode(":",$line,2);
1293 if(count($parts) == 2) // validate line
1294 $customCaptions[$parts[0]] = $parts[1];
1295 }
1296
1297
1298 $prev = null;
1299 while( $result = $matches->next() ) {
1300 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
1301 $prev = $result->getInterwikiPrefix();
1302 }
1303 // FIXME: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
1304 $out .= "</ul></div>\n";
1305
1306 // convert the whole thing to desired language variant
1307 global $wgContLang;
1308 $out = $wgContLang->convert( $out );
1309 wfProfileOut( __METHOD__ );
1310 return $out;
1311 }
1312
1313 /**
1314 * Show single interwiki link
1315 *
1316 * @param SearchResult $result
1317 * @param string $lastInterwiki
1318 * @param array $terms
1319 * @param string $query
1320 * @param array $customCaptions iw prefix -> caption
1321 */
1322 function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
1323 wfProfileIn( __METHOD__ );
1324 global $wgUser, $wgContLang, $wgLang;
1325
1326 if( $result->isBrokenTitle() ) {
1327 wfProfileOut( __METHOD__ );
1328 return "<!-- Broken link in search result -->\n";
1329 }
1330
1331 $t = $result->getTitle();
1332 $sk = $wgUser->getSkin();
1333
1334 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
1335
1336 // format redirect if any
1337 $redirectTitle = $result->getRedirectTitle();
1338 $redirectText = $result->getRedirectSnippet($terms);
1339 $redirect = '';
1340 if( !is_null($redirectTitle) )
1341 $redirect = "<span class='searchalttitle'>"
1342 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
1343 ."</span>";
1344
1345 $out = "";
1346 // display project name
1347 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()){
1348 if( key_exists($t->getInterwiki(),$customCaptions) )
1349 // captions from 'search-interwiki-custom'
1350 $caption = $customCaptions[$t->getInterwiki()];
1351 else{
1352 // default is to show the hostname of the other wiki which might suck
1353 // if there are many wikis on one hostname
1354 $parsed = parse_url($t->getFullURL());
1355 $caption = wfMsg('search-interwiki-default', $parsed['host']);
1356 }
1357 // "more results" link (special page stuff could be localized, but we might not know target lang)
1358 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
1359 $searchLink = $sk->makeKnownLinkObj( $searchTitle, wfMsg('search-interwiki-more'),
1360 wfArrayToCGI(array('search' => $query, 'fulltext' => 'Search')));
1361 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>{$searchLink}</span>{$caption}</div>\n<ul>";
1362 }
1363
1364 $out .= "<li>{$link} {$redirect}</li>\n";
1365 wfProfileOut( __METHOD__ );
1366 return $out;
1367 }
1368
1369
1370 /**
1371 * Generates the power search box at bottom of [[Special:Search]]
1372 * @param $term string: search term
1373 * @return $out string: HTML form
1374 */
1375 function powerSearchBox( $term ) {
1376 global $wgScript, $wgContLang;
1377
1378 $namespaces = SearchEngine::searchableNamespaces();
1379
1380 // group namespaces into rows according to subject; try not to make too
1381 // many assumptions about namespace numbering
1382 $rows = array();
1383 foreach( $namespaces as $ns => $name ) {
1384 $subj = MWNamespace::getSubject( $ns );
1385 if( !array_key_exists( $subj, $rows ) ) {
1386 $rows[$subj] = "";
1387 }
1388 $name = str_replace( '_', ' ', $name );
1389 if( '' == $name ) {
1390 $name = wfMsg( 'blanknamespace' );
1391 }
1392 $rows[$subj] .= Xml::openElement( 'td', array( 'style' => 'white-space: nowrap' ) ) .
1393 Xml::checkLabel( $name, "ns{$ns}", "mw-search-ns{$ns}", in_array( $ns, $this->namespaces ) ) .
1394 Xml::closeElement( 'td' ) . "\n";
1395 }
1396 $rows = array_values( $rows );
1397 $numRows = count( $rows );
1398
1399 // lay out namespaces in multiple floating two-column tables so they'll
1400 // be arranged nicely while still accommodating different screen widths
1401 $rowsPerTable = 3; // seems to look nice
1402
1403 // float to the right on RTL wikis
1404 $tableStyle = ( $wgContLang->isRTL() ?
1405 'float: right; margin: 0 0 1em 1em' :
1406 'float: left; margin: 0 1em 1em 0' );
1407
1408 $tables = "";
1409 for( $i = 0; $i < $numRows; $i += $rowsPerTable ) {
1410 $tables .= Xml::openElement( 'table', array( 'style' => $tableStyle ) );
1411 for( $j = $i; $j < $i + $rowsPerTable && $j < $numRows; $j++ ) {
1412 $tables .= "<tr>\n" . $rows[$j] . "</tr>";
1413 }
1414 $tables .= Xml::closeElement( 'table' ) . "\n";
1415 }
1416
1417 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' ) );
1418 $redirectLabel = Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
1419 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
1420 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'fulltext' ) ) . "\n";
1421 $searchTitle = SpecialPage::getTitleFor( 'Search' );
1422 $searchHiddens = Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
1423 $searchHiddens .= Xml::hidden( 'fulltext', 'Advanced search' ) . "\n";
1424
1425 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
1426 Xml::fieldset( wfMsg( 'powersearch-legend' ),
1427 "<p>" .
1428 wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) .
1429 "</p>\n" .
1430 $tables .
1431 "<hr style=\"clear: both\" />\n" .
1432 "<p>" .
1433 $redirect . " " . $redirectLabel .
1434 "</p>\n" .
1435 wfMsgExt( 'powersearch-field', array( 'parseinline' ) ) .
1436 "&nbsp;" .
1437 $searchField .
1438 "&nbsp;" .
1439 $searchHiddens .
1440 $searchButton ) .
1441 "</form>";
1442
1443 return $out;
1444 }
1445
1446 function powerSearchFocus() {
1447 global $wgJsMimeType;
1448 return "<script type=\"$wgJsMimeType\">" .
1449 "hookEvent(\"load\", function(){" .
1450 "document.getElementById('powerSearchText').focus();" .
1451 "});" .
1452 "</script>";
1453 }
1454
1455 function shortDialog($term) {
1456 global $wgScript;
1457
1458 $out = Xml::openElement( 'form', array(
1459 'id' => 'search',
1460 'method' => 'get',
1461 'action' => $wgScript
1462 ));
1463 $searchTitle = SpecialPage::getTitleFor( 'Search' );
1464 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . ' ';
1465 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
1466 if( in_array( $ns, $this->namespaces ) ) {
1467 $out .= Xml::hidden( "ns{$ns}", '1' );
1468 }
1469 }
1470 $out .= Xml::hidden( 'title', $searchTitle->getPrefixedText() );
1471 $out .= Xml::hidden( 'fulltext', 'Search' );
1472 $out .= Xml::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
1473 $out .= Xml::closeElement( 'form' );
1474
1475 return $out;
1476 }
1477 }