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