Remove superfluous re- from confirmemail_body_set
[mediawiki.git] / thumb.php
blob4a0c9fb3d394b25b92e1e13ac29b7b6bb19e01ae
1 <?php
2 /**
3 * PHP script to stream out an image thumbnail.
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.
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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Media
24 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
25 require __DIR__ . '/includes/WebStart.php';
27 // Don't use fancy mime detection, just check the file extension for jpg/gif/png
28 $wgTrivialMimeDetection = true;
30 if ( defined( 'THUMB_HANDLER' ) ) {
31 // Called from thumb_handler.php via 404; extract params from the URI...
32 wfThumbHandle404();
33 } else {
34 // Called directly, use $_GET params
35 wfThumbHandleRequest();
38 wfLogProfilingData();
40 //--------------------------------------------------------------------------
42 /**
43 * Handle a thumbnail request via query parameters
45 * @return void
47 function wfThumbHandleRequest() {
48 $params = get_magic_quotes_gpc()
49 ? array_map( 'stripslashes', $_GET )
50 : $_GET;
52 wfStreamThumb( $params ); // stream the thumbnail
55 /**
56 * Handle a thumbnail request via thumbnail file URL
58 * @return void
60 function wfThumbHandle404() {
61 global $wgArticlePath;
63 # Set action base paths so that WebRequest::getPathInfo()
64 # recognizes the "X" as the 'title' in ../thumb_handler.php/X urls.
65 $wgArticlePath = false; # Don't let a "/*" article path clober our action path
67 $matches = WebRequest::getPathInfo();
68 if ( !isset( $matches['title'] ) ) {
69 wfThumbError( 404, 'Could not determine the name of the requested thumbnail.' );
70 return;
73 $params = wfExtractThumbParams( $matches['title'] ); // basic wiki URL param extracting
74 if ( $params == null ) {
75 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
76 return;
79 wfStreamThumb( $params ); // stream the thumbnail
82 /**
83 * Stream a thumbnail specified by parameters
85 * @param $params Array
86 * @return void
88 function wfStreamThumb( array $params ) {
89 global $wgVaryOnXFP;
91 wfProfileIn( __METHOD__ );
93 $headers = array(); // HTTP headers to send
95 $fileName = isset( $params['f'] ) ? $params['f'] : '';
96 unset( $params['f'] );
98 // Backwards compatibility parameters
99 if ( isset( $params['w'] ) ) {
100 $params['width'] = $params['w'];
101 unset( $params['w'] );
103 if ( isset( $params['p'] ) ) {
104 $params['page'] = $params['p'];
106 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
108 // Is this a thumb of an archived file?
109 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
110 unset( $params['archived'] ); // handlers don't care
112 // Is this a thumb of a temp file?
113 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
114 unset( $params['temp'] ); // handlers don't care
116 // Some basic input validation
117 $fileName = strtr( $fileName, '\\/', '__' );
119 // Actually fetch the image. Method depends on whether it is archived or not.
120 if ( $isTemp ) {
121 $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo();
122 $img = new UnregisteredLocalFile( null, $repo,
123 # Temp files are hashed based on the name without the timestamp.
124 # The thumbnails will be hashed based on the entire name however.
125 # @todo fix this convention to actually be reasonable.
126 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
128 } elseif ( $isOld ) {
129 // Format is <timestamp>!<name>
130 $bits = explode( '!', $fileName, 2 );
131 if ( count( $bits ) != 2 ) {
132 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
133 wfProfileOut( __METHOD__ );
134 return;
136 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
137 if ( !$title ) {
138 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
139 wfProfileOut( __METHOD__ );
140 return;
142 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
143 } else {
144 $img = wfLocalFile( $fileName );
147 // Check the source file title
148 if ( !$img ) {
149 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
150 wfProfileOut( __METHOD__ );
151 return;
154 // Check permissions if there are read restrictions
155 $varyHeader = array();
156 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
157 if ( !$img->getTitle() || !$img->getTitle()->userCan( 'read' ) ) {
158 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
159 'the source file.' );
160 wfProfileOut( __METHOD__ );
161 return;
163 $headers[] = 'Cache-Control: private';
164 $varyHeader[] = 'Cookie';
167 // Check the source file storage path
168 if ( !$img->exists() ) {
169 wfThumbError( 404, "The source file '$fileName' does not exist." );
170 wfProfileOut( __METHOD__ );
171 return;
172 } elseif ( $img->getPath() === false ) {
173 wfThumbError( 500, "The source file '$fileName' is not locally accessible." );
174 wfProfileOut( __METHOD__ );
175 return;
178 // Check IMS against the source file
179 // This means that clients can keep a cached copy even after it has been deleted on the server
180 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
181 // Fix IE brokenness
182 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
183 // Calculate time
184 wfSuppressWarnings();
185 $imsUnix = strtotime( $imsString );
186 wfRestoreWarnings();
187 if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
188 header( 'HTTP/1.1 304 Not Modified' );
189 wfProfileOut( __METHOD__ );
190 return;
194 // Get the normalized thumbnail name from the parameters...
195 try {
196 $thumbName = $img->thumbName( $params );
197 if ( !strlen( $thumbName ) ) { // invalid params?
198 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
199 wfProfileOut( __METHOD__ );
200 return;
202 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
203 } catch ( MWException $e ) {
204 wfThumbError( 500, $e->getHTML() );
205 wfProfileOut( __METHOD__ );
206 return;
209 // For 404 handled thumbnails, we only use the the base name of the URI
210 // for the thumb params and the parent directory for the source file name.
211 // Check that the zone relative path matches up so squid caches won't pick
212 // up thumbs that would not be purged on source file deletion (bug 34231).
213 if ( isset( $params['rel404'] ) ) { // thumbnail was handled via 404
214 if ( rawurldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName ) ) {
215 // Request for the canonical thumbnail name
216 } elseif ( rawurldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName2 ) ) {
217 // Request for the "long" thumbnail name; redirect to canonical name
218 $response = RequestContext::getMain()->getRequest()->response();
219 $response->header( "HTTP/1.1 301 " . HttpStatus::getMessage( 301 ) );
220 $response->header( 'Location: ' .
221 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
222 $response->header( 'Expires: ' .
223 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
224 if ( $wgVaryOnXFP ) {
225 $varyHeader[] = 'X-Forwarded-Proto';
227 if ( count( $varyHeader ) ) {
228 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
230 wfProfileOut( __METHOD__ );
231 return;
232 } else {
233 wfThumbError( 404, "The given path of the specified thumbnail is incorrect;
234 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
235 rawurldecode( $params['rel404'] ) . "'." );
236 wfProfileOut( __METHOD__ );
237 return;
241 // Suggest a good name for users downloading this thumbnail
242 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName )}";
244 if ( count( $varyHeader ) ) {
245 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
248 // Stream the file if it exists already...
249 $thumbPath = $img->getThumbPath( $thumbName );
250 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
251 $img->getRepo()->streamFile( $thumbPath, $headers );
252 wfProfileOut( __METHOD__ );
253 return;
256 // Thumbnail isn't already there, so create the new thumbnail...
257 try {
258 $thumb = $img->transform( $params, File::RENDER_NOW );
259 } catch ( Exception $ex ) {
260 // Tried to select a page on a non-paged file?
261 $thumb = false;
264 // Check for thumbnail generation errors...
265 $errorMsg = false;
266 $msg = wfMessage( 'thumbnail_error' );
267 if ( !$thumb ) {
268 $errorMsg = $msg->rawParams( 'File::transform() returned false' )->escaped();
269 } elseif ( $thumb->isError() ) {
270 $errorMsg = $thumb->getHtmlMsg();
271 } elseif ( !$thumb->hasFile() ) {
272 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
273 } elseif ( $thumb->fileIsSource() ) {
274 $errorMsg = $msg->
275 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
278 if ( $errorMsg !== false ) {
279 wfThumbError( 500, $errorMsg );
280 } else {
281 // Stream the file if there were no errors
282 $thumb->streamFile( $headers );
285 wfProfileOut( __METHOD__ );
289 * Extract the required params for thumb.php from the thumbnail request URI.
290 * At least 'width' and 'f' should be set if the result is an array.
292 * @param $thumbRel String Thumbnail path relative to the thumb zone
293 * @return Array|null associative params array or null
295 function wfExtractThumbParams( $thumbRel ) {
296 $repo = RepoGroup::singleton()->getLocalRepo();
298 $hashDirReg = $subdirReg = '';
299 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
300 $subdirReg .= '[0-9a-f]';
301 $hashDirReg .= "$subdirReg/";
304 // Check if this is a thumbnail of an original in the local file repo
305 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
306 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
307 // Check if this is a thumbnail of an temp file in the local file repo
308 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
309 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
310 } else {
311 return null; // not a valid looking thumbnail request
314 $params = array( 'f' => $filename, 'rel404' => $rel );
315 if ( $archOrTemp === 'archive/' ) {
316 $params['archived'] = 1;
317 } elseif ( $archOrTemp === 'temp/' ) {
318 $params['temp'] = 1;
321 // Check hooks if parameters can be extracted
322 // Hooks return false if they manage to *resolve* the parameters
323 if ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
324 return $params; // valid thumbnail URL (via extension or config)
325 // Check if the parameters can be extracted from the thumbnail name...
326 } elseif ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
327 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
328 $params['width'] = $size;
329 if ( $pagenum ) {
330 $params['page'] = $pagenum;
332 return $params; // valid thumbnail URL
335 return null; // not a valid thumbnail URL
339 * Output a thumbnail generation error message
341 * @param $status integer
342 * @param $msg string
343 * @return void
345 function wfThumbError( $status, $msg ) {
346 global $wgShowHostnames;
348 header( 'Cache-Control: no-cache' );
349 header( 'Content-Type: text/html; charset=utf-8' );
350 if ( $status == 404 ) {
351 header( 'HTTP/1.1 404 Not found' );
352 } elseif ( $status == 403 ) {
353 header( 'HTTP/1.1 403 Forbidden' );
354 header( 'Vary: Cookie' );
355 } else {
356 header( 'HTTP/1.1 500 Internal server error' );
358 if ( $wgShowHostnames ) {
359 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
360 $hostname = htmlspecialchars( wfHostname() );
361 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
362 } else {
363 $debug = '';
365 echo <<<EOT
366 <html><head><title>Error generating thumbnail</title></head>
367 <body>
368 <h1>Error generating thumbnail</h1>
370 $msg
371 </p>
372 $debug
373 </body>
374 </html>
376 EOT;