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