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 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
27 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
28 require __DIR__
. '/includes/WebStart.php';
30 // Don't use fancy MIME detection, just check the file extension for jpg/gif/png
31 $wgTrivialMimeDetection = true;
33 if ( defined( 'THUMB_HANDLER' ) ) {
34 // Called from thumb_handler.php via 404; extract params from the URI...
37 // Called directly, use $_GET params
38 wfStreamThumb( $wgRequest->getQueryValues() );
41 $mediawiki = new MediaWiki();
42 $mediawiki->doPostOutputShutdown( 'fast' );
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 ) {
94 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
96 $headers = []; // HTTP headers to send
98 $fileName = $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
158 if ( !in_array( 'read', $permissionManager->getGroupPermissions( [ '*' ] ), true ) ) {
159 $user = RequestContext
::getMain()->getUser();
160 $imgTitle = $img->getTitle();
162 if ( !$imgTitle ||
!$permissionManager->userCan( 'read', $user, $imgTitle ) ) {
163 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
164 'the source file.' );
167 $headers[] = 'Cache-Control: private';
168 $varyHeader[] = 'Cookie';
171 // Check if the file is hidden
172 if ( $img->isDeleted( File
::DELETED_FILE
) ) {
173 wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
177 // Do rendering parameters extraction from thumbnail name.
178 if ( isset( $params['thumbName'] ) ) {
179 $params = wfExtractThumbParams( $img, $params );
181 if ( $params == null ) {
182 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
186 // Check the source file storage path
187 if ( !$img->exists() ) {
188 $redirectedLocation = false;
190 // Check for file redirect
191 // Since redirects are associated with pages, not versions of files,
192 // we look for the most current version to see if its a redirect.
193 $possRedirFile = RepoGroup
::singleton()->getLocalRepo()->findFile( $img->getName() );
194 if ( $possRedirFile && !is_null( $possRedirFile->getRedirected() ) ) {
195 $redirTarget = $possRedirFile->getName();
196 $targetFile = wfLocalFile( Title
::makeTitleSafe( NS_FILE
, $redirTarget ) );
197 if ( $targetFile->exists() ) {
198 $newThumbName = $targetFile->thumbName( $params );
200 /** @var array $bits */
201 $newThumbUrl = $targetFile->getArchiveThumbUrl(
202 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
204 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
206 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT
);
211 if ( $redirectedLocation ) {
212 // File has been moved. Give redirect.
213 $response = RequestContext
::getMain()->getRequest()->response();
214 $response->statusHeader( 302 );
215 $response->header( 'Location: ' . $redirectedLocation );
216 $response->header( 'Expires: ' .
217 gmdate( 'D, d M Y H:i:s', time() +
12 * 3600 ) . ' GMT' );
218 if ( $wgVaryOnXFP ) {
219 $varyHeader[] = 'X-Forwarded-Proto';
221 if ( count( $varyHeader ) ) {
222 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
224 $response->header( 'Content-Length: 0' );
228 // If its not a redirect that has a target as a local file, give 404.
229 wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
231 } elseif ( $img->getPath() === false ) {
232 wfThumbErrorText( 400, "The source file '$fileName' is not locally accessible." );
236 // Check IMS against the source file
237 // This means that clients can keep a cached copy even after it has been deleted on the server
238 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
240 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
242 Wikimedia\
suppressWarnings();
243 $imsUnix = strtotime( $imsString );
244 Wikimedia\restoreWarnings
();
245 if ( wfTimestamp( TS_UNIX
, $img->getTimestamp() ) <= $imsUnix ) {
246 HttpStatus
::header( 304 );
251 $rel404 = $params['rel404'] ??
null;
252 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
253 unset( $params['f'] ); // We're done with 'f' parameter.
254 unset( $params['rel404'] ); // moved to $rel404
256 // Get the normalized thumbnail name from the parameters...
258 $thumbName = $img->thumbName( $params );
259 if ( !strlen( $thumbName ) ) { // invalid params?
260 throw new MediaTransformInvalidParametersException(
261 'Empty return from File::thumbName'
264 $thumbName2 = $img->thumbName( $params, File
::THUMB_FULL_NAME
); // b/c; "long" style
265 } catch ( MediaTransformInvalidParametersException
$e ) {
268 'The specified thumbnail parameters are not valid: ' . $e->getMessage()
271 } catch ( MWException
$e ) {
272 wfThumbError( 500, $e->getHTML(), 'Exception caught while extracting thumb name',
273 [ 'exception' => $e ] );
277 // For 404 handled thumbnails, we only use the base name of the URI
278 // for the thumb params and the parent directory for the source file name.
279 // Check that the zone relative path matches up so CDN caches won't pick
280 // up thumbs that would not be purged on source file deletion (T36231).
281 if ( $rel404 !== null ) { // thumbnail was handled via 404
282 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
283 // Request for the canonical thumbnail name
284 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
285 // Request for the "long" thumbnail name; redirect to canonical name
286 $response = RequestContext
::getMain()->getRequest()->response();
287 $response->statusHeader( 301 );
288 $response->header( 'Location: ' .
289 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT
) );
290 $response->header( 'Expires: ' .
291 gmdate( 'D, d M Y H:i:s', time() +
7 * 86400 ) . ' GMT' );
292 if ( $wgVaryOnXFP ) {
293 $varyHeader[] = 'X-Forwarded-Proto';
295 if ( count( $varyHeader ) ) {
296 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
300 wfThumbErrorText( 404, "The given path of the specified thumbnail is incorrect;
301 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
302 rawurldecode( $rel404 ) . "'." );
307 $dispositionType = isset( $params['download'] ) ?
'attachment' : 'inline';
309 // Suggest a good name for users downloading this thumbnail
311 "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 $starttime = microtime( true );
321 $status = $img->getRepo()->streamFileWithStatus( $thumbPath, $headers );
322 $streamtime = microtime( true ) - $starttime;
324 if ( $status->isOK() ) {
325 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
326 'media.thumbnail.stream', $streamtime
329 wfThumbError( 500, 'Could not stream the file', null, [ 'file' => $thumbName,
330 'path' => $thumbPath, 'error' => $status->getWikiText( false, false, 'en' ) ] );
335 $user = RequestContext
::getMain()->getUser();
336 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
337 wfThumbError( 429, wfMessage( 'actionthrottledtext' )->parse() );
339 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
340 wfThumbError( 429, wfMessage( 'actionthrottledtext' )->parse() );
344 $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
346 if ( strlen( $thumbProxyUrl ) ) {
347 wfProxyThumbnailRequest( $img, $thumbName );
348 // No local fallback when in proxy mode
351 // Generate the thumbnail locally
352 list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
355 /** @var MediaTransformOutput|MediaTransformError|bool $thumb */
357 // Check for thumbnail generation errors...
358 $msg = wfMessage( 'thumbnail_error' );
362 $errorMsg = $errorMsg ?
: $msg->rawParams( 'File::transform() returned false' )->escaped();
363 if ( $errorMsg instanceof MessageSpecifier
&&
364 $errorMsg->getKey() === 'thumbnail_image-failure-limit'
368 } elseif ( $thumb->isError() ) {
369 $errorMsg = $thumb->getHtmlMsg();
370 $errorCode = $thumb->getHttpStatusCode();
371 } elseif ( !$thumb->hasFile() ) {
372 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
373 } elseif ( $thumb->fileIsSource() ) {
375 ->rawParams( 'Image was not scaled, is the requested width bigger than the source?' )
380 if ( $errorMsg !== false ) {
381 wfThumbError( $errorCode, $errorMsg, null, [ 'file' => $thumbName, 'path' => $thumbPath ] );
383 // Stream the file if there were no errors
384 $status = $thumb->streamFileWithStatus( $headers );
385 if ( !$status->isOK() ) {
386 wfThumbError( 500, 'Could not stream the file', null, [
387 'file' => $thumbName, 'path' => $thumbPath,
388 'error' => $status->getWikiText( false, false, 'en' ) ] );
394 * Proxies thumbnail request to a service that handles thumbnailing
397 * @param string $thumbName
399 function wfProxyThumbnailRequest( $img, $thumbName ) {
400 $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
402 // Instead of generating the thumbnail ourselves, we proxy the request to another service
403 $thumbProxiedUrl = $thumbProxyUrl . $img->getThumbRel( $thumbName );
405 $req = MWHttpRequest
::factory( $thumbProxiedUrl );
406 $secret = $img->getRepo()->getThumbProxySecret();
408 // Pass a secret key shared with the proxied service if any
409 if ( strlen( $secret ) ) {
410 $req->setHeader( 'X-Swift-Secret', $secret );
413 // Send request to proxied service
414 $status = $req->execute();
416 MediaWiki\HeaderCallback
::warnIfHeadersSent();
418 // Simply serve the response from the proxied service as-is
419 header( 'HTTP/1.1 ' . $req->getStatus() );
421 $headers = $req->getResponseHeaders();
423 foreach ( $headers as $key => $values ) {
424 foreach ( $values as $value ) {
425 header( $key . ': ' . $value, false );
429 echo $req->getContent();
433 * Actually try to generate a new thumbnail
436 * @param array $params
437 * @param string $thumbName
438 * @param string $thumbPath
439 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
441 function wfGenerateThumbnail( File
$file, array $params, $thumbName, $thumbPath ) {
442 global $wgAttemptFailureEpoch;
444 $cache = ObjectCache
::getLocalClusterInstance();
445 $key = $cache->makeKey(
447 $wgAttemptFailureEpoch,
448 $file->getRepo()->getName(),
453 // Check if this file keeps failing to render
454 if ( $cache->get( $key ) >= 4 ) {
455 return [ false, wfMessage( 'thumbnail_image-failure-limit', 4 ) ];
459 // Record failures on PHP fatals in addition to caching exceptions
460 register_shutdown_function( function () use ( $cache, &$done, $key ) {
461 if ( !$done ) { // transform() gave a fatal
462 // Randomize TTL to reduce stampedes
463 $cache->incrWithInit( $key, $cache::TTL_HOUR +
mt_rand( 0, 300 ) );
470 // guard thumbnail rendering with PoolCounter to avoid stampedes
471 // expensive files use a separate PoolCounter config so it is possible
472 // to set up a global limit on them
473 if ( $file->isExpensiveToThumbnail() ) {
474 $poolCounterType = 'FileRenderExpensive';
476 $poolCounterType = 'FileRender';
479 // Thumbnail isn't already there, so create the new thumbnail...
481 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
483 'doWork' => function () use ( $file, $params ) {
484 return $file->transform( $params, File
::RENDER_NOW
);
486 'doCachedWork' => function () use ( $file, $params, $thumbPath ) {
487 // If the worker that finished made this thumbnail then use it.
488 // Otherwise, it probably made a different thumbnail for this file.
489 return $file->getRepo()->fileExists( $thumbPath )
490 ?
$file->transform( $params, File
::RENDER_NOW
)
491 : false; // retry once more in exclusive mode
493 'error' => function ( Status
$status ) {
494 return wfMessage( 'generic-pool-error' )->parse() . '<hr>' . $status->getHTML();
498 $result = $work->execute();
499 if ( $result instanceof MediaTransformOutput
) {
501 } elseif ( is_string( $result ) ) { // error
502 $errorHtml = $result;
504 } catch ( Exception
$e ) {
505 // Tried to select a page on a non-paged file?
508 /** @noinspection PhpUnusedLocalVariableInspection */
509 $done = true; // no PHP fatal occurred
511 if ( !$thumb ||
$thumb->isError() ) {
512 // Randomize TTL to reduce stampedes
513 $cache->incrWithInit( $key, $cache::TTL_HOUR +
mt_rand( 0, 300 ) );
516 return [ $thumb, $errorHtml ];
520 * Convert pathinfo type parameter, into normal request parameters
522 * So for example, if the request was redirected from
523 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
524 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
525 * This method is responsible for turning that into an array
526 * with the folowing keys:
527 * * f => the filename (Foo.png)
528 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
529 * * archived => 1 (If the request is for an archived thumb)
530 * * temp => 1 (If the file is in the "temporary" zone)
531 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
533 * Transform specific parameters are set later via wfExtractThumbParams().
535 * @param string $thumbRel Thumbnail path relative to the thumb zone
536 * @return array|null Associative params array or null
538 function wfExtractThumbRequestInfo( $thumbRel ) {
539 $repo = RepoGroup
::singleton()->getLocalRepo();
541 $hashDirReg = $subdirReg = '';
542 $hashLevels = $repo->getHashLevels();
543 for ( $i = 0; $i < $hashLevels; $i++
) {
544 $subdirReg .= '[0-9a-f]';
545 $hashDirReg .= "$subdirReg/";
548 // Check if this is a thumbnail of an original in the local file repo
549 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
550 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
551 // Check if this is a thumbnail of an temp file in the local file repo
552 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
553 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
555 return null; // not a valid looking thumbnail request
558 $params = [ 'f' => $filename, 'rel404' => $rel ];
559 if ( $archOrTemp === 'archive/' ) {
560 $params['archived'] = 1;
561 } elseif ( $archOrTemp === 'temp/' ) {
565 $params['thumbName'] = $thumbname;
570 * Convert a thumbnail name (122px-foo.png) to parameters, using
573 * @param File $file File object for file in question
574 * @param array $params Array of parameters so far
575 * @return array Parameters array with more parameters
577 function wfExtractThumbParams( $file, $params ) {
578 if ( !isset( $params['thumbName'] ) ) {
579 throw new InvalidArgumentException( "No thumbnail name passed to wfExtractThumbParams" );
582 $thumbname = $params['thumbName'];
583 unset( $params['thumbName'] );
585 // FIXME: Files in the temp zone don't set a MIME type, which means
586 // they don't have a handler. Which means we can't parse the param
587 // string. However, not a big issue as what good is a param string
588 // if you have no handler to make use of the param string and
589 // actually generate the thumbnail.
590 $handler = $file->getHandler();
592 // Based on UploadStash::parseKey
593 $fileNamePos = strrpos( $thumbname, $params['f'] );
594 if ( $fileNamePos === false ) {
595 // Maybe using a short filename? (see FileRepo::nameForThumb)
596 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
599 if ( $handler && $fileNamePos !== false ) {
600 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
601 $extraParams = $handler->parseParamString( $paramString );
602 if ( $extraParams !== false ) {
603 return $params +
$extraParams;
607 // As a last ditch fallback, use the traditional common parameters
608 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
609 list( /* all */, /* pagefull */, $pagenum, $size ) = $matches;
610 $params['width'] = $size;
612 $params['page'] = $pagenum;
614 return $params; // valid thumbnail URL
620 * Output a thumbnail generation error message
623 * @param string $msgText Plain text (will be html escaped)
626 function wfThumbErrorText( $status, $msgText ) {
627 wfThumbError( $status, htmlspecialchars( $msgText, ENT_NOQUOTES
) );
631 * Output a thumbnail generation error message
634 * @param string $msgHtml HTML
635 * @param string|null $msgText Short error description, for internal logging. Defaults to $msgHtml.
636 * Only used for HTTP 500 errors.
637 * @param array $context Error context, for internal logging. Only used for HTTP 500 errors.
640 function wfThumbError( $status, $msgHtml, $msgText = null, $context = [] ) {
641 global $wgShowHostnames;
643 MediaWiki\HeaderCallback
::warnIfHeadersSent();
645 header( 'Cache-Control: no-cache' );
646 header( 'Content-Type: text/html; charset=utf-8' );
647 if ( $status == 400 ||
$status == 404 ||
$status == 429 ) {
648 HttpStatus
::header( $status );
649 } elseif ( $status == 403 ) {
650 HttpStatus
::header( 403 );
651 header( 'Vary: Cookie' );
653 LoggerFactory
::getInstance( 'thumb' )->error( $msgText ?
: $msgHtml, $context );
654 HttpStatus
::header( 500 );
656 if ( $wgShowHostnames ) {
657 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
658 $url = htmlspecialchars(
659 $_SERVER['REQUEST_URI'] ??
'',
662 $hostname = htmlspecialchars( wfHostname(), ENT_NOQUOTES
);
663 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
670 <meta charset="UTF-8" />
671 <title>Error generating thumbnail</title>
674 <h1>Error generating thumbnail</h1>
683 header( 'Content-Length: ' . strlen( $content ) );