HISTORY: Add 1.35.5/1.36.3/1.37.1
[mediawiki.git] / thumb.php
blob11d6183d133bc8c6526766629f9945a3c8b19e25
1 <?php
2 /**
3 * The web entry point for retrieving media thumbnails, created by a MediaHandler
4 * subclass or proxy request if FileRepo::getThumbProxyUrl is configured.
6 * This script may also resize an image on-demand, if it isn't found in the
7 * configured FileBackend storage.
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
24 * @file
25 * @ingroup entrypoint
26 * @ingroup Media
29 use MediaWiki\Logger\LoggerFactory;
30 use MediaWiki\MediaWikiServices;
32 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
33 // T241340: thumb.php is included by thumb_handler.php which already defined
34 // MW_ENTRY_POINT to 'thumb_handler'
35 if ( !defined( 'MW_ENTRY_POINT' ) ) {
36 define( 'MW_ENTRY_POINT', 'thumb' );
38 require __DIR__ . '/includes/WebStart.php';
40 wfThumbMain();
42 function wfThumbMain() {
43 global $wgTrivialMimeDetection, $wgRequest;
45 // Don't use fancy MIME detection, just check the file extension for jpg/gif/png
46 $wgTrivialMimeDetection = true;
48 if ( defined( 'THUMB_HANDLER' ) ) {
49 // Called from thumb_handler.php via 404; extract params from the URI...
50 wfThumbHandle404();
51 } else {
52 // Called directly, use $_GET params
53 wfStreamThumb( $wgRequest->getQueryValuesOnly() );
56 $mediawiki = new MediaWiki();
57 $mediawiki->doPostOutputShutdown();
60 /**
61 * Handle a thumbnail request via thumbnail file URL
63 * @return void
65 function wfThumbHandle404() {
66 global $wgThumbPath;
68 if ( $wgThumbPath ) {
69 $relPath = WebRequest::getRequestPathSuffix( $wgThumbPath );
70 } else {
71 // Determine the request path relative to the thumbnail zone base
72 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
73 $baseUrl = $repo->getZoneUrl( 'thumb' );
74 if ( substr( $baseUrl, 0, 1 ) === '/' ) {
75 $basePath = $baseUrl;
76 } else {
77 $basePath = parse_url( $baseUrl, PHP_URL_PATH );
79 $relPath = WebRequest::getRequestPathSuffix( $basePath );
82 $params = wfExtractThumbRequestInfo( $relPath ); // basic wiki URL param extracting
83 if ( $params == null ) {
84 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
85 return;
88 wfStreamThumb( $params ); // stream the thumbnail
91 /**
92 * Stream a thumbnail specified by parameters
94 * @param array $params List of thumbnailing parameters. In addition to parameters
95 * passed to the MediaHandler, this may also includes the keys:
96 * f (for filename), archived (if archived file), temp (if temp file),
97 * w (alias for width), p (alias for page), r (ignored; historical),
98 * rel404 (path for render on 404 to verify hash path correct),
99 * thumbName (thumbnail name to potentially extract more parameters from
100 * e.g. 'lossy-page1-120px-Foo.tiff' would add page, lossy and width
101 * to the parameters)
102 * @return void
104 function wfStreamThumb( array $params ) {
105 global $wgVaryOnXFP;
106 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
108 $headers = []; // HTTP headers to send
110 $fileName = $params['f'] ?? '';
112 // Backwards compatibility parameters
113 if ( isset( $params['w'] ) ) {
114 $params['width'] = $params['w'];
115 unset( $params['w'] );
117 if ( isset( $params['width'] ) && substr( $params['width'], -2 ) == 'px' ) {
118 // strip the px (pixel) suffix, if found
119 $params['width'] = substr( $params['width'], 0, -2 );
121 if ( isset( $params['p'] ) ) {
122 $params['page'] = $params['p'];
125 // Is this a thumb of an archived file?
126 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
127 unset( $params['archived'] ); // handlers don't care
129 // Is this a thumb of a temp file?
130 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
131 unset( $params['temp'] ); // handlers don't care
133 // Some basic input validation
134 $fileName = strtr( $fileName, '\\/', '__' );
135 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
137 // Actually fetch the image. Method depends on whether it is archived or not.
138 if ( $isTemp ) {
139 $repo = $localRepo->getTempRepo();
140 $img = new UnregisteredLocalFile( null, $repo,
141 # Temp files are hashed based on the name without the timestamp.
142 # The thumbnails will be hashed based on the entire name however.
143 # @todo fix this convention to actually be reasonable.
144 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
146 } elseif ( $isOld ) {
147 // Format is <timestamp>!<name>
148 $bits = explode( '!', $fileName, 2 );
149 if ( count( $bits ) != 2 ) {
150 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
151 return;
153 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
154 if ( !$title ) {
155 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
156 return;
158 $img = $localRepo->newFromArchiveName( $title, $fileName );
159 } else {
160 $img = $localRepo->newFile( $fileName );
163 // Check the source file title
164 if ( !$img ) {
165 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
166 return;
169 // Check permissions if there are read restrictions
170 $varyHeader = [];
171 if ( !in_array( 'read', $permissionManager->getGroupPermissions( [ '*' ] ), true ) ) {
172 $user = RequestContext::getMain()->getUser();
173 $imgTitle = $img->getTitle();
175 if ( !$imgTitle || !$permissionManager->userCan( 'read', $user, $imgTitle ) ) {
176 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
177 'the source file.' );
178 return;
180 $headers[] = 'Cache-Control: private';
181 $varyHeader[] = 'Cookie';
184 // Check if the file is hidden
185 if ( $img->isDeleted( File::DELETED_FILE ) ) {
186 wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
187 return;
190 // Do rendering parameters extraction from thumbnail name.
191 if ( isset( $params['thumbName'] ) ) {
192 $params = wfExtractThumbParams( $img, $params );
194 if ( $params == null ) {
195 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
196 return;
199 // Check the source file storage path
200 if ( !$img->exists() ) {
201 $redirectedLocation = false;
202 if ( !$isTemp ) {
203 // Check for file redirect
204 // Since redirects are associated with pages, not versions of files,
205 // we look for the most current version to see if its a redirect.
206 $possRedirFile = $localRepo->findFile( $img->getName() );
207 if ( $possRedirFile && $possRedirFile->getRedirected() !== null ) {
208 $redirTarget = $possRedirFile->getName();
209 $targetFile = $localRepo->newFile( Title::makeTitleSafe( NS_FILE, $redirTarget ) );
210 if ( $targetFile->exists() ) {
211 $newThumbName = $targetFile->thumbName( $params );
212 if ( $isOld ) {
213 /** @var array $bits */
214 $newThumbUrl = $targetFile->getArchiveThumbUrl(
215 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
216 } else {
217 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
219 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT );
224 if ( $redirectedLocation ) {
225 // File has been moved. Give redirect.
226 $response = RequestContext::getMain()->getRequest()->response();
227 $response->statusHeader( 302 );
228 $response->header( 'Location: ' . $redirectedLocation );
229 $response->header( 'Expires: ' .
230 gmdate( 'D, d M Y H:i:s', time() + 12 * 3600 ) . ' GMT' );
231 if ( $wgVaryOnXFP ) {
232 $varyHeader[] = 'X-Forwarded-Proto';
234 if ( count( $varyHeader ) ) {
235 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
237 $response->header( 'Content-Length: 0' );
238 return;
241 // If its not a redirect that has a target as a local file, give 404.
242 wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
243 return;
244 } elseif ( $img->getPath() === false ) {
245 wfThumbErrorText( 400, "The source file '$fileName' is not locally accessible." );
246 return;
249 // Check IMS against the source file
250 // This means that clients can keep a cached copy even after it has been deleted on the server
251 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
252 // Fix IE brokenness
253 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
254 // Calculate time
255 Wikimedia\suppressWarnings();
256 $imsUnix = strtotime( $imsString );
257 Wikimedia\restoreWarnings();
258 if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
259 HttpStatus::header( 304 );
260 return;
264 $rel404 = $params['rel404'] ?? null;
265 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
266 unset( $params['f'] ); // We're done with 'f' parameter.
267 unset( $params['rel404'] ); // moved to $rel404
269 // Get the normalized thumbnail name from the parameters...
270 try {
271 $thumbName = $img->thumbName( $params );
272 if ( !strlen( $thumbName ) ) { // invalid params?
273 throw new MediaTransformInvalidParametersException(
274 'Empty return from File::thumbName'
277 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
278 } catch ( MediaTransformInvalidParametersException $e ) {
279 wfThumbError(
280 400,
281 'The specified thumbnail parameters are not valid: ' . $e->getMessage()
283 return;
284 } catch ( MWException $e ) {
285 wfThumbError( 500, $e->getHTML(), 'Exception caught while extracting thumb name',
286 [ 'exception' => $e ] );
287 return;
290 // For 404 handled thumbnails, we only use the base name of the URI
291 // for the thumb params and the parent directory for the source file name.
292 // Check that the zone relative path matches up so CDN caches won't pick
293 // up thumbs that would not be purged on source file deletion (T36231).
294 if ( $rel404 !== null ) { // thumbnail was handled via 404
295 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
296 // Request for the canonical thumbnail name
297 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
298 // Request for the "long" thumbnail name; redirect to canonical name
299 $response = RequestContext::getMain()->getRequest()->response();
300 $response->statusHeader( 301 );
301 $response->header( 'Location: ' .
302 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
303 $response->header( 'Expires: ' .
304 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
305 if ( $wgVaryOnXFP ) {
306 $varyHeader[] = 'X-Forwarded-Proto';
308 if ( count( $varyHeader ) ) {
309 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
311 return;
312 } else {
313 wfThumbErrorText( 404, "The given path of the specified thumbnail is incorrect;
314 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
315 rawurldecode( $rel404 ) . "'." );
316 return;
320 $dispositionType = isset( $params['download'] ) ? 'attachment' : 'inline';
322 // Suggest a good name for users downloading this thumbnail
323 $headers[] =
324 "Content-Disposition: {$img->getThumbDisposition( $thumbName, $dispositionType )}";
326 if ( count( $varyHeader ) ) {
327 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
330 // Stream the file if it exists already...
331 $thumbPath = $img->getThumbPath( $thumbName );
332 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
333 $starttime = microtime( true );
334 $status = $img->getRepo()->streamFileWithStatus( $thumbPath, $headers );
335 $streamtime = microtime( true ) - $starttime;
337 if ( $status->isOK() ) {
338 MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
339 'media.thumbnail.stream', $streamtime
341 } else {
342 wfThumbError( 500, 'Could not stream the file', null, [ 'file' => $thumbName,
343 'path' => $thumbPath, 'error' => $status->getWikiText( false, false, 'en' ) ] );
345 return;
348 $user = RequestContext::getMain()->getUser();
349 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
350 wfThumbError( 429, wfMessage( 'actionthrottledtext' )->parse() );
351 return;
352 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
353 wfThumbError( 429, wfMessage( 'actionthrottledtext' )->parse() );
354 return;
357 $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
359 if ( strlen( $thumbProxyUrl ) ) {
360 wfProxyThumbnailRequest( $img, $thumbName );
361 // No local fallback when in proxy mode
362 return;
363 } else {
364 // Generate the thumbnail locally
365 list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
368 /** @var MediaTransformOutput|MediaTransformError|bool $thumb */
370 // Check for thumbnail generation errors...
371 $msg = wfMessage( 'thumbnail_error' );
372 $errorCode = 500;
374 if ( !$thumb ) {
375 $errorMsg = $errorMsg ?: $msg->rawParams( 'File::transform() returned false' )->escaped();
376 if ( $errorMsg instanceof MessageSpecifier &&
377 $errorMsg->getKey() === 'thumbnail_image-failure-limit'
379 $errorCode = 429;
381 } elseif ( $thumb->isError() ) {
382 $errorMsg = $thumb->getHtmlMsg();
383 $errorCode = $thumb->getHttpStatusCode();
384 } elseif ( !$thumb->hasFile() ) {
385 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
386 } elseif ( $thumb->fileIsSource() ) {
387 $errorMsg = $msg
388 ->rawParams( 'Image was not scaled, is the requested width bigger than the source?' )
389 ->escaped();
390 $errorCode = 400;
393 if ( $errorMsg !== false ) {
394 wfThumbError( $errorCode, $errorMsg, null, [ 'file' => $thumbName, 'path' => $thumbPath ] );
395 } else {
396 // Stream the file if there were no errors
397 $status = $thumb->streamFileWithStatus( $headers );
398 if ( !$status->isOK() ) {
399 wfThumbError( 500, 'Could not stream the file', null, [
400 'file' => $thumbName, 'path' => $thumbPath,
401 'error' => $status->getWikiText( false, false, 'en' ) ] );
407 * Proxies thumbnail request to a service that handles thumbnailing
409 * @param File $img
410 * @param string $thumbName
412 function wfProxyThumbnailRequest( $img, $thumbName ) {
413 $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
415 // Instead of generating the thumbnail ourselves, we proxy the request to another service
416 $thumbProxiedUrl = $thumbProxyUrl . $img->getThumbRel( $thumbName );
418 $req = MWHttpRequest::factory( $thumbProxiedUrl );
419 $secret = $img->getRepo()->getThumbProxySecret();
421 // Pass a secret key shared with the proxied service if any
422 if ( strlen( $secret ) ) {
423 $req->setHeader( 'X-Swift-Secret', $secret );
426 // Send request to proxied service
427 $status = $req->execute();
429 MediaWiki\HeaderCallback::warnIfHeadersSent();
431 // Simply serve the response from the proxied service as-is
432 header( 'HTTP/1.1 ' . $req->getStatus() );
434 $headers = $req->getResponseHeaders();
436 foreach ( $headers as $key => $values ) {
437 foreach ( $values as $value ) {
438 header( $key . ': ' . $value, false );
442 echo $req->getContent();
446 * Actually try to generate a new thumbnail
448 * @param File $file
449 * @param array $params
450 * @param string $thumbName
451 * @param string $thumbPath
452 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
454 function wfGenerateThumbnail( File $file, array $params, $thumbName, $thumbPath ) {
455 global $wgAttemptFailureEpoch;
457 $cache = ObjectCache::getLocalClusterInstance();
458 $key = $cache->makeKey(
459 'attempt-failures',
460 $wgAttemptFailureEpoch,
461 $file->getRepo()->getName(),
462 $file->getSha1(),
463 md5( $thumbName )
466 // Check if this file keeps failing to render
467 if ( $cache->get( $key ) >= 4 ) {
468 return [ false, wfMessage( 'thumbnail_image-failure-limit', 4 ) ];
471 $done = false;
472 // Record failures on PHP fatals in addition to caching exceptions
473 register_shutdown_function( static function () use ( $cache, &$done, $key ) {
474 if ( !$done ) { // transform() gave a fatal
475 // Randomize TTL to reduce stampedes
476 $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
478 } );
480 $thumb = false;
481 $errorHtml = false;
483 // guard thumbnail rendering with PoolCounter to avoid stampedes
484 // expensive files use a separate PoolCounter config so it is possible
485 // to set up a global limit on them
486 if ( $file->isExpensiveToThumbnail() ) {
487 $poolCounterType = 'FileRenderExpensive';
488 } else {
489 $poolCounterType = 'FileRender';
492 // Thumbnail isn't already there, so create the new thumbnail...
493 try {
494 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
496 'doWork' => static function () use ( $file, $params ) {
497 return $file->transform( $params, File::RENDER_NOW );
499 'doCachedWork' => static function () use ( $file, $params, $thumbPath ) {
500 // If the worker that finished made this thumbnail then use it.
501 // Otherwise, it probably made a different thumbnail for this file.
502 return $file->getRepo()->fileExists( $thumbPath )
503 ? $file->transform( $params, File::RENDER_NOW )
504 : false; // retry once more in exclusive mode
506 'error' => static function ( Status $status ) {
507 return wfMessage( 'generic-pool-error' )->parse() . '<hr>' . $status->getHTML();
511 $result = $work->execute();
512 if ( $result instanceof MediaTransformOutput ) {
513 $thumb = $result;
514 } elseif ( is_string( $result ) ) { // error
515 $errorHtml = $result;
517 } catch ( Exception $e ) {
518 // Tried to select a page on a non-paged file?
521 /** @noinspection PhpUnusedLocalVariableInspection */
522 $done = true; // no PHP fatal occurred
524 if ( !$thumb || $thumb->isError() ) {
525 // Randomize TTL to reduce stampedes
526 $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
529 return [ $thumb, $errorHtml ];
533 * Convert pathinfo type parameter, into normal request parameters
535 * So for example, if the request was redirected from
536 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
537 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
538 * This method is responsible for turning that into an array
539 * with the following keys:
540 * * f => the filename (Foo.png)
541 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
542 * * archived => 1 (If the request is for an archived thumb)
543 * * temp => 1 (If the file is in the "temporary" zone)
544 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
546 * Transform specific parameters are set later via wfExtractThumbParams().
548 * @param string $thumbRel Thumbnail path relative to the thumb zone
549 * @return array|null Associative params array or null
551 function wfExtractThumbRequestInfo( $thumbRel ) {
552 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
554 $hashDirReg = $subdirReg = '';
555 $hashLevels = $repo->getHashLevels();
556 for ( $i = 0; $i < $hashLevels; $i++ ) {
557 $subdirReg .= '[0-9a-f]';
558 $hashDirReg .= "$subdirReg/";
561 // Check if this is a thumbnail of an original in the local file repo
562 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
563 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
564 // Check if this is a thumbnail of an temp file in the local file repo
565 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
566 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
567 } else {
568 return null; // not a valid looking thumbnail request
571 $params = [ 'f' => $filename, 'rel404' => $rel ];
572 if ( $archOrTemp === 'archive/' ) {
573 $params['archived'] = 1;
574 } elseif ( $archOrTemp === 'temp/' ) {
575 $params['temp'] = 1;
578 $params['thumbName'] = $thumbname;
579 return $params;
583 * Convert a thumbnail name (122px-foo.png) to parameters, using
584 * file handler.
586 * @param File $file File object for file in question
587 * @param array $params Array of parameters so far
588 * @return array|null Parameters array with more parameters, or null
590 function wfExtractThumbParams( $file, $params ) {
591 if ( !isset( $params['thumbName'] ) ) {
592 throw new InvalidArgumentException( "No thumbnail name passed to wfExtractThumbParams" );
595 $thumbname = $params['thumbName'];
596 unset( $params['thumbName'] );
598 // FIXME: Files in the temp zone don't set a MIME type, which means
599 // they don't have a handler. Which means we can't parse the param
600 // string. However, not a big issue as what good is a param string
601 // if you have no handler to make use of the param string and
602 // actually generate the thumbnail.
603 $handler = $file->getHandler();
605 // Based on UploadStash::parseKey
606 $fileNamePos = strrpos( $thumbname, $params['f'] );
607 if ( $fileNamePos === false ) {
608 // Maybe using a short filename? (see FileRepo::nameForThumb)
609 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
612 if ( $handler && $fileNamePos !== false ) {
613 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
614 $extraParams = $handler->parseParamString( $paramString );
615 if ( $extraParams !== false ) {
616 return $params + $extraParams;
620 // As a last ditch fallback, use the traditional common parameters
621 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
622 list( /* all */, /* pagefull */, $pagenum, $size ) = $matches;
623 $params['width'] = $size;
624 if ( $pagenum ) {
625 $params['page'] = $pagenum;
627 return $params; // valid thumbnail URL
629 return null;
633 * Output a thumbnail generation error message
635 * @param int $status
636 * @param string $msgText Plain text (will be html escaped)
637 * @return void
639 function wfThumbErrorText( $status, $msgText ) {
640 wfThumbError( $status, htmlspecialchars( $msgText, ENT_NOQUOTES ) );
644 * Output a thumbnail generation error message
646 * @param int $status
647 * @param string $msgHtml HTML
648 * @param string|null $msgText Short error description, for internal logging. Defaults to $msgHtml.
649 * Only used for HTTP 500 errors.
650 * @param array $context Error context, for internal logging. Only used for HTTP 500 errors.
651 * @return void
653 function wfThumbError( $status, $msgHtml, $msgText = null, $context = [] ) {
654 global $wgShowHostnames;
656 MediaWiki\HeaderCallback::warnIfHeadersSent();
658 if ( headers_sent() ) {
659 LoggerFactory::getInstance( 'thumbnail' )->error(
660 'Error after output had been started. Output may be corrupt or truncated. ' .
661 'Original error: ' . ( $msgText ?: $msgHtml ) . " (Status $status)",
662 $context
664 return;
667 header( 'Cache-Control: no-cache' );
668 header( 'Content-Type: text/html; charset=utf-8' );
669 if ( $status == 400 || $status == 404 || $status == 429 ) {
670 HttpStatus::header( $status );
671 } elseif ( $status == 403 ) {
672 HttpStatus::header( 403 );
673 header( 'Vary: Cookie' );
674 } else {
675 LoggerFactory::getInstance( 'thumbnail' )->error( $msgText ?: $msgHtml, $context );
676 HttpStatus::header( 500 );
678 if ( $wgShowHostnames ) {
679 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
680 $url = htmlspecialchars(
681 $_SERVER['REQUEST_URI'] ?? '',
682 ENT_NOQUOTES
684 $hostname = htmlspecialchars( wfHostname(), ENT_NOQUOTES );
685 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
686 } else {
687 $debug = '';
689 $content = <<<EOT
690 <!DOCTYPE html>
691 <html><head>
692 <meta charset="UTF-8" />
693 <title>Error generating thumbnail</title>
694 </head>
695 <body>
696 <h1>Error generating thumbnail</h1>
698 $msgHtml
699 </p>
700 $debug
701 </body>
702 </html>
704 EOT;
705 header( 'Content-Length: ' . strlen( $content ) );
706 echo $content;