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