Add some more allowedRedirectParams to MyContributions
[lhc/web/wiklou.git] / thumb.php
1 <?php
2 /**
3 * PHP script to stream out an image thumbnail.
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 * @file
21 * @ingroup Media
22 */
23
24 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
25 require __DIR__ . '/includes/WebStart.php';
26
27 // Don't use fancy MIME detection, just check the file extension for jpg/gif/png
28 $wgTrivialMimeDetection = true;
29
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 wfStreamThumb( $_GET );
36 }
37
38 $mediawiki = new MediaWiki();
39 $mediawiki->doPostOutputShutdown( 'fast' );
40
41 //--------------------------------------------------------------------------
42
43 /**
44 * Handle a thumbnail request via thumbnail file URL
45 *
46 * @return void
47 */
48 function wfThumbHandle404() {
49 global $wgArticlePath;
50
51 # Set action base paths so that WebRequest::getPathInfo()
52 # recognizes the "X" as the 'title' in ../thumb_handler.php/X urls.
53 # Note: If Custom per-extension repo paths are set, this may break.
54 $repo = RepoGroup::singleton()->getLocalRepo();
55 $oldArticlePath = $wgArticlePath;
56 $wgArticlePath = $repo->getZoneUrl( 'thumb' ) . '/$1';
57
58 $matches = WebRequest::getPathInfo();
59
60 $wgArticlePath = $oldArticlePath;
61
62 if ( !isset( $matches['title'] ) ) {
63 wfThumbError( 404, 'Could not determine the name of the requested thumbnail.' );
64 return;
65 }
66
67 $params = wfExtractThumbRequestInfo( $matches['title'] ); // basic wiki URL param extracting
68 if ( $params == null ) {
69 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
70 return;
71 }
72
73 wfStreamThumb( $params ); // stream the thumbnail
74 }
75
76 /**
77 * Stream a thumbnail specified by parameters
78 *
79 * @param array $params List of thumbnailing parameters. In addition to parameters
80 * passed to the MediaHandler, this may also includes the keys:
81 * f (for filename), archived (if archived file), temp (if temp file),
82 * w (alias for width), p (alias for page), r (ignored; historical),
83 * rel404 (path for render on 404 to verify hash path correct),
84 * thumbName (thumbnail name to potentially extract more parameters from
85 * e.g. 'lossy-page1-120px-Foo.tiff' would add page, lossy and width
86 * to the parameters)
87 * @return void
88 */
89 function wfStreamThumb( array $params ) {
90 global $wgVaryOnXFP;
91
92
93 $headers = array(); // HTTP headers to send
94
95 $fileName = isset( $params['f'] ) ? $params['f'] : '';
96
97 // Backwards compatibility parameters
98 if ( isset( $params['w'] ) ) {
99 $params['width'] = $params['w'];
100 unset( $params['w'] );
101 }
102 if ( isset( $params['width'] ) && substr( $params['width'], -2 ) == 'px' ) {
103 // strip the px (pixel) suffix, if found
104 $params['width'] = substr( $params['width'], 0, -2 );
105 }
106 if ( isset( $params['p'] ) ) {
107 $params['page'] = $params['p'];
108 }
109
110 // Is this a thumb of an archived file?
111 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
112 unset( $params['archived'] ); // handlers don't care
113
114 // Is this a thumb of a temp file?
115 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
116 unset( $params['temp'] ); // handlers don't care
117
118 // Some basic input validation
119 $fileName = strtr( $fileName, '\\/', '__' );
120
121 // Actually fetch the image. Method depends on whether it is archived or not.
122 if ( $isTemp ) {
123 $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo();
124 $img = new UnregisteredLocalFile( null, $repo,
125 # Temp files are hashed based on the name without the timestamp.
126 # The thumbnails will be hashed based on the entire name however.
127 # @todo fix this convention to actually be reasonable.
128 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
129 );
130 } elseif ( $isOld ) {
131 // Format is <timestamp>!<name>
132 $bits = explode( '!', $fileName, 2 );
133 if ( count( $bits ) != 2 ) {
134 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
135 return;
136 }
137 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
138 if ( !$title ) {
139 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
140 return;
141 }
142 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
143 } else {
144 $img = wfLocalFile( $fileName );
145 }
146
147 // Check the source file title
148 if ( !$img ) {
149 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
150 return;
151 }
152
153 // Check permissions if there are read restrictions
154 $varyHeader = array();
155 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
156 if ( !$img->getTitle() || !$img->getTitle()->userCan( 'read' ) ) {
157 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
158 'the source file.' );
159 return;
160 }
161 $headers[] = 'Cache-Control: private';
162 $varyHeader[] = 'Cookie';
163 }
164
165 // Check if the file is hidden
166 if ( $img->isDeleted( File::DELETED_FILE ) ) {
167 wfThumbError( 404, "The source file '$fileName' does not exist." );
168 return;
169 }
170
171 // Do rendering parameters extraction from thumbnail name.
172 if ( isset( $params['thumbName'] ) ) {
173 $params = wfExtractThumbParams( $img, $params );
174 }
175 if ( $params == null ) {
176 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
177 return;
178 }
179
180 // Check the source file storage path
181 if ( !$img->exists() ) {
182 $redirectedLocation = false;
183 if ( !$isTemp ) {
184 // Check for file redirect
185 // Since redirects are associated with pages, not versions of files,
186 // we look for the most current version to see if its a redirect.
187 $possRedirFile = RepoGroup::singleton()->getLocalRepo()->findFile( $img->getName() );
188 if ( $possRedirFile && !is_null( $possRedirFile->getRedirected() ) ) {
189 $redirTarget = $possRedirFile->getName();
190 $targetFile = wfLocalFile( Title::makeTitleSafe( NS_FILE, $redirTarget ) );
191 if ( $targetFile->exists() ) {
192 $newThumbName = $targetFile->thumbName( $params );
193 if ( $isOld ) {
194 $newThumbUrl = $targetFile->getArchiveThumbUrl(
195 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
196 } else {
197 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
198 }
199 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT );
200 }
201 }
202 }
203
204 if ( $redirectedLocation ) {
205 // File has been moved. Give redirect.
206 $response = RequestContext::getMain()->getRequest()->response();
207 $response->statusHeader( 302 );
208 $response->header( 'Location: ' . $redirectedLocation );
209 $response->header( 'Expires: ' .
210 gmdate( 'D, d M Y H:i:s', time() + 12 * 3600 ) . ' GMT' );
211 if ( $wgVaryOnXFP ) {
212 $varyHeader[] = 'X-Forwarded-Proto';
213 }
214 if ( count( $varyHeader ) ) {
215 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
216 }
217 return;
218 }
219
220 // If its not a redirect that has a target as a local file, give 404.
221 wfThumbError( 404, "The source file '$fileName' does not exist." );
222 return;
223 } elseif ( $img->getPath() === false ) {
224 wfThumbError( 500, "The source file '$fileName' is not locally accessible." );
225 return;
226 }
227
228 // Check IMS against the source file
229 // This means that clients can keep a cached copy even after it has been deleted on the server
230 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
231 // Fix IE brokenness
232 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
233 // Calculate time
234 wfSuppressWarnings();
235 $imsUnix = strtotime( $imsString );
236 wfRestoreWarnings();
237 if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
238 HttpStatus::header( 304 );
239 return;
240 }
241 }
242
243 $rel404 = isset( $params['rel404'] ) ? $params['rel404'] : null;
244 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
245 unset( $params['f'] ); // We're done with 'f' parameter.
246 unset( $params['rel404'] ); // moved to $rel404
247
248 // Get the normalized thumbnail name from the parameters...
249 try {
250 $thumbName = $img->thumbName( $params );
251 if ( !strlen( $thumbName ) ) { // invalid params?
252 throw new MediaTransformInvalidParametersException( 'Empty return from File::thumbName' );
253 }
254 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
255 } catch ( MediaTransformInvalidParametersException $e ) {
256 wfThumbError( 400, 'The specified thumbnail parameters are not valid: ' . $e->getMessage() );
257 return;
258 } catch ( MWException $e ) {
259 wfThumbError( 500, $e->getHTML() );
260 return;
261 }
262
263 // For 404 handled thumbnails, we only use the base name of the URI
264 // for the thumb params and the parent directory for the source file name.
265 // Check that the zone relative path matches up so squid caches won't pick
266 // up thumbs that would not be purged on source file deletion (bug 34231).
267 if ( $rel404 !== null ) { // thumbnail was handled via 404
268 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
269 // Request for the canonical thumbnail name
270 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
271 // Request for the "long" thumbnail name; redirect to canonical name
272 $response = RequestContext::getMain()->getRequest()->response();
273 $response->statusHeader( 301 );
274 $response->header( 'Location: ' .
275 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
276 $response->header( 'Expires: ' .
277 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
278 if ( $wgVaryOnXFP ) {
279 $varyHeader[] = 'X-Forwarded-Proto';
280 }
281 if ( count( $varyHeader ) ) {
282 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
283 }
284 return;
285 } else {
286 wfThumbError( 404, "The given path of the specified thumbnail is incorrect;
287 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
288 rawurldecode( $rel404 ) . "'." );
289 return;
290 }
291 }
292
293 $dispositionType = isset( $params['download'] ) ? 'attachment' : 'inline';
294
295 // Suggest a good name for users downloading this thumbnail
296 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName, $dispositionType )}";
297
298 if ( count( $varyHeader ) ) {
299 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
300 }
301
302 // Stream the file if it exists already...
303 $thumbPath = $img->getThumbPath( $thumbName );
304 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
305 $success = $img->getRepo()->streamFile( $thumbPath, $headers );
306 if ( !$success ) {
307 wfThumbError( 500, 'Could not stream the file' );
308 }
309 return;
310 }
311
312 $user = RequestContext::getMain()->getUser();
313 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
314 wfThumbError( 500, wfMessage( 'actionthrottledtext' )->parse() );
315 return;
316 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
317 wfThumbError( 500, wfMessage( 'actionthrottledtext' )->parse() );
318 return;
319 }
320
321 // Actually generate a new thumbnail
322 list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
323 /** @var MediaTransformOutput|bool $thumb */
324
325 // Check for thumbnail generation errors...
326 $msg = wfMessage( 'thumbnail_error' );
327 $errorCode = 500;
328 if ( !$thumb ) {
329 $errorMsg = $errorMsg ?: $msg->rawParams( 'File::transform() returned false' )->escaped();
330 } elseif ( $thumb->isError() ) {
331 $errorMsg = $thumb->getHtmlMsg();
332 } elseif ( !$thumb->hasFile() ) {
333 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
334 } elseif ( $thumb->fileIsSource() ) {
335 $errorMsg = $msg->
336 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
337 $errorCode = 400;
338 }
339
340 if ( $errorMsg !== false ) {
341 wfThumbError( $errorCode, $errorMsg );
342 } else {
343 // Stream the file if there were no errors
344 $success = $thumb->streamFile( $headers );
345 if ( !$success ) {
346 wfThumbError( 500, 'Could not stream the file' );
347 }
348 }
349 }
350
351 /**
352 * Actually try to generate a new thumbnail
353 *
354 * @param File $file
355 * @param array $params
356 * @param string $thumbName
357 * @param string $thumbPath
358 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
359 */
360 function wfGenerateThumbnail( File $file, array $params, $thumbName, $thumbPath ) {
361 global $wgMemc, $wgAttemptFailureEpoch;
362
363 $key = wfMemcKey( 'attempt-failures', $wgAttemptFailureEpoch,
364 $file->getRepo()->getName(), $file->getSha1(), md5( $thumbName ) );
365
366 // Check if this file keeps failing to render
367 if ( $wgMemc->get( $key ) >= 4 ) {
368 return array( false, wfMessage( 'thumbnail_image-failure-limit', 4 ) );
369 }
370
371 $done = false;
372 // Record failures on PHP fatals in addition to caching exceptions
373 register_shutdown_function( function () use ( &$done, $key ) {
374 if ( !$done ) { // transform() gave a fatal
375 global $wgMemc;
376 // Randomize TTL to reduce stampedes
377 $wgMemc->incrWithInit( $key, 3600 + mt_rand( 0, 300 ) );
378 }
379 } );
380
381 $thumb = false;
382 $errorHtml = false;
383
384 // guard thumbnail rendering with PoolCounter to avoid stampedes
385 // expensive files use a separate PoolCounter config so it is possible
386 // to set up a global limit on them
387 if ( $file->isExpensiveToThumbnail() ) {
388 $poolCounterType = 'FileRenderExpensive';
389 } else {
390 $poolCounterType = 'FileRender';
391 }
392
393 // Thumbnail isn't already there, so create the new thumbnail...
394 try {
395 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
396 array(
397 'doWork' => function () use ( $file, $params ) {
398 return $file->transform( $params, File::RENDER_NOW );
399 },
400 'getCachedWork' => function () use ( $file, $params, $thumbPath ) {
401 // If the worker that finished made this thumbnail then use it.
402 // Otherwise, it probably made a different thumbnail for this file.
403 return $file->getRepo()->fileExists( $thumbPath )
404 ? $file->transform( $params, File::RENDER_NOW )
405 : false; // retry once more in exclusive mode
406 },
407 'fallback' => function () {
408 return wfMessage( 'generic-pool-error' )->parse();
409 },
410 'error' => function ( $status ) {
411 return $status->getHTML();
412 }
413 )
414 );
415 $result = $work->execute();
416 if ( $result instanceof MediaTransformOutput ) {
417 $thumb = $result;
418 } elseif ( is_string( $result ) ) { // error
419 $errorHtml = $result;
420 }
421 } catch ( Exception $e ) {
422 // Tried to select a page on a non-paged file?
423 }
424
425 $done = true; // no PHP fatal occured
426
427 if ( !$thumb || $thumb->isError() ) {
428 // Randomize TTL to reduce stampedes
429 $wgMemc->incrWithInit( $key, 3600 + mt_rand( 0, 300 ) );
430 }
431
432 return array( $thumb, $errorHtml );
433 }
434
435 /**
436 * Convert pathinfo type parameter, into normal request parameters
437 *
438 * So for example, if the request was redirected from
439 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
440 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
441 * This method is responsible for turning that into an array
442 * with the folowing keys:
443 * * f => the filename (Foo.png)
444 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
445 * * archived => 1 (If the request is for an archived thumb)
446 * * temp => 1 (If the file is in the "temporary" zone)
447 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
448 *
449 * Transform specific parameters are set later via wfExtractThumbParams().
450 *
451 * @param string $thumbRel Thumbnail path relative to the thumb zone
452 * @return array|null Associative params array or null
453 */
454 function wfExtractThumbRequestInfo( $thumbRel ) {
455 $repo = RepoGroup::singleton()->getLocalRepo();
456
457 $hashDirReg = $subdirReg = '';
458 $hashLevels = $repo->getHashLevels();
459 for ( $i = 0; $i < $hashLevels; $i++ ) {
460 $subdirReg .= '[0-9a-f]';
461 $hashDirReg .= "$subdirReg/";
462 }
463
464 // Check if this is a thumbnail of an original in the local file repo
465 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
466 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
467 // Check if this is a thumbnail of an temp file in the local file repo
468 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
469 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
470 } else {
471 return null; // not a valid looking thumbnail request
472 }
473
474 $params = array( 'f' => $filename, 'rel404' => $rel );
475 if ( $archOrTemp === 'archive/' ) {
476 $params['archived'] = 1;
477 } elseif ( $archOrTemp === 'temp/' ) {
478 $params['temp'] = 1;
479 }
480
481 $params['thumbName'] = $thumbname;
482 return $params;
483 }
484
485 /**
486 * Convert a thumbnail name (122px-foo.png) to parameters, using
487 * file handler.
488 *
489 * @param File $file File object for file in question
490 * @param array $params Array of parameters so far
491 * @return array Parameters array with more parameters
492 */
493 function wfExtractThumbParams( $file, $params ) {
494 if ( !isset( $params['thumbName'] ) ) {
495 throw new MWException( "No thumbnail name passed to wfExtractThumbParams" );
496 }
497
498 $thumbname = $params['thumbName'];
499 unset( $params['thumbName'] );
500
501 // Do the hook first for older extensions that rely on it.
502 if ( !Hooks::run( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
503 // Check hooks if parameters can be extracted
504 // Hooks return false if they manage to *resolve* the parameters
505 // This hook should be considered deprecated
506 wfDeprecated( 'ExtractThumbParameters', '1.22' );
507 return $params; // valid thumbnail URL (via extension or config)
508 }
509
510 // FIXME: Files in the temp zone don't set a MIME type, which means
511 // they don't have a handler. Which means we can't parse the param
512 // string. However, not a big issue as what good is a param string
513 // if you have no handler to make use of the param string and
514 // actually generate the thumbnail.
515 $handler = $file->getHandler();
516
517 // Based on UploadStash::parseKey
518 $fileNamePos = strrpos( $thumbname, $params['f'] );
519 if ( $fileNamePos === false ) {
520 // Maybe using a short filename? (see FileRepo::nameForThumb)
521 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
522 }
523
524 if ( $handler && $fileNamePos !== false ) {
525 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
526 $extraParams = $handler->parseParamString( $paramString );
527 if ( $extraParams !== false ) {
528 return $params + $extraParams;
529 }
530 }
531
532 // As a last ditch fallback, use the traditional common parameters
533 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
534 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
535 $params['width'] = $size;
536 if ( $pagenum ) {
537 $params['page'] = $pagenum;
538 }
539 return $params; // valid thumbnail URL
540 }
541 return null;
542 }
543
544 /**
545 * Output a thumbnail generation error message
546 *
547 * @param int $status
548 * @param string $msg HTML
549 * @return void
550 */
551 function wfThumbError( $status, $msg ) {
552 global $wgShowHostnames;
553
554 header( 'Cache-Control: no-cache' );
555 header( 'Content-Type: text/html; charset=utf-8' );
556 if ( $status == 400 ) {
557 HttpStatus::header( 400 );
558 } elseif ( $status == 404 ) {
559 HttpStatus::header( 404 );
560 } elseif ( $status == 403 ) {
561 HttpStatus::header( 403 );
562 header( 'Vary: Cookie' );
563 } else {
564 HttpStatus::header( 500 );
565 }
566 if ( $wgShowHostnames ) {
567 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
568 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
569 $hostname = htmlspecialchars( wfHostname() );
570 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
571 } else {
572 $debug = '';
573 }
574 echo <<<EOT
575 <!DOCTYPE html>
576 <html><head>
577 <meta charset="UTF-8" />
578 <title>Error generating thumbnail</title>
579 </head>
580 <body>
581 <h1>Error generating thumbnail</h1>
582 <p>
583 $msg
584 </p>
585 $debug
586 </body>
587 </html>
588
589 EOT;
590 }