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