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