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
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...
34 // Called directly, use $_GET params
35 wfStreamThumb( $_GET );
38 $mediawiki = new MediaWiki();
39 $mediawiki->doPostOutputShutdown( 'fast' );
41 //--------------------------------------------------------------------------
44 * Handle a thumbnail request via thumbnail file URL
48 function wfThumbHandle404() {
49 global $wgArticlePath;
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';
58 $matches = WebRequest
::getPathInfo();
60 $wgArticlePath = $oldArticlePath;
62 if ( !isset( $matches['title'] ) ) {
63 wfThumbError( 404, 'Could not determine the name of the requested thumbnail.' );
67 $params = wfExtractThumbRequestInfo( $matches['title'] ); // basic wiki URL param extracting
68 if ( $params == null ) {
69 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
73 wfStreamThumb( $params ); // stream the thumbnail
77 * Stream a thumbnail specified by parameters
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
89 function wfStreamThumb( array $params ) {
92 $headers = array(); // HTTP headers to send
94 $fileName = isset( $params['f'] ) ?
$params['f'] : '';
96 // Backwards compatibility parameters
97 if ( isset( $params['w'] ) ) {
98 $params['width'] = $params['w'];
99 unset( $params['w'] );
101 if ( isset( $params['width'] ) && substr( $params['width'], -2 ) == 'px' ) {
102 // strip the px (pixel) suffix, if found
103 $params['width'] = substr( $params['width'], 0, -2 );
105 if ( isset( $params['p'] ) ) {
106 $params['page'] = $params['p'];
109 // Is this a thumb of an archived file?
110 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
111 unset( $params['archived'] ); // handlers don't care
113 // Is this a thumb of a temp file?
114 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
115 unset( $params['temp'] ); // handlers don't care
117 // Some basic input validation
118 $fileName = strtr( $fileName, '\\/', '__' );
120 // Actually fetch the image. Method depends on whether it is archived or not.
122 $repo = RepoGroup
::singleton()->getLocalRepo()->getTempRepo();
123 $img = new UnregisteredLocalFile( null, $repo,
124 # Temp files are hashed based on the name without the timestamp.
125 # The thumbnails will be hashed based on the entire name however.
126 # @todo fix this convention to actually be reasonable.
127 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
129 } elseif ( $isOld ) {
130 // Format is <timestamp>!<name>
131 $bits = explode( '!', $fileName, 2 );
132 if ( count( $bits ) != 2 ) {
133 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
136 $title = Title
::makeTitleSafe( NS_FILE
, $bits[1] );
138 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
141 $img = RepoGroup
::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
143 $img = wfLocalFile( $fileName );
146 // Check the source file title
148 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
152 // Check permissions if there are read restrictions
153 $varyHeader = array();
154 if ( !in_array( 'read', User
::getGroupPermissions( array( '*' ) ), true ) ) {
155 if ( !$img->getTitle() ||
!$img->getTitle()->userCan( 'read' ) ) {
156 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
157 'the source file.' );
160 $headers[] = 'Cache-Control: private';
161 $varyHeader[] = 'Cookie';
164 // Check if the file is hidden
165 if ( $img->isDeleted( File
::DELETED_FILE
) ) {
166 wfThumbError( 404, "The source file '$fileName' does not exist." );
170 // Do rendering parameters extraction from thumbnail name.
171 if ( isset( $params['thumbName'] ) ) {
172 $params = wfExtractThumbParams( $img, $params );
174 if ( $params == null ) {
175 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
179 // Check the source file storage path
180 if ( !$img->exists() ) {
181 $redirectedLocation = false;
183 // Check for file redirect
184 // Since redirects are associated with pages, not versions of files,
185 // we look for the most current version to see if its a redirect.
186 $possRedirFile = RepoGroup
::singleton()->getLocalRepo()->findFile( $img->getName() );
187 if ( $possRedirFile && !is_null( $possRedirFile->getRedirected() ) ) {
188 $redirTarget = $possRedirFile->getName();
189 $targetFile = wfLocalFile( Title
::makeTitleSafe( NS_FILE
, $redirTarget ) );
190 if ( $targetFile->exists() ) {
191 $newThumbName = $targetFile->thumbName( $params );
193 $newThumbUrl = $targetFile->getArchiveThumbUrl(
194 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
196 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
198 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT
);
203 if ( $redirectedLocation ) {
204 // File has been moved. Give redirect.
205 $response = RequestContext
::getMain()->getRequest()->response();
206 $response->statusHeader( 302 );
207 $response->header( 'Location: ' . $redirectedLocation );
208 $response->header( 'Expires: ' .
209 gmdate( 'D, d M Y H:i:s', time() +
12 * 3600 ) . ' GMT' );
210 if ( $wgVaryOnXFP ) {
211 $varyHeader[] = 'X-Forwarded-Proto';
213 if ( count( $varyHeader ) ) {
214 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
219 // If its not a redirect that has a target as a local file, give 404.
220 wfThumbError( 404, "The source file '$fileName' does not exist." );
222 } elseif ( $img->getPath() === false ) {
223 wfThumbError( 500, "The source file '$fileName' is not locally accessible." );
227 // Check IMS against the source file
228 // This means that clients can keep a cached copy even after it has been deleted on the server
229 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
231 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
233 MediaWiki\
suppressWarnings();
234 $imsUnix = strtotime( $imsString );
235 MediaWiki\restoreWarnings
();
236 if ( wfTimestamp( TS_UNIX
, $img->getTimestamp() ) <= $imsUnix ) {
237 HttpStatus
::header( 304 );
242 $rel404 = isset( $params['rel404'] ) ?
$params['rel404'] : null;
243 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
244 unset( $params['f'] ); // We're done with 'f' parameter.
245 unset( $params['rel404'] ); // moved to $rel404
247 // Get the normalized thumbnail name from the parameters...
249 $thumbName = $img->thumbName( $params );
250 if ( !strlen( $thumbName ) ) { // invalid params?
251 throw new MediaTransformInvalidParametersException( 'Empty return from File::thumbName' );
253 $thumbName2 = $img->thumbName( $params, File
::THUMB_FULL_NAME
); // b/c; "long" style
254 } catch ( MediaTransformInvalidParametersException
$e ) {
255 wfThumbError( 400, 'The specified thumbnail parameters are not valid: ' . $e->getMessage() );
257 } catch ( MWException
$e ) {
258 wfThumbError( 500, $e->getHTML() );
262 // For 404 handled thumbnails, we only use the base name of the URI
263 // for the thumb params and the parent directory for the source file name.
264 // Check that the zone relative path matches up so squid caches won't pick
265 // up thumbs that would not be purged on source file deletion (bug 34231).
266 if ( $rel404 !== null ) { // thumbnail was handled via 404
267 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
268 // Request for the canonical thumbnail name
269 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
270 // Request for the "long" thumbnail name; redirect to canonical name
271 $response = RequestContext
::getMain()->getRequest()->response();
272 $response->statusHeader( 301 );
273 $response->header( 'Location: ' .
274 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT
) );
275 $response->header( 'Expires: ' .
276 gmdate( 'D, d M Y H:i:s', time() +
7 * 86400 ) . ' GMT' );
277 if ( $wgVaryOnXFP ) {
278 $varyHeader[] = 'X-Forwarded-Proto';
280 if ( count( $varyHeader ) ) {
281 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
285 wfThumbError( 404, "The given path of the specified thumbnail is incorrect;
286 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
287 rawurldecode( $rel404 ) . "'." );
292 $dispositionType = isset( $params['download'] ) ?
'attachment' : 'inline';
294 // Suggest a good name for users downloading this thumbnail
295 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName, $dispositionType )}";
297 if ( count( $varyHeader ) ) {
298 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
301 $stats = RequestContext
::getMain()->getStats();
303 // Stream the file if it exists already...
304 $thumbPath = $img->getThumbPath( $thumbName );
305 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
306 $starttime = microtime( true );
307 $success = $img->getRepo()->streamFile( $thumbPath, $headers );
308 $streamtime = microtime( true ) - $starttime;
311 wfThumbError( 500, 'Could not stream the file' );
313 $stats->timing( 'media.thumbnail.stream', $streamtime );
318 $user = RequestContext
::getMain()->getUser();
319 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
320 wfThumbError( 500, wfMessage( 'actionthrottledtext' )->parse() );
322 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
323 wfThumbError( 500, wfMessage( 'actionthrottledtext' )->parse() );
327 // Actually generate a new thumbnail
328 $starttime = microtime( true );
329 list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
330 $generatetime = microtime( true ) - $starttime;
331 /** @var MediaTransformOutput|bool $thumb */
333 // Check for thumbnail generation errors...
334 $msg = wfMessage( 'thumbnail_error' );
337 $errorMsg = $errorMsg ?
: $msg->rawParams( 'File::transform() returned false' )->escaped();
338 } elseif ( $thumb->isError() ) {
339 $errorMsg = $thumb->getHtmlMsg();
340 } elseif ( !$thumb->hasFile() ) {
341 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
342 } elseif ( $thumb->fileIsSource() ) {
344 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
348 if ( $errorMsg !== false ) {
349 wfThumbError( $errorCode, $errorMsg );
351 $stats->timing( 'media.thumbnail.generate', $generatetime );
353 // Stream the file if there were no errors
354 $success = $thumb->streamFile( $headers );
356 wfThumbError( 500, 'Could not stream the file' );
362 * Actually try to generate a new thumbnail
365 * @param array $params
366 * @param string $thumbName
367 * @param string $thumbPath
368 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
370 function wfGenerateThumbnail( File
$file, array $params, $thumbName, $thumbPath ) {
371 global $wgMemc, $wgAttemptFailureEpoch;
373 $key = wfMemcKey( 'attempt-failures', $wgAttemptFailureEpoch,
374 $file->getRepo()->getName(), $file->getSha1(), md5( $thumbName ) );
376 // Check if this file keeps failing to render
377 if ( $wgMemc->get( $key ) >= 4 ) {
378 return array( false, wfMessage( 'thumbnail_image-failure-limit', 4 ) );
382 // Record failures on PHP fatals in addition to caching exceptions
383 register_shutdown_function( function () use ( &$done, $key ) {
384 if ( !$done ) { // transform() gave a fatal
386 // Randomize TTL to reduce stampedes
387 $wgMemc->incrWithInit( $key, 3600 +
mt_rand( 0, 300 ) );
394 // guard thumbnail rendering with PoolCounter to avoid stampedes
395 // expensive files use a separate PoolCounter config so it is possible
396 // to set up a global limit on them
397 if ( $file->isExpensiveToThumbnail() ) {
398 $poolCounterType = 'FileRenderExpensive';
400 $poolCounterType = 'FileRender';
403 // Thumbnail isn't already there, so create the new thumbnail...
405 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
407 'doWork' => function () use ( $file, $params ) {
408 return $file->transform( $params, File
::RENDER_NOW
);
410 'getCachedWork' => function () use ( $file, $params, $thumbPath ) {
411 // If the worker that finished made this thumbnail then use it.
412 // Otherwise, it probably made a different thumbnail for this file.
413 return $file->getRepo()->fileExists( $thumbPath )
414 ?
$file->transform( $params, File
::RENDER_NOW
)
415 : false; // retry once more in exclusive mode
417 'fallback' => function () {
418 return wfMessage( 'generic-pool-error' )->parse();
420 'error' => function ( $status ) {
421 return $status->getHTML();
425 $result = $work->execute();
426 if ( $result instanceof MediaTransformOutput
) {
428 } elseif ( is_string( $result ) ) { // error
429 $errorHtml = $result;
431 } catch ( Exception
$e ) {
432 // Tried to select a page on a non-paged file?
435 $done = true; // no PHP fatal occured
437 if ( !$thumb ||
$thumb->isError() ) {
438 // Randomize TTL to reduce stampedes
439 $wgMemc->incrWithInit( $key, 3600 +
mt_rand( 0, 300 ) );
442 return array( $thumb, $errorHtml );
446 * Convert pathinfo type parameter, into normal request parameters
448 * So for example, if the request was redirected from
449 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
450 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
451 * This method is responsible for turning that into an array
452 * with the folowing keys:
453 * * f => the filename (Foo.png)
454 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
455 * * archived => 1 (If the request is for an archived thumb)
456 * * temp => 1 (If the file is in the "temporary" zone)
457 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
459 * Transform specific parameters are set later via wfExtractThumbParams().
461 * @param string $thumbRel Thumbnail path relative to the thumb zone
462 * @return array|null Associative params array or null
464 function wfExtractThumbRequestInfo( $thumbRel ) {
465 $repo = RepoGroup
::singleton()->getLocalRepo();
467 $hashDirReg = $subdirReg = '';
468 $hashLevels = $repo->getHashLevels();
469 for ( $i = 0; $i < $hashLevels; $i++
) {
470 $subdirReg .= '[0-9a-f]';
471 $hashDirReg .= "$subdirReg/";
474 // Check if this is a thumbnail of an original in the local file repo
475 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
476 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
477 // Check if this is a thumbnail of an temp file in the local file repo
478 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
479 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
481 return null; // not a valid looking thumbnail request
484 $params = array( 'f' => $filename, 'rel404' => $rel );
485 if ( $archOrTemp === 'archive/' ) {
486 $params['archived'] = 1;
487 } elseif ( $archOrTemp === 'temp/' ) {
491 $params['thumbName'] = $thumbname;
496 * Convert a thumbnail name (122px-foo.png) to parameters, using
499 * @param File $file File object for file in question
500 * @param array $params Array of parameters so far
501 * @return array Parameters array with more parameters
503 function wfExtractThumbParams( $file, $params ) {
504 if ( !isset( $params['thumbName'] ) ) {
505 throw new MWException( "No thumbnail name passed to wfExtractThumbParams" );
508 $thumbname = $params['thumbName'];
509 unset( $params['thumbName'] );
511 // Do the hook first for older extensions that rely on it.
512 if ( !Hooks
::run( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
513 // Check hooks if parameters can be extracted
514 // Hooks return false if they manage to *resolve* the parameters
515 // This hook should be considered deprecated
516 wfDeprecated( 'ExtractThumbParameters', '1.22' );
517 return $params; // valid thumbnail URL (via extension or config)
520 // FIXME: Files in the temp zone don't set a MIME type, which means
521 // they don't have a handler. Which means we can't parse the param
522 // string. However, not a big issue as what good is a param string
523 // if you have no handler to make use of the param string and
524 // actually generate the thumbnail.
525 $handler = $file->getHandler();
527 // Based on UploadStash::parseKey
528 $fileNamePos = strrpos( $thumbname, $params['f'] );
529 if ( $fileNamePos === false ) {
530 // Maybe using a short filename? (see FileRepo::nameForThumb)
531 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
534 if ( $handler && $fileNamePos !== false ) {
535 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
536 $extraParams = $handler->parseParamString( $paramString );
537 if ( $extraParams !== false ) {
538 return $params +
$extraParams;
542 // As a last ditch fallback, use the traditional common parameters
543 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
544 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
545 $params['width'] = $size;
547 $params['page'] = $pagenum;
549 return $params; // valid thumbnail URL
555 * Output a thumbnail generation error message
558 * @param string $msg HTML
561 function wfThumbError( $status, $msg ) {
562 global $wgShowHostnames;
564 header( 'Cache-Control: no-cache' );
565 header( 'Content-Type: text/html; charset=utf-8' );
566 if ( $status == 400 ) {
567 HttpStatus
::header( 400 );
568 } elseif ( $status == 404 ) {
569 HttpStatus
::header( 404 );
570 } elseif ( $status == 403 ) {
571 HttpStatus
::header( 403 );
572 header( 'Vary: Cookie' );
574 HttpStatus
::header( 500 );
576 if ( $wgShowHostnames ) {
577 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
578 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : '' );
579 $hostname = htmlspecialchars( wfHostname() );
580 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
587 <meta charset="UTF-8" />
588 <title>Error generating thumbnail</title>
591 <h1>Error generating thumbnail</h1>
600 header( 'Content-Length: ' . strlen( $content ) );