Revision: Remove some unnecessary temporary variables for returns
[mediawiki.git] / thumb.php
blob2264aaf67fa0a830ec9bb1ad748b80bec8218579
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 // Determine the request path relative to the thumbnail zone base
67 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
68 $baseUrl = $repo->getZoneUrl( 'thumb' );
69 if ( substr( $baseUrl, 0, 1 ) === '/' ) {
70 $basePath = $baseUrl;
71 } else {
72 $basePath = parse_url( $baseUrl, PHP_URL_PATH );
74 $relPath = WebRequest::getRequestPathSuffix( $basePath );
76 $params = wfExtractThumbRequestInfo( $relPath ); // basic wiki URL param extracting
77 if ( $params == null ) {
78 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
79 return;
82 wfStreamThumb( $params ); // stream the thumbnail
85 /**
86 * Stream a thumbnail specified by parameters
88 * @param array $params List of thumbnailing parameters. In addition to parameters
89 * passed to the MediaHandler, this may also includes the keys:
90 * f (for filename), archived (if archived file), temp (if temp file),
91 * w (alias for width), p (alias for page), r (ignored; historical),
92 * rel404 (path for render on 404 to verify hash path correct),
93 * thumbName (thumbnail name to potentially extract more parameters from
94 * e.g. 'lossy-page1-120px-Foo.tiff' would add page, lossy and width
95 * to the parameters)
96 * @return void
98 function wfStreamThumb( array $params ) {
99 global $wgVaryOnXFP;
100 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
102 $headers = []; // HTTP headers to send
104 $fileName = $params['f'] ?? '';
106 // Backwards compatibility parameters
107 if ( isset( $params['w'] ) ) {
108 $params['width'] = $params['w'];
109 unset( $params['w'] );
111 if ( isset( $params['width'] ) && substr( $params['width'], -2 ) == 'px' ) {
112 // strip the px (pixel) suffix, if found
113 $params['width'] = substr( $params['width'], 0, -2 );
115 if ( isset( $params['p'] ) ) {
116 $params['page'] = $params['p'];
119 // Is this a thumb of an archived file?
120 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
121 unset( $params['archived'] ); // handlers don't care
123 // Is this a thumb of a temp file?
124 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
125 unset( $params['temp'] ); // handlers don't care
127 // Some basic input validation
128 $fileName = strtr( $fileName, '\\/', '__' );
129 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
131 // Actually fetch the image. Method depends on whether it is archived or not.
132 if ( $isTemp ) {
133 $repo = $localRepo->getTempRepo();
134 $img = new UnregisteredLocalFile( null, $repo,
135 # Temp files are hashed based on the name without the timestamp.
136 # The thumbnails will be hashed based on the entire name however.
137 # @todo fix this convention to actually be reasonable.
138 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
140 } elseif ( $isOld ) {
141 // Format is <timestamp>!<name>
142 $bits = explode( '!', $fileName, 2 );
143 if ( count( $bits ) != 2 ) {
144 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
145 return;
147 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
148 if ( !$title ) {
149 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
150 return;
152 $img = $localRepo->newFromArchiveName( $title, $fileName );
153 } else {
154 $img = $localRepo->newFile( $fileName );
157 // Check the source file title
158 if ( !$img ) {
159 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
160 return;
163 // Check permissions if there are read restrictions
164 $varyHeader = [];
165 if ( !in_array( 'read', $permissionManager->getGroupPermissions( [ '*' ] ), true ) ) {
166 $user = RequestContext::getMain()->getUser();
167 $imgTitle = $img->getTitle();
169 if ( !$imgTitle || !$permissionManager->userCan( 'read', $user, $imgTitle ) ) {
170 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
171 'the source file.' );
172 return;
174 $headers[] = 'Cache-Control: private';
175 $varyHeader[] = 'Cookie';
178 // Check if the file is hidden
179 if ( $img->isDeleted( File::DELETED_FILE ) ) {
180 wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
181 return;
184 // Do rendering parameters extraction from thumbnail name.
185 if ( isset( $params['thumbName'] ) ) {
186 $params = wfExtractThumbParams( $img, $params );
188 if ( $params == null ) {
189 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
190 return;
193 // Check the source file storage path
194 if ( !$img->exists() ) {
195 $redirectedLocation = false;
196 if ( !$isTemp ) {
197 // Check for file redirect
198 // Since redirects are associated with pages, not versions of files,
199 // we look for the most current version to see if its a redirect.
200 $possRedirFile = $localRepo->findFile( $img->getName() );
201 if ( $possRedirFile && $possRedirFile->getRedirected() !== null ) {
202 $redirTarget = $possRedirFile->getName();
203 $targetFile = $localRepo->newFile( Title::makeTitleSafe( NS_FILE, $redirTarget ) );
204 if ( $targetFile->exists() ) {
205 $newThumbName = $targetFile->thumbName( $params );
206 if ( $isOld ) {
207 /** @var array $bits */
208 $newThumbUrl = $targetFile->getArchiveThumbUrl(
209 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
210 } else {
211 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
213 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT );
218 if ( $redirectedLocation ) {
219 // File has been moved. Give redirect.
220 $response = RequestContext::getMain()->getRequest()->response();
221 $response->statusHeader( 302 );
222 $response->header( 'Location: ' . $redirectedLocation );
223 $response->header( 'Expires: ' .
224 gmdate( 'D, d M Y H:i:s', time() + 12 * 3600 ) . ' GMT' );
225 if ( $wgVaryOnXFP ) {
226 $varyHeader[] = 'X-Forwarded-Proto';
228 if ( count( $varyHeader ) ) {
229 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
231 $response->header( 'Content-Length: 0' );
232 return;
235 // If its not a redirect that has a target as a local file, give 404.
236 wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
237 return;
238 } elseif ( $img->getPath() === false ) {
239 wfThumbErrorText( 400, "The source file '$fileName' is not locally accessible." );
240 return;
243 // Check IMS against the source file
244 // This means that clients can keep a cached copy even after it has been deleted on the server
245 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
246 // Fix IE brokenness
247 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
248 // Calculate time
249 Wikimedia\suppressWarnings();
250 $imsUnix = strtotime( $imsString );
251 Wikimedia\restoreWarnings();
252 if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
253 HttpStatus::header( 304 );
254 return;
258 $rel404 = $params['rel404'] ?? null;
259 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
260 unset( $params['f'] ); // We're done with 'f' parameter.
261 unset( $params['rel404'] ); // moved to $rel404
263 // Get the normalized thumbnail name from the parameters...
264 try {
265 $thumbName = $img->thumbName( $params );
266 if ( !strlen( $thumbName ) ) { // invalid params?
267 throw new MediaTransformInvalidParametersException(
268 'Empty return from File::thumbName'
271 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
272 } catch ( MediaTransformInvalidParametersException $e ) {
273 wfThumbError(
274 400,
275 'The specified thumbnail parameters are not valid: ' . $e->getMessage()
277 return;
278 } catch ( MWException $e ) {
279 wfThumbError( 500, $e->getHTML(), 'Exception caught while extracting thumb name',
280 [ 'exception' => $e ] );
281 return;
284 // For 404 handled thumbnails, we only use the base name of the URI
285 // for the thumb params and the parent directory for the source file name.
286 // Check that the zone relative path matches up so CDN caches won't pick
287 // up thumbs that would not be purged on source file deletion (T36231).
288 if ( $rel404 !== null ) { // thumbnail was handled via 404
289 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
290 // Request for the canonical thumbnail name
291 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
292 // Request for the "long" thumbnail name; redirect to canonical name
293 $response = RequestContext::getMain()->getRequest()->response();
294 $response->statusHeader( 301 );
295 $response->header( 'Location: ' .
296 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
297 $response->header( 'Expires: ' .
298 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
299 if ( $wgVaryOnXFP ) {
300 $varyHeader[] = 'X-Forwarded-Proto';
302 if ( count( $varyHeader ) ) {
303 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
305 return;
306 } else {
307 wfThumbErrorText( 404, "The given path of the specified thumbnail is incorrect;
308 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
309 rawurldecode( $rel404 ) . "'." );
310 return;
314 $dispositionType = isset( $params['download'] ) ? 'attachment' : 'inline';
316 // Suggest a good name for users downloading this thumbnail
317 $headers[] =
318 "Content-Disposition: {$img->getThumbDisposition( $thumbName, $dispositionType )}";
320 if ( count( $varyHeader ) ) {
321 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
324 // Stream the file if it exists already...
325 $thumbPath = $img->getThumbPath( $thumbName );
326 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
327 $starttime = microtime( true );
328 $status = $img->getRepo()->streamFileWithStatus( $thumbPath, $headers );
329 $streamtime = microtime( true ) - $starttime;
331 if ( $status->isOK() ) {
332 MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
333 'media.thumbnail.stream', $streamtime
335 } else {
336 wfThumbError( 500, 'Could not stream the file', null, [ 'file' => $thumbName,
337 'path' => $thumbPath, 'error' => $status->getWikiText( false, false, 'en' ) ] );
339 return;
342 $user = RequestContext::getMain()->getUser();
343 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
344 wfThumbError( 429, wfMessage( 'actionthrottledtext' )->parse() );
345 return;
346 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
347 wfThumbError( 429, wfMessage( 'actionthrottledtext' )->parse() );
348 return;
351 $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
353 if ( strlen( $thumbProxyUrl ) ) {
354 wfProxyThumbnailRequest( $img, $thumbName );
355 // No local fallback when in proxy mode
356 return;
357 } else {
358 // Generate the thumbnail locally
359 list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
362 /** @var MediaTransformOutput|MediaTransformError|bool $thumb */
364 // Check for thumbnail generation errors...
365 $msg = wfMessage( 'thumbnail_error' );
366 $errorCode = 500;
368 if ( !$thumb ) {
369 $errorMsg = $errorMsg ?: $msg->rawParams( 'File::transform() returned false' )->escaped();
370 if ( $errorMsg instanceof MessageSpecifier &&
371 $errorMsg->getKey() === 'thumbnail_image-failure-limit'
373 $errorCode = 429;
375 } elseif ( $thumb->isError() ) {
376 $errorMsg = $thumb->getHtmlMsg();
377 $errorCode = $thumb->getHttpStatusCode();
378 } elseif ( !$thumb->hasFile() ) {
379 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
380 } elseif ( $thumb->fileIsSource() ) {
381 $errorMsg = $msg
382 ->rawParams( 'Image was not scaled, is the requested width bigger than the source?' )
383 ->escaped();
384 $errorCode = 400;
387 if ( $errorMsg !== false ) {
388 wfThumbError( $errorCode, $errorMsg, null, [ 'file' => $thumbName, 'path' => $thumbPath ] );
389 } else {
390 // Stream the file if there were no errors
391 $status = $thumb->streamFileWithStatus( $headers );
392 if ( !$status->isOK() ) {
393 wfThumbError( 500, 'Could not stream the file', null, [
394 'file' => $thumbName, 'path' => $thumbPath,
395 'error' => $status->getWikiText( false, false, 'en' ) ] );
401 * Proxies thumbnail request to a service that handles thumbnailing
403 * @param File $img
404 * @param string $thumbName
406 function wfProxyThumbnailRequest( $img, $thumbName ) {
407 $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
409 // Instead of generating the thumbnail ourselves, we proxy the request to another service
410 $thumbProxiedUrl = $thumbProxyUrl . $img->getThumbRel( $thumbName );
412 $req = MWHttpRequest::factory( $thumbProxiedUrl );
413 $secret = $img->getRepo()->getThumbProxySecret();
415 // Pass a secret key shared with the proxied service if any
416 if ( strlen( $secret ) ) {
417 $req->setHeader( 'X-Swift-Secret', $secret );
420 // Send request to proxied service
421 $status = $req->execute();
423 MediaWiki\HeaderCallback::warnIfHeadersSent();
425 // Simply serve the response from the proxied service as-is
426 header( 'HTTP/1.1 ' . $req->getStatus() );
428 $headers = $req->getResponseHeaders();
430 foreach ( $headers as $key => $values ) {
431 foreach ( $values as $value ) {
432 header( $key . ': ' . $value, false );
436 echo $req->getContent();
440 * Actually try to generate a new thumbnail
442 * @param File $file
443 * @param array $params
444 * @param string $thumbName
445 * @param string $thumbPath
446 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
448 function wfGenerateThumbnail( File $file, array $params, $thumbName, $thumbPath ) {
449 global $wgAttemptFailureEpoch;
451 $cache = ObjectCache::getLocalClusterInstance();
452 $key = $cache->makeKey(
453 'attempt-failures',
454 $wgAttemptFailureEpoch,
455 $file->getRepo()->getName(),
456 $file->getSha1(),
457 md5( $thumbName )
460 // Check if this file keeps failing to render
461 if ( $cache->get( $key ) >= 4 ) {
462 return [ false, wfMessage( 'thumbnail_image-failure-limit', 4 ) ];
465 $done = false;
466 // Record failures on PHP fatals in addition to caching exceptions
467 register_shutdown_function( function () use ( $cache, &$done, $key ) {
468 if ( !$done ) { // transform() gave a fatal
469 // Randomize TTL to reduce stampedes
470 $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
472 } );
474 $thumb = false;
475 $errorHtml = false;
477 // guard thumbnail rendering with PoolCounter to avoid stampedes
478 // expensive files use a separate PoolCounter config so it is possible
479 // to set up a global limit on them
480 if ( $file->isExpensiveToThumbnail() ) {
481 $poolCounterType = 'FileRenderExpensive';
482 } else {
483 $poolCounterType = 'FileRender';
486 // Thumbnail isn't already there, so create the new thumbnail...
487 try {
488 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
490 'doWork' => function () use ( $file, $params ) {
491 return $file->transform( $params, File::RENDER_NOW );
493 'doCachedWork' => function () use ( $file, $params, $thumbPath ) {
494 // If the worker that finished made this thumbnail then use it.
495 // Otherwise, it probably made a different thumbnail for this file.
496 return $file->getRepo()->fileExists( $thumbPath )
497 ? $file->transform( $params, File::RENDER_NOW )
498 : false; // retry once more in exclusive mode
500 'error' => function ( Status $status ) {
501 return wfMessage( 'generic-pool-error' )->parse() . '<hr>' . $status->getHTML();
505 $result = $work->execute();
506 if ( $result instanceof MediaTransformOutput ) {
507 $thumb = $result;
508 } elseif ( is_string( $result ) ) { // error
509 $errorHtml = $result;
511 } catch ( Exception $e ) {
512 // Tried to select a page on a non-paged file?
515 /** @noinspection PhpUnusedLocalVariableInspection */
516 $done = true; // no PHP fatal occurred
518 if ( !$thumb || $thumb->isError() ) {
519 // Randomize TTL to reduce stampedes
520 $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
523 return [ $thumb, $errorHtml ];
527 * Convert pathinfo type parameter, into normal request parameters
529 * So for example, if the request was redirected from
530 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
531 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
532 * This method is responsible for turning that into an array
533 * with the following keys:
534 * * f => the filename (Foo.png)
535 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
536 * * archived => 1 (If the request is for an archived thumb)
537 * * temp => 1 (If the file is in the "temporary" zone)
538 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
540 * Transform specific parameters are set later via wfExtractThumbParams().
542 * @param string $thumbRel Thumbnail path relative to the thumb zone
543 * @return array|null Associative params array or null
545 function wfExtractThumbRequestInfo( $thumbRel ) {
546 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
548 $hashDirReg = $subdirReg = '';
549 $hashLevels = $repo->getHashLevels();
550 for ( $i = 0; $i < $hashLevels; $i++ ) {
551 $subdirReg .= '[0-9a-f]';
552 $hashDirReg .= "$subdirReg/";
555 // Check if this is a thumbnail of an original in the local file repo
556 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
557 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
558 // Check if this is a thumbnail of an temp file in the local file repo
559 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
560 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
561 } else {
562 return null; // not a valid looking thumbnail request
565 $params = [ 'f' => $filename, 'rel404' => $rel ];
566 if ( $archOrTemp === 'archive/' ) {
567 $params['archived'] = 1;
568 } elseif ( $archOrTemp === 'temp/' ) {
569 $params['temp'] = 1;
572 $params['thumbName'] = $thumbname;
573 return $params;
577 * Convert a thumbnail name (122px-foo.png) to parameters, using
578 * file handler.
580 * @param File $file File object for file in question
581 * @param array $params Array of parameters so far
582 * @return array Parameters array with more parameters
584 function wfExtractThumbParams( $file, $params ) {
585 if ( !isset( $params['thumbName'] ) ) {
586 throw new InvalidArgumentException( "No thumbnail name passed to wfExtractThumbParams" );
589 $thumbname = $params['thumbName'];
590 unset( $params['thumbName'] );
592 // FIXME: Files in the temp zone don't set a MIME type, which means
593 // they don't have a handler. Which means we can't parse the param
594 // string. However, not a big issue as what good is a param string
595 // if you have no handler to make use of the param string and
596 // actually generate the thumbnail.
597 $handler = $file->getHandler();
599 // Based on UploadStash::parseKey
600 $fileNamePos = strrpos( $thumbname, $params['f'] );
601 if ( $fileNamePos === false ) {
602 // Maybe using a short filename? (see FileRepo::nameForThumb)
603 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
606 if ( $handler && $fileNamePos !== false ) {
607 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
608 $extraParams = $handler->parseParamString( $paramString );
609 if ( $extraParams !== false ) {
610 return $params + $extraParams;
614 // As a last ditch fallback, use the traditional common parameters
615 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
616 list( /* all */, /* pagefull */, $pagenum, $size ) = $matches;
617 $params['width'] = $size;
618 if ( $pagenum ) {
619 $params['page'] = $pagenum;
621 return $params; // valid thumbnail URL
623 return null;
627 * Output a thumbnail generation error message
629 * @param int $status
630 * @param string $msgText Plain text (will be html escaped)
631 * @return void
633 function wfThumbErrorText( $status, $msgText ) {
634 wfThumbError( $status, htmlspecialchars( $msgText, ENT_NOQUOTES ) );
638 * Output a thumbnail generation error message
640 * @param int $status
641 * @param string $msgHtml HTML
642 * @param string|null $msgText Short error description, for internal logging. Defaults to $msgHtml.
643 * Only used for HTTP 500 errors.
644 * @param array $context Error context, for internal logging. Only used for HTTP 500 errors.
645 * @return void
647 function wfThumbError( $status, $msgHtml, $msgText = null, $context = [] ) {
648 global $wgShowHostnames;
650 MediaWiki\HeaderCallback::warnIfHeadersSent();
652 if ( headers_sent() ) {
653 LoggerFactory::getInstance( 'thumbnail' )->error(
654 'Error after output had been started. Output may be corrupt or truncated. ' .
655 'Original error: ' . ( $msgText ?: $msgHtml ) . " (Status $status)",
656 $context
658 return;
661 header( 'Cache-Control: no-cache' );
662 header( 'Content-Type: text/html; charset=utf-8' );
663 if ( $status == 400 || $status == 404 || $status == 429 ) {
664 HttpStatus::header( $status );
665 } elseif ( $status == 403 ) {
666 HttpStatus::header( 403 );
667 header( 'Vary: Cookie' );
668 } else {
669 LoggerFactory::getInstance( 'thumbnail' )->error( $msgText ?: $msgHtml, $context );
670 HttpStatus::header( 500 );
672 if ( $wgShowHostnames ) {
673 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
674 $url = htmlspecialchars(
675 $_SERVER['REQUEST_URI'] ?? '',
676 ENT_NOQUOTES
678 $hostname = htmlspecialchars( wfHostname(), ENT_NOQUOTES );
679 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
680 } else {
681 $debug = '';
683 $content = <<<EOT
684 <!DOCTYPE html>
685 <html><head>
686 <meta charset="UTF-8" />
687 <title>Error generating thumbnail</title>
688 </head>
689 <body>
690 <h1>Error generating thumbnail</h1>
692 $msgHtml
693 </p>
694 $debug
695 </body>
696 </html>
698 EOT;
699 header( 'Content-Length: ' . strlen( $content ) );
700 echo $content;