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 );
39 // Commit and close up!
40 $factory = wfGetLBFactory();
41 $factory->commitMasterChanges();
44 //--------------------------------------------------------------------------
47 * Handle a thumbnail request via thumbnail file URL
51 function wfThumbHandle404() {
52 global $wgArticlePath;
54 # Set action base paths so that WebRequest::getPathInfo()
55 # recognizes the "X" as the 'title' in ../thumb_handler.php/X urls.
56 # Note: If Custom per-extension repo paths are set, this may break.
57 $repo = RepoGroup
::singleton()->getLocalRepo();
58 $oldArticlePath = $wgArticlePath;
59 $wgArticlePath = $repo->getZoneUrl( 'thumb' ) . '/$1';
61 $matches = WebRequest
::getPathInfo();
63 $wgArticlePath = $oldArticlePath;
65 if ( !isset( $matches['title'] ) ) {
66 wfThumbError( 404, 'Could not determine the name of the requested thumbnail.' );
70 $params = wfExtractThumbRequestInfo( $matches['title'] ); // basic wiki URL param extracting
71 if ( $params == null ) {
72 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
76 wfStreamThumb( $params ); // stream the thumbnail
80 * Stream a thumbnail specified by parameters
82 * @param array $params List of thumbnailing parameters. In addition to parameters
83 * passed to the MediaHandler, this may also includes the keys:
84 * f (for filename), archived (if archived file), temp (if temp file),
85 * w (alias for width), p (alias for page), r (ignored; historical),
86 * rel404 (path for render on 404 to verify hash path correct),
87 * thumbName (thumbnail name to potentially extract more parameters from
88 * e.g. 'lossy-page1-120px-Foo.tiff' would add page, lossy and width
92 function wfStreamThumb( array $params ) {
96 $headers = array(); // HTTP headers to send
98 $fileName = isset( $params['f'] ) ?
$params['f'] : '';
100 // Backwards compatibility parameters
101 if ( isset( $params['w'] ) ) {
102 $params['width'] = $params['w'];
103 unset( $params['w'] );
105 if ( isset( $params['width'] ) && substr( $params['width'], -2 ) == 'px' ) {
106 // strip the px (pixel) suffix, if found
107 $params['width'] = substr( $params['width'], 0, -2 );
109 if ( isset( $params['p'] ) ) {
110 $params['page'] = $params['p'];
113 // Is this a thumb of an archived file?
114 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
115 unset( $params['archived'] ); // handlers don't care
117 // Is this a thumb of a temp file?
118 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
119 unset( $params['temp'] ); // handlers don't care
121 // Some basic input validation
122 $fileName = strtr( $fileName, '\\/', '__' );
124 // Actually fetch the image. Method depends on whether it is archived or not.
126 $repo = RepoGroup
::singleton()->getLocalRepo()->getTempRepo();
127 $img = new UnregisteredLocalFile( null, $repo,
128 # Temp files are hashed based on the name without the timestamp.
129 # The thumbnails will be hashed based on the entire name however.
130 # @todo fix this convention to actually be reasonable.
131 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
133 } elseif ( $isOld ) {
134 // Format is <timestamp>!<name>
135 $bits = explode( '!', $fileName, 2 );
136 if ( count( $bits ) != 2 ) {
137 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
140 $title = Title
::makeTitleSafe( NS_FILE
, $bits[1] );
142 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
145 $img = RepoGroup
::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
147 $img = wfLocalFile( $fileName );
150 // Check the source file title
152 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
156 // Check permissions if there are read restrictions
157 $varyHeader = array();
158 if ( !in_array( 'read', User
::getGroupPermissions( array( '*' ) ), true ) ) {
159 if ( !$img->getTitle() ||
!$img->getTitle()->userCan( 'read' ) ) {
160 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
161 'the source file.' );
164 $headers[] = 'Cache-Control: private';
165 $varyHeader[] = 'Cookie';
168 // Check if the file is hidden
169 if ( $img->isDeleted( File
::DELETED_FILE
) ) {
170 wfThumbError( 404, "The source file '$fileName' does not exist." );
174 // Do rendering parameters extraction from thumbnail name.
175 if ( isset( $params['thumbName'] ) ) {
176 $params = wfExtractThumbParams( $img, $params );
178 if ( $params == null ) {
179 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
183 // Check the source file storage path
184 if ( !$img->exists() ) {
185 $redirectedLocation = false;
187 // Check for file redirect
188 // Since redirects are associated with pages, not versions of files,
189 // we look for the most current version to see if its a redirect.
190 $possRedirFile = RepoGroup
::singleton()->getLocalRepo()->findFile( $img->getName() );
191 if ( $possRedirFile && !is_null( $possRedirFile->getRedirected() ) ) {
192 $redirTarget = $possRedirFile->getName();
193 $targetFile = wfLocalFile( Title
::makeTitleSafe( NS_FILE
, $redirTarget ) );
194 if ( $targetFile->exists() ) {
195 $newThumbName = $targetFile->thumbName( $params );
197 $newThumbUrl = $targetFile->getArchiveThumbUrl(
198 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
200 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
202 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT
);
207 if ( $redirectedLocation ) {
208 // File has been moved. Give redirect.
209 $response = RequestContext
::getMain()->getRequest()->response();
210 $response->header( "HTTP/1.1 302 " . HttpStatus
::getMessage( 302 ) );
211 $response->header( 'Location: ' . $redirectedLocation );
212 $response->header( 'Expires: ' .
213 gmdate( 'D, d M Y H:i:s', time() +
12 * 3600 ) . ' GMT' );
214 if ( $wgVaryOnXFP ) {
215 $varyHeader[] = 'X-Forwarded-Proto';
217 if ( count( $varyHeader ) ) {
218 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
223 // If its not a redirect that has a target as a local file, give 404.
224 wfThumbError( 404, "The source file '$fileName' does not exist." );
226 } elseif ( $img->getPath() === false ) {
227 wfThumbError( 500, "The source file '$fileName' is not locally accessible." );
231 // Check IMS against the source file
232 // This means that clients can keep a cached copy even after it has been deleted on the server
233 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
235 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
237 wfSuppressWarnings();
238 $imsUnix = strtotime( $imsString );
240 if ( wfTimestamp( TS_UNIX
, $img->getTimestamp() ) <= $imsUnix ) {
241 header( 'HTTP/1.1 304 Not Modified' );
246 $rel404 = isset( $params['rel404'] ) ?
$params['rel404'] : null;
247 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
248 unset( $params['f'] ); // We're done with 'f' parameter.
249 unset( $params['rel404'] ); // moved to $rel404
251 // Get the normalized thumbnail name from the parameters...
253 $thumbName = $img->thumbName( $params );
254 if ( !strlen( $thumbName ) ) { // invalid params?
255 throw new MediaTransformInvalidParametersException( 'Empty return from File::thumbName' );
257 $thumbName2 = $img->thumbName( $params, File
::THUMB_FULL_NAME
); // b/c; "long" style
258 } catch ( MediaTransformInvalidParametersException
$e ) {
259 wfThumbError( 400, 'The specified thumbnail parameters are not valid: ' . $e->getMessage() );
261 } catch ( MWException
$e ) {
262 wfThumbError( 500, $e->getHTML() );
266 // For 404 handled thumbnails, we only use the base name of the URI
267 // for the thumb params and the parent directory for the source file name.
268 // Check that the zone relative path matches up so squid caches won't pick
269 // up thumbs that would not be purged on source file deletion (bug 34231).
270 if ( $rel404 !== null ) { // thumbnail was handled via 404
271 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
272 // Request for the canonical thumbnail name
273 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
274 // Request for the "long" thumbnail name; redirect to canonical name
275 $response = RequestContext
::getMain()->getRequest()->response();
276 $response->header( "HTTP/1.1 301 " . HttpStatus
::getMessage( 301 ) );
277 $response->header( 'Location: ' .
278 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT
) );
279 $response->header( 'Expires: ' .
280 gmdate( 'D, d M Y H:i:s', time() +
7 * 86400 ) . ' GMT' );
281 if ( $wgVaryOnXFP ) {
282 $varyHeader[] = 'X-Forwarded-Proto';
284 if ( count( $varyHeader ) ) {
285 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
289 wfThumbError( 404, "The given path of the specified thumbnail is incorrect;
290 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
291 rawurldecode( $rel404 ) . "'." );
296 $dispositionType = isset( $params['download'] ) ?
'attachment' : 'inline';
298 // Suggest a good name for users downloading this thumbnail
299 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName, $dispositionType )}";
301 if ( count( $varyHeader ) ) {
302 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
305 // Stream the file if it exists already...
306 $thumbPath = $img->getThumbPath( $thumbName );
307 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
308 $img->getRepo()->streamFile( $thumbPath, $headers );
312 $user = RequestContext
::getMain()->getUser();
313 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
314 wfThumbError( 500, wfMessage( 'actionthrottledtext' )->parse() );
316 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
317 wfThumbError( 500, wfMessage( 'actionthrottledtext' )->parse() );
321 // Actually generate a new thumbnail
322 list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
324 // Check for thumbnail generation errors...
325 $msg = wfMessage( 'thumbnail_error' );
328 $errorMsg = $errorMsg ?
: $msg->rawParams( 'File::transform() returned false' )->escaped();
329 } elseif ( $thumb->isError() ) {
330 $errorMsg = $thumb->getHtmlMsg();
331 } elseif ( !$thumb->hasFile() ) {
332 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
333 } elseif ( $thumb->fileIsSource() ) {
335 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
339 if ( $errorMsg !== false ) {
340 wfThumbError( $errorCode, $errorMsg );
342 // Stream the file if there were no errors
343 $thumb->streamFile( $headers );
348 * Actually try to generate a new thumbnail
351 * @param array $params
352 * @param string $thumbName
353 * @param string $thumbPath
354 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
356 function wfGenerateThumbnail( File
$file, array $params, $thumbName, $thumbPath ) {
357 global $wgMemc, $wgAttemptFailureEpoch;
359 $key = wfMemcKey( 'attempt-failures', $wgAttemptFailureEpoch,
360 $file->getRepo()->getName(), $file->getSha1(), md5( $thumbName ) );
362 // Check if this file keeps failing to render
363 if ( $wgMemc->get( $key ) >= 4 ) {
364 return array( false, wfMessage( 'thumbnail_image-failure-limit', 4 ) );
368 // Record failures on PHP fatals in addition to caching exceptions
369 register_shutdown_function( function () use ( &$done, $key ) {
370 if ( !$done ) { // transform() gave a fatal
372 // Randomize TTL to reduce stampedes
373 $wgMemc->incrWithInit( $key, 3600 +
mt_rand( 0, 300 ) );
380 // guard thumbnail rendering with PoolCounter to avoid stampedes
381 // expensive files use a separate PoolCounter config so it is possible
382 // to set up a global limit on them
383 if ( $file->isExpensiveToThumbnail() ) {
384 $poolCounterType = 'FileRenderExpensive';
386 $poolCounterType = 'FileRender';
389 // Thumbnail isn't already there, so create the new thumbnail...
391 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
393 'doWork' => function () use ( $file, $params ) {
394 return $file->transform( $params, File
::RENDER_NOW
);
396 'getCachedWork' => function () use ( $file, $params, $thumbPath ) {
397 // If the worker that finished made this thumbnail then use it.
398 // Otherwise, it probably made a different thumbnail for this file.
399 return $file->getRepo()->fileExists( $thumbPath )
400 ?
$file->transform( $params, File
::RENDER_NOW
)
401 : false; // retry once more in exclusive mode
403 'fallback' => function () {
404 return wfMessage( 'generic-pool-error' )->parse();
406 'error' => function ( $status ) {
407 return $status->getHTML();
411 $result = $work->execute();
412 if ( $result instanceof MediaTransformOutput
) {
414 } elseif ( is_string( $result ) ) { // error
415 $errorHtml = $result;
417 } catch ( Exception
$e ) {
418 // Tried to select a page on a non-paged file?
421 $done = true; // no PHP fatal occured
423 if ( !$thumb ||
$thumb->isError() ) {
424 // Randomize TTL to reduce stampedes
425 $wgMemc->incrWithInit( $key, 3600 +
mt_rand( 0, 300 ) );
428 return array( $thumb, $errorHtml );
432 * Convert pathinfo type parameter, into normal request parameters
434 * So for example, if the request was redirected from
435 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
436 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
437 * This method is responsible for turning that into an array
438 * with the folowing keys:
439 * * f => the filename (Foo.png)
440 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
441 * * archived => 1 (If the request is for an archived thumb)
442 * * temp => 1 (If the file is in the "temporary" zone)
443 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
445 * Transform specific parameters are set later via wfExtractThumbParams().
447 * @param string $thumbRel Thumbnail path relative to the thumb zone
448 * @return array|null Associative params array or null
450 function wfExtractThumbRequestInfo( $thumbRel ) {
451 $repo = RepoGroup
::singleton()->getLocalRepo();
453 $hashDirReg = $subdirReg = '';
454 $hashLevels = $repo->getHashLevels();
455 for ( $i = 0; $i < $hashLevels; $i++
) {
456 $subdirReg .= '[0-9a-f]';
457 $hashDirReg .= "$subdirReg/";
460 // Check if this is a thumbnail of an original in the local file repo
461 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
462 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
463 // Check if this is a thumbnail of an temp file in the local file repo
464 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
465 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
467 return null; // not a valid looking thumbnail request
470 $params = array( 'f' => $filename, 'rel404' => $rel );
471 if ( $archOrTemp === 'archive/' ) {
472 $params['archived'] = 1;
473 } elseif ( $archOrTemp === 'temp/' ) {
477 $params['thumbName'] = $thumbname;
482 * Convert a thumbnail name (122px-foo.png) to parameters, using
485 * @param File $file File object for file in question
486 * @param array $params Array of parameters so far
487 * @return array Parameters array with more parameters
489 function wfExtractThumbParams( $file, $params ) {
490 if ( !isset( $params['thumbName'] ) ) {
491 throw new MWException( "No thumbnail name passed to wfExtractThumbParams" );
494 $thumbname = $params['thumbName'];
495 unset( $params['thumbName'] );
497 // Do the hook first for older extensions that rely on it.
498 if ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
499 // Check hooks if parameters can be extracted
500 // Hooks return false if they manage to *resolve* the parameters
501 // This hook should be considered deprecated
502 wfDeprecated( 'ExtractThumbParameters', '1.22' );
503 return $params; // valid thumbnail URL (via extension or config)
506 // FIXME: Files in the temp zone don't set a MIME type, which means
507 // they don't have a handler. Which means we can't parse the param
508 // string. However, not a big issue as what good is a param string
509 // if you have no handler to make use of the param string and
510 // actually generate the thumbnail.
511 $handler = $file->getHandler();
513 // Based on UploadStash::parseKey
514 $fileNamePos = strrpos( $thumbname, $params['f'] );
515 if ( $fileNamePos === false ) {
516 // Maybe using a short filename? (see FileRepo::nameForThumb)
517 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
520 if ( $handler && $fileNamePos !== false ) {
521 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
522 $extraParams = $handler->parseParamString( $paramString );
523 if ( $extraParams !== false ) {
524 return $params +
$extraParams;
528 // As a last ditch fallback, use the traditional common parameters
529 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
530 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
531 $params['width'] = $size;
533 $params['page'] = $pagenum;
535 return $params; // valid thumbnail URL
541 * Output a thumbnail generation error message
544 * @param string $msg HTML
547 function wfThumbError( $status, $msg ) {
548 global $wgShowHostnames;
550 header( 'Cache-Control: no-cache' );
551 header( 'Content-Type: text/html; charset=utf-8' );
552 if ( $status == 400 ) {
553 header( 'HTTP/1.1 400 Bad request' );
554 } elseif ( $status == 404 ) {
555 header( 'HTTP/1.1 404 Not found' );
556 } elseif ( $status == 403 ) {
557 header( 'HTTP/1.1 403 Forbidden' );
558 header( 'Vary: Cookie' );
560 header( 'HTTP/1.1 500 Internal server error' );
562 if ( $wgShowHostnames ) {
563 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
564 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : '' );
565 $hostname = htmlspecialchars( wfHostname() );
566 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
573 <meta charset="UTF-8" />
574 <title>Error generating thumbnail</title>
577 <h1>Error generating thumbnail</h1>