fixed potential XSS vulnerability
[mediawiki.git] / includes / SpecialSearch.php
blobd29f2e30a89c47f1102d2c9e0894116657dbba6a
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.
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 # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 # http://www.gnu.org/copyleft/gpl.html
20 /**
21 * Run text & title search and display the output
22 * @package MediaWiki
23 * @subpackage SpecialPage
26 /** */
27 require_once( 'SearchEngine.php' );
28 require_once( 'Revision.php' );
30 /**
31 * Entry point
33 * @param string $par (default '')
35 function wfSpecialSearch( $par = '' ) {
36 global $wgRequest, $wgUser;
38 $search = $wgRequest->getText( 'search', $par );
39 $searchPage = new SpecialSearch( $wgRequest, $wgUser );
40 if( $wgRequest->getVal( 'fulltext' ) ||
41 !is_null( $wgRequest->getVal( 'offset' ) ) ||
42 !is_null ($wgRequest->getVal( 'searchx' ) ) ) {
43 $searchPage->showResults( $search );
44 } else {
45 $searchPage->goResult( $search );
49 /**
50 * @todo document
51 * @package MediaWiki
52 * @subpackage SpecialPage
54 class SpecialSearch {
56 /**
57 * Set up basic search parameters from the request and user settings.
58 * Typically you'll pass $wgRequest and $wgUser.
60 * @param WebRequest $request
61 * @param User $user
62 * @access public
64 function SpecialSearch( &$request, &$user ) {
65 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
67 if( $request->getCheck( 'searchx' ) ) {
68 $this->namespaces = $this->powerSearch( $request );
69 } else {
70 $this->namespaces = $this->userNamespaces( $user );
73 $this->searchRedirects = false;
76 /**
77 * If an exact title match can be found, jump straight ahead to
78 * @param string $term
79 * @access public
81 function goResult( $term ) {
82 global $wgOut;
83 global $wgGoToEdit;
85 $this->setupPage( $term );
87 # Try to go to page as entered.
89 $t = Title::newFromText( $term );
91 # If the string cannot be used to create a title
92 if( is_null( $t ) ){
93 return $this->showResults( $term );
96 # If there's an exact or very near match, jump right there.
97 $t = SearchEngine::getNearMatch( $term );
98 if( !is_null( $t ) ) {
99 $wgOut->redirect( $t->getFullURL() );
100 return;
103 # No match, generate an edit URL
104 $t = Title::newFromText( $term );
105 if( is_null( $t ) ) {
106 $editurl = ''; # hrm...
107 } else {
108 # If the feature is enabled, go straight to the edit page
109 if ( $wgGoToEdit ) {
110 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
111 return;
112 } else {
113 $editurl = $t->escapeLocalURL( 'action=edit' );
116 $wgOut->addWikiText( wfMsg('nogomatch', ":$term" ) );
118 return $this->showResults( $term );
122 * @param string $term
123 * @access public
125 function showResults( $term ) {
126 $fname = 'SpecialSearch::showResults';
127 wfProfileIn( $fname );
129 $this->setupPage( $term );
131 global $wgUser, $wgOut;
132 $sk = $wgUser->getSkin();
133 $wgOut->addWikiText( wfMsg( 'searchresulttext' ) );
135 #if ( !$this->parseQuery() ) {
136 if( '' === trim( $term ) ) {
137 $wgOut->addWikiText(
138 '==' . wfMsg( 'badquery' ) . "==\n" .
139 wfMsg( 'badquerytext' ) );
140 wfProfileOut( $fname );
141 return;
144 global $wgDisableTextSearch;
145 if ( $wgDisableTextSearch ) {
146 global $wgForwardSearchUrl;
147 if( $wgForwardSearchUrl ) {
148 $url = str_replace( '$1', urlencode( $term ), $wgForwardSearchUrl );
149 $wgOut->redirect( $url );
150 return;
152 global $wgInputEncoding;
153 $wgOut->addHTML( wfMsg( 'searchdisabled' ) );
154 $wgOut->addHTML(
155 wfMsg( 'googlesearch',
156 htmlspecialchars( $term ),
157 htmlspecialchars( $wgInputEncoding ),
158 htmlspecialchars( wfMsg( 'search' ) )
161 wfProfileOut( $fname );
162 return;
165 $search =& SearchEngine::create();
166 $search->setLimitOffset( $this->limit, $this->offset );
167 $search->setNamespaces( $this->namespaces );
168 $titleMatches = $search->searchTitle( $term );
169 $textMatches = $search->searchText( $term );
171 $num = $titleMatches->numRows() + $textMatches->numRows();
172 if ( $num >= $this->limit ) {
173 $top = wfShowingResults( $this->offset, $this->limit );
174 } else {
175 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
177 $wgOut->addHTML( "<p>{$top}</p>\n" );
179 if( $num || $this->offset ) {
180 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
181 'Special:Search',
182 wfArrayToCGI(
183 $this->powerSearchOptions(),
184 array( 'search' => $term ) ) );
185 $wgOut->addHTML( "<br />{$prevnext}\n" );
188 global $wgContLang;
189 $tm = $wgContLang->convertForSearchResult( $search->termMatches() );
190 $terms = implode( '|', $tm );
192 if( $titleMatches->numRows() ) {
193 $wgOut->addWikiText( '==' . wfMsg( 'titlematches' ) . "==\n" );
194 $wgOut->addHTML( $this->showMatches( $titleMatches, $terms ) );
195 } else {
196 $wgOut->addWikiText( '==' . wfMsg( 'notitlematches' ) . "==\n" );
199 if( $textMatches->numRows() ) {
200 $wgOut->addWikiText( '==' . wfMsg( 'textmatches' ) . "==\n" );
201 $wgOut->addHTML( $this->showMatches( $textMatches, $terms ) );
202 } elseif( $num == 0 ) {
203 # Don't show the 'no text matches' if we received title matches
204 $wgOut->addWikiText( '==' . wfMsg( 'notextmatches' ) . "==\n" );
207 if ( $num == 0 ) {
208 $wgOut->addWikiText( wfMsg( 'nonefound' ) );
210 if( $num || $this->offset ) {
211 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
213 $wgOut->addHTML( $this->powerSearchBox( $term ) );
214 wfProfileOut( $fname );
217 #------------------------------------------------------------------
218 # Private methods below this line
223 function setupPage( $term ) {
224 global $wgOut;
225 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
226 $wgOut->setSubtitle( wfMsg( 'searchquery', htmlspecialchars( $term ) ) );
227 $wgOut->setArticleRelated( false );
228 $wgOut->setRobotpolicy( 'noindex,nofollow' );
232 * Extract default namespaces to search from the given user's
233 * settings, returning a list of index numbers.
235 * @param User $user
236 * @return array
237 * @access private
239 function userNamespaces( &$user ) {
240 $arr = array();
241 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
242 if( $user->getOption( 'searchNs' . $ns ) ) {
243 $arr[] = $ns;
246 return $arr;
250 * Extract "power search" namespace settings from the request object,
251 * returning a list of index numbers to search.
253 * @param WebRequest $request
254 * @return array
255 * @access private
257 function powerSearch( &$request ) {
258 $arr = array();
259 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
260 if( $request->getCheck( 'ns' . $ns ) ) {
261 $arr[] = $ns;
264 return $arr;
268 * Reconstruct the 'power search' options for links
269 * @return array
270 * @access private
272 function powerSearchOptions() {
273 $opt = array();
274 foreach( $this->namespaces as $n ) {
275 $opt['ns' . $n] = 1;
277 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
278 $opt['searchx'] = 1;
279 return $opt;
283 * @param ResultWrapper $matches
284 * @param string $terms partial regexp for highlighting terms
286 function showMatches( &$matches, $terms ) {
287 $fname = 'SpecialSearch::showMatches';
288 wfProfileIn( $fname );
290 global $wgOut;
291 $off = $this->offset + 1;
292 $out = "<ol start='{$off}'>\n";
294 while( $row = $matches->fetchObject() ) {
295 $out .= $this->showHit( $row, $terms );
297 $out .= "</ol>\n";
299 // convert the whole thing to desired language variant
300 global $wgContLang;
301 $out = $wgContLang->convert( $out );
302 wfProfileOut( $fname );
303 return $out;
307 * Format a single hit result
308 * @param object $row
309 * @param string $terms partial regexp for highlighting terms
311 function showHit( $row, $terms ) {
312 $fname = 'SpecialSearch::showHit';
313 wfProfileIn( $fname );
314 global $wgUser, $wgContLang;
316 $t = Title::makeTitle( $row->page_namespace, $row->page_title );
317 if( is_null( $t ) ) {
318 wfProfileOut( $fname );
319 return "<!-- Broken link in search result -->\n";
321 $sk =& $wgUser->getSkin();
323 $contextlines = $wgUser->getOption( 'contextlines' );
324 if ( '' == $contextlines ) { $contextlines = 5; }
325 $contextchars = $wgUser->getOption( 'contextchars' );
326 if ( '' == $contextchars ) { $contextchars = 50; }
328 $link = $sk->makeKnownLinkObj( $t, '' );
329 $text = Revision::getRevisionText( $row );
330 $size = wfMsg( 'nbytes', strlen( $text ) );
332 $lines = explode( "\n", $text );
334 $max = IntVal( $contextchars ) + 1;
335 $pat1 = "/(.*)($terms)(.{0,$max})/i";
337 $lineno = 0;
339 $extract = '';
340 wfProfileIn( "$fname-extract" );
341 foreach ( $lines as $line ) {
342 if ( 0 == $contextlines ) {
343 break;
345 ++$lineno;
346 if ( ! preg_match( $pat1, $line, $m ) ) {
347 continue;
349 --$contextlines;
350 $pre = $wgContLang->truncate( $m[1], -$contextchars, '...' );
352 if ( count( $m ) < 3 ) {
353 $post = '';
354 } else {
355 $post = $wgContLang->truncate( $m[3], $contextchars, '...' );
358 $found = $m[2];
360 $line = htmlspecialchars( $pre . $found . $post );
361 $pat2 = '/(' . $terms . ")/i";
362 $line = preg_replace( $pat2,
363 "<span class='searchmatch'>\\1</span>", $line );
365 $extract .= "<br /><small>{$lineno}: {$line}</small>\n";
367 wfProfileOut( "$fname-extract" );
368 wfProfileOut( $fname );
369 return "<li>{$link} ({$size}){$extract}</li>\n";
372 function powerSearchBox( $term ) {
373 $namespaces = '';
374 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
375 $checked = in_array( $ns, $this->namespaces )
376 ? ' checked="checked"'
377 : '';
378 $name = str_replace( '_', ' ', $name );
379 if( '' == $name ) {
380 $name = wfMsg( 'blanknamespace' );
382 $namespaces .= " <label><input type='checkbox' value=\"1\" name=\"" .
383 "ns{$ns}\"{$checked} />{$name}</label>\n";
386 $checked = $this->searchRedirects
387 ? ' checked="checked"'
388 : '';
389 $redirect = "<input type='checkbox' value='1' name=\"redirs\"{$checked} />\n";
391 $searchField = "<input type='text' name=\"search\" value=\"" .
392 htmlspecialchars( $term ) ."\" width=\"80\" />\n";
394 $searchButton = '<input type="submit" name="searchx" value="' .
395 htmlspecialchars( wfMsg('powersearch') ) . "\" />\n";
397 $ret = wfMsg( 'powersearchtext',
398 $namespaces, $redirect, $searchField,
399 '', '', '', '', '', # Dummy placeholders
400 $searchButton );
402 $title = Title::makeTitle( NS_SPECIAL, 'Search' );
403 $action = $title->escapeLocalURL();
404 return "<br /><br />\n<form id=\"powersearch\" method=\"get\" " .
405 "action=\"$action\">\n{$ret}\n</form>\n";