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