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 wfThumbHandleRequest();
39 // Commit and close up!
40 $factory = wfGetLBFactory();
41 $factory->commitMasterChanges();
44 //--------------------------------------------------------------------------
47 * Handle a thumbnail request via query parameters
51 function wfThumbHandleRequest() {
52 $params = get_magic_quotes_gpc()
53 ?
array_map( 'stripslashes', $_GET )
56 wfStreamThumb( $params ); // stream the thumbnail
60 * Handle a thumbnail request via thumbnail file URL
64 function wfThumbHandle404() {
65 global $wgArticlePath;
67 # Set action base paths so that WebRequest::getPathInfo()
68 # recognizes the "X" as the 'title' in ../thumb_handler.php/X urls.
69 # Note: If Custom per-extension repo paths are set, this may break.
70 $repo = RepoGroup
::singleton()->getLocalRepo();
71 $oldArticlePath = $wgArticlePath;
72 $wgArticlePath = $repo->getZoneUrl( 'thumb' ) . '/$1';
74 $matches = WebRequest
::getPathInfo();
76 $wgArticlePath = $oldArticlePath;
78 if ( !isset( $matches['title'] ) ) {
79 wfThumbError( 404, 'Could not determine the name of the requested thumbnail.' );
83 $params = wfExtractThumbRequestInfo( $matches['title'] ); // basic wiki URL param extracting
84 if ( $params == null ) {
85 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
89 wfStreamThumb( $params ); // stream the thumbnail
93 * Stream a thumbnail specified by parameters
95 * @param array $params List of thumbnailing parameters. In addition to parameters
96 * passed to the MediaHandler, this may also includes the keys:
97 * f (for filename), archived (if archived file), temp (if temp file),
98 * w (alias for width), p (alias for page), r (ignored; historical),
99 * rel404 (path for render on 404 to verify hash path correct),
100 * thumbName (thumbnail name to potentially extract more parameters from
101 * e.g. 'lossy-page1-120px-Foo.tiff' would add page, lossy and width
105 function wfStreamThumb( array $params ) {
108 $section = new ProfileSection( __METHOD__
);
110 $headers = array(); // HTTP headers to send
112 $fileName = isset( $params['f'] ) ?
$params['f'] : '';
114 // Backwards compatibility parameters
115 if ( isset( $params['w'] ) ) {
116 $params['width'] = $params['w'];
117 unset( $params['w'] );
119 if ( isset( $params['width'] ) && substr( $params['width'], -2 ) == 'px' ) {
120 // strip the px (pixel) suffix, if found
121 $params['width'] = substr( $width, 0, strlen( $width ) - 2 );
123 if ( isset( $params['p'] ) ) {
124 $params['page'] = $params['p'];
127 // Is this a thumb of an archived file?
128 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
129 unset( $params['archived'] ); // handlers don't care
131 // Is this a thumb of a temp file?
132 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
133 unset( $params['temp'] ); // handlers don't care
135 // Some basic input validation
136 $fileName = strtr( $fileName, '\\/', '__' );
138 // Actually fetch the image. Method depends on whether it is archived or not.
140 $repo = RepoGroup
::singleton()->getLocalRepo()->getTempRepo();
141 $img = new UnregisteredLocalFile( null, $repo,
142 # Temp files are hashed based on the name without the timestamp.
143 # The thumbnails will be hashed based on the entire name however.
144 # @todo fix this convention to actually be reasonable.
145 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
147 } elseif ( $isOld ) {
148 // Format is <timestamp>!<name>
149 $bits = explode( '!', $fileName, 2 );
150 if ( count( $bits ) != 2 ) {
151 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
154 $title = Title
::makeTitleSafe( NS_FILE
, $bits[1] );
156 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
159 $img = RepoGroup
::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
161 $img = wfLocalFile( $fileName );
164 // Check the source file title
166 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
170 // Check permissions if there are read restrictions
171 $varyHeader = array();
172 if ( !in_array( 'read', User
::getGroupPermissions( array( '*' ) ), true ) ) {
173 if ( !$img->getTitle() ||
!$img->getTitle()->userCan( 'read' ) ) {
174 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
175 'the source file.' );
178 $headers[] = 'Cache-Control: private';
179 $varyHeader[] = 'Cookie';
182 // Check if the file is hidden
183 if ( $img->isDeleted( File
::DELETED_FILE
) ) {
184 wfThumbError( 404, "The source file '$fileName' does not exist." );
188 // Do rendering parameters extraction from thumbnail name.
189 if ( isset( $params['thumbName'] ) ) {
190 $params = wfExtractThumbParams( $img, $params );
192 if ( $params == null ) {
193 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
197 // Check the source file storage path
198 if ( !$img->exists() ) {
199 $redirectedLocation = false;
201 // Check for file redirect
202 // Since redirects are associated with pages, not versions of files,
203 // we look for the most current version to see if its a redirect.
204 $possRedirFile = RepoGroup
::singleton()->getLocalRepo()->findFile( $img->getName() );
205 if ( $possRedirFile && !is_null( $possRedirFile->getRedirected() ) ) {
206 $redirTarget = $possRedirFile->getName();
207 $targetFile = wfLocalFile( Title
::makeTitleSafe( NS_FILE
, $redirTarget ) );
208 if ( $targetFile->exists() ) {
209 $newThumbName = $targetFile->thumbName( $params );
211 $newThumbUrl = $targetFile->getArchiveThumbUrl(
212 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
214 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
216 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT
);
221 if ( $redirectedLocation ) {
222 // File has been moved. Give redirect.
223 $response = RequestContext
::getMain()->getRequest()->response();
224 $response->header( "HTTP/1.1 302 " . HttpStatus
::getMessage( 302 ) );
225 $response->header( 'Location: ' . $redirectedLocation );
226 $response->header( 'Expires: ' .
227 gmdate( 'D, d M Y H:i:s', time() +
12 * 3600 ) . ' GMT' );
228 if ( $wgVaryOnXFP ) {
229 $varyHeader[] = 'X-Forwarded-Proto';
231 if ( count( $varyHeader ) ) {
232 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
237 // If its not a redirect that has a target as a local file, give 404.
238 wfThumbError( 404, "The source file '$fileName' does not exist." );
240 } elseif ( $img->getPath() === false ) {
241 wfThumbError( 500, "The source file '$fileName' is not locally accessible." );
245 // Check IMS against the source file
246 // This means that clients can keep a cached copy even after it has been deleted on the server
247 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
249 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
251 wfSuppressWarnings();
252 $imsUnix = strtotime( $imsString );
254 if ( wfTimestamp( TS_UNIX
, $img->getTimestamp() ) <= $imsUnix ) {
255 header( 'HTTP/1.1 304 Not Modified' );
260 $rel404 = isset( $params['rel404'] ) ?
$params['rel404'] : null;
261 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
262 unset( $params['f'] ); // We're done with 'f' parameter.
263 unset( $params['rel404'] ); // moved to $rel404
265 // Get the normalized thumbnail name from the parameters...
267 $thumbName = $img->thumbName( $params );
268 if ( !strlen( $thumbName ) ) { // invalid params?
269 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
272 $thumbName2 = $img->thumbName( $params, File
::THUMB_FULL_NAME
); // b/c; "long" style
273 } catch ( MWException
$e ) {
274 wfThumbError( 500, $e->getHTML() );
278 // For 404 handled thumbnails, we only use the the base name of the URI
279 // for the thumb params and the parent directory for the source file name.
280 // Check that the zone relative path matches up so squid caches won't pick
281 // up thumbs that would not be purged on source file deletion (bug 34231).
282 if ( $rel404 !== null ) { // thumbnail was handled via 404
283 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
284 // Request for the canonical thumbnail name
285 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
286 // Request for the "long" thumbnail name; redirect to canonical name
287 $response = RequestContext
::getMain()->getRequest()->response();
288 $response->header( "HTTP/1.1 301 " . HttpStatus
::getMessage( 301 ) );
289 $response->header( 'Location: ' .
290 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT
) );
291 $response->header( 'Expires: ' .
292 gmdate( 'D, d M Y H:i:s', time() +
7 * 86400 ) . ' GMT' );
293 if ( $wgVaryOnXFP ) {
294 $varyHeader[] = 'X-Forwarded-Proto';
296 if ( count( $varyHeader ) ) {
297 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
301 wfThumbError( 404, "The given path of the specified thumbnail is incorrect;
302 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
303 rawurldecode( $rel404 ) . "'." );
308 $dispositionType = isset( $params['download'] ) ?
'attachment' : 'inline';
310 // Suggest a good name for users downloading this thumbnail
311 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName, $dispositionType )}";
313 if ( count( $varyHeader ) ) {
314 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
317 // Stream the file if it exists already...
318 $thumbPath = $img->getThumbPath( $thumbName );
319 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
320 $img->getRepo()->streamFile( $thumbPath, $headers );
324 $user = RequestContext
::getMain()->getUser();
325 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
326 wfThumbError( 500, wfMessage( 'actionthrottledtext' ) );
328 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
329 wfThumbError( 500, wfMessage( 'actionthrottledtext' ) );
333 // Actually generate a new thumbnail
334 list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
336 // Check for thumbnail generation errors...
337 $msg = wfMessage( 'thumbnail_error' );
339 $errorMsg = $errorMsg ?
: $msg->rawParams( 'File::transform() returned false' )->escaped();
340 } elseif ( $thumb->isError() ) {
341 $errorMsg = $thumb->getHtmlMsg();
342 } elseif ( !$thumb->hasFile() ) {
343 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
344 } elseif ( $thumb->fileIsSource() ) {
346 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
349 if ( $errorMsg !== false ) {
350 wfThumbError( 500, $errorMsg );
352 // Stream the file if there were no errors
353 $thumb->streamFile( $headers );
358 * Actually try to generate a new thumbnail
361 * @param array $params
362 * @param string $thumbName
363 * @param string $thumbPath
364 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
366 function wfGenerateThumbnail( File
$file, array $params, $thumbName, $thumbPath ) {
367 global $wgMemc, $wgAttemptFailureEpoch;
369 $key = wfMemcKey( 'attempt-failures', $wgAttemptFailureEpoch,
370 $file->getRepo()->getName(), md5( $file->getName() ), md5( $thumbName ) );
372 // Check if this file keeps failing to render
373 if ( $wgMemc->get( $key ) >= 4 ) {
374 return array( false, wfMessage( 'thumbnail_image-failure-limit', 4 ) );
378 // Record failures on PHP fatals in addition to caching exceptions
379 register_shutdown_function( function() use ( &$done, $key ) {
380 if ( !$done ) { // transform() gave a fatal
382 // Randomize TTL to reduce stampedes
383 $wgMemc->incrWithInit( $key, 3600 +
mt_rand( 0, 300 ) );
390 // Thumbnail isn't already there, so create the new thumbnail...
392 $work = new PoolCounterWorkViaCallback( 'FileRender', sha1( $file->getName() ),
394 'doWork' => function() use ( $file, $params ) {
395 return $file->transform( $params, File
::RENDER_NOW
);
397 'getCachedWork' => function() use ( $file, $params, $thumbPath ) {
398 // If the worker that finished made this thumbnail then use it.
399 // Otherwise, it probably made a different thumbnail for this file.
400 return $file->getRepo()->fileExists( $thumbPath )
401 ?
$file->transform( $params, File
::RENDER_NOW
)
402 : false; // retry once more in exclusive mode
404 'fallback' => function() {
405 return wfMessage( 'generic-pool-error' )->parse();
407 'error' => function ( $status ) {
408 return $status->getHTML();
412 $result = $work->execute();
413 if ( $result instanceof MediaTransformOutput
) {
415 } elseif ( is_string( $result ) ) { // error
416 $errorHtml = $result;
418 } catch ( Exception
$e ) {
419 // Tried to select a page on a non-paged file?
422 $done = true; // no PHP fatal occured
424 if ( !$thumb ||
$thumb->isError() ) {
425 // Randomize TTL to reduce stampedes
426 $wgMemc->incrWithInit( $key, 3600 +
mt_rand( 0, 300 ) );
429 return array( $thumb, $errorHtml );
433 * Returns true if this thumbnail is one that MediaWiki generates
434 * links to on file description pages and possibly parser output.
436 * $params is considered non-standard if they involve a non-standard
437 * width or any non-default parameters aside from width and page number.
438 * The number of possible files with standard parameters is far less than
439 * that of all combinations; rate-limiting for them can thus be more generious.
442 * @param array $params
445 function wfThumbIsStandard( File
$file, array $params ) {
446 global $wgThumbLimits, $wgImageLimits;
448 $handler = $file->getHandler();
449 if ( !$handler ||
!isset( $params['width'] ) ) {
453 $basicParams = array();
454 if ( isset( $params['page'] ) ) {
455 $basicParams['page'] = $params['page'];
458 // Check if the width matches one of $wgThumbLimits
459 if ( in_array( $params['width'], $wgThumbLimits ) ) {
460 $normalParams = $basicParams +
array( 'width' => $params['width'] );
461 // Append any default values to the map (e.g. "lossy", "lossless", ...)
462 $handler->normaliseParams( $file, $normalParams );
464 // If not, then check if the width matchs one of $wgImageLimits
466 foreach ( $wgImageLimits as $pair ) {
467 $normalParams = $basicParams +
array( 'width' => $pair[0], 'height' => $pair[1] );
468 // Decide whether the thumbnail should be scaled on width or height.
469 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
470 $handler->normaliseParams( $file, $normalParams );
471 // Check if this standard thumbnail size maps to the given width
472 if ( $normalParams['width'] == $params['width'] ) {
478 return false; // not standard for description pages
482 // Check that the given values for non-page, non-width, params are just defaults
483 foreach ( $params as $key => $value ) {
484 if ( !isset( $normalParams[$key] ) ||
$normalParams[$key] != $value ) {
493 * Convert pathinfo type parameter, into normal request parameters
495 * So for example, if the request was redirected from
496 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
497 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
498 * This method is responsible for turning that into an array
499 * with the folowing keys:
500 * * f => the filename (Foo.png)
501 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
502 * * archived => 1 (If the request is for an archived thumb)
503 * * temp => 1 (If the file is in the "temporary" zone)
504 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
506 * Transform specific parameters are set later via wfExtractThumbParams().
508 * @param string $thumbRel Thumbnail path relative to the thumb zone
509 * @return array|null Associative params array or null
511 function wfExtractThumbRequestInfo( $thumbRel ) {
512 $repo = RepoGroup
::singleton()->getLocalRepo();
514 $hashDirReg = $subdirReg = '';
515 for ( $i = 0; $i < $repo->getHashLevels(); $i++
) {
516 $subdirReg .= '[0-9a-f]';
517 $hashDirReg .= "$subdirReg/";
520 // Check if this is a thumbnail of an original in the local file repo
521 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
522 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
523 // Check if this is a thumbnail of an temp file in the local file repo
524 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
525 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
527 return null; // not a valid looking thumbnail request
530 $params = array( 'f' => $filename, 'rel404' => $rel );
531 if ( $archOrTemp === 'archive/' ) {
532 $params['archived'] = 1;
533 } elseif ( $archOrTemp === 'temp/' ) {
537 $params['thumbName'] = $thumbname;
542 * Convert a thumbnail name (122px-foo.png) to parameters, using
545 * @param File $file File object for file in question
546 * @param array $param Array of parameters so far
547 * @return array Parameters array with more parameters
549 function wfExtractThumbParams( $file, $params ) {
550 if ( !isset( $params['thumbName'] ) ) {
551 throw new MWException( "No thumbnail name passed to wfExtractThumbParams" );
554 $thumbname = $params['thumbName'];
555 unset( $params['thumbName'] );
557 // Do the hook first for older extensions that rely on it.
558 if ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
559 // Check hooks if parameters can be extracted
560 // Hooks return false if they manage to *resolve* the parameters
561 // This hook should be considered deprecated
562 wfDeprecated( 'ExtractThumbParameters', '1.22' );
563 return $params; // valid thumbnail URL (via extension or config)
566 // FIXME: Files in the temp zone don't set a mime type, which means
567 // they don't have a handler. Which means we can't parse the param
568 // string. However, not a big issue as what good is a param string
569 // if you have no handler to make use of the param string and
570 // actually generate the thumbnail.
571 $handler = $file->getHandler();
573 // Based on UploadStash::parseKey
574 $fileNamePos = strrpos( $thumbname, $params['f'] );
575 if ( $fileNamePos === false ) {
576 // Maybe using a short filename? (see FileRepo::nameForThumb)
577 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
580 if ( $handler && $fileNamePos !== false ) {
581 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
582 $extraParams = $handler->parseParamString( $paramString );
583 if ( $extraParams !== false ) {
584 return $params +
$extraParams;
588 // As a last ditch fallback, use the traditional common parameters
589 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
590 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
591 $params['width'] = $size;
593 $params['page'] = $pagenum;
595 return $params; // valid thumbnail URL
601 * Output a thumbnail generation error message
607 function wfThumbError( $status, $msg ) {
608 global $wgShowHostnames;
610 header( 'Cache-Control: no-cache' );
611 header( 'Content-Type: text/html; charset=utf-8' );
612 if ( $status == 404 ) {
613 header( 'HTTP/1.1 404 Not found' );
614 } elseif ( $status == 403 ) {
615 header( 'HTTP/1.1 403 Forbidden' );
616 header( 'Vary: Cookie' );
618 header( 'HTTP/1.1 500 Internal server error' );
620 if ( $wgShowHostnames ) {
621 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
622 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : '' );
623 $hostname = htmlspecialchars( wfHostname() );
624 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
629 <html><head><title>Error generating thumbnail</title></head>
631 <h1>Error generating thumbnail</h1>