Fix MediaWiki.WhiteSpace.EmptyLinesBetweenUse.Found
[mediawiki.git] / thumb.php
blob99c9f64b0153ccc258a0a09447fb82a5665eb177
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;
31 use Wikimedia\AtEase\AtEase;
33 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
34 // T241340: thumb.php is included by thumb_handler.php which already defined
35 // MW_ENTRY_POINT to 'thumb_handler'
36 if ( !defined( 'MW_ENTRY_POINT' ) ) {
37 define( 'MW_ENTRY_POINT', 'thumb' );
39 require __DIR__ . '/includes/WebStart.php';
41 wfThumbMain();
43 function wfThumbMain() {
44 global $wgTrivialMimeDetection, $wgRequest;
46 // Don't use fancy MIME detection, just check the file extension for jpg/gif/png
47 $wgTrivialMimeDetection = true;
49 if ( defined( 'THUMB_HANDLER' ) ) {
50 // Called from thumb_handler.php via 404; extract params from the URI...
51 wfThumbHandle404();
52 } else {
53 // Called directly, use $_GET params
54 wfStreamThumb( $wgRequest->getQueryValuesOnly() );
57 $mediawiki = new MediaWiki();
58 $mediawiki->doPostOutputShutdown();
61 /**
62 * Handle a thumbnail request via thumbnail file URL
64 * @return void
66 function wfThumbHandle404() {
67 global $wgThumbPath;
69 if ( $wgThumbPath ) {
70 $relPath = WebRequest::getRequestPathSuffix( $wgThumbPath );
71 } else {
72 // Determine the request path relative to the thumbnail zone base
73 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
74 $baseUrl = $repo->getZoneUrl( 'thumb' );
75 if ( substr( $baseUrl, 0, 1 ) === '/' ) {
76 $basePath = $baseUrl;
77 } else {
78 $basePath = parse_url( $baseUrl, PHP_URL_PATH );
80 $relPath = WebRequest::getRequestPathSuffix( $basePath );
83 $params = wfExtractThumbRequestInfo( $relPath ); // basic wiki URL param extracting
84 if ( $params == null ) {
85 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
86 return;
89 wfStreamThumb( $params ); // stream the thumbnail
92 /**
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
102 * to the parameters)
103 * @return void
105 function wfStreamThumb( array $params ) {
106 global $wgVaryOnXFP;
107 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
109 $headers = []; // HTTP headers to send
111 $fileName = $params['f'] ?? '';
113 // Backwards compatibility parameters
114 if ( isset( $params['w'] ) ) {
115 $params['width'] = $params['w'];
116 unset( $params['w'] );
118 if ( isset( $params['width'] ) && substr( $params['width'], -2 ) == 'px' ) {
119 // strip the px (pixel) suffix, if found
120 $params['width'] = substr( $params['width'], 0, -2 );
122 if ( isset( $params['p'] ) ) {
123 $params['page'] = $params['p'];
126 // Is this a thumb of an archived file?
127 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
128 unset( $params['archived'] ); // handlers don't care
130 // Is this a thumb of a temp file?
131 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
132 unset( $params['temp'] ); // handlers don't care
134 // Some basic input validation
135 $fileName = strtr( $fileName, '\\/', '__' );
136 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
138 // Actually fetch the image. Method depends on whether it is archived or not.
139 if ( $isTemp ) {
140 $repo = $localRepo->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' )->parse() );
152 return;
154 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
155 if ( !$title ) {
156 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
157 return;
159 $img = $localRepo->newFromArchiveName( $title, $fileName );
160 } else {
161 $img = $localRepo->newFile( $fileName );
164 // Check the source file title
165 if ( !$img ) {
166 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
167 return;
170 // Check permissions if there are read restrictions
171 $varyHeader = [];
172 if ( !in_array( 'read', $permissionManager->getGroupPermissions( [ '*' ] ), true ) ) {
173 $user = RequestContext::getMain()->getUser();
174 $imgTitle = $img->getTitle();
176 if ( !$imgTitle || !$permissionManager->userCan( 'read', $user, $imgTitle ) ) {
177 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
178 'the source file.' );
179 return;
181 $headers[] = 'Cache-Control: private';
182 $varyHeader[] = 'Cookie';
185 // Check if the file is hidden
186 if ( $img->isDeleted( File::DELETED_FILE ) ) {
187 wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
188 return;
191 // Do rendering parameters extraction from thumbnail name.
192 if ( isset( $params['thumbName'] ) ) {
193 $params = wfExtractThumbParams( $img, $params );
195 if ( $params == null ) {
196 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
197 return;
200 // Check the source file storage path
201 if ( !$img->exists() ) {
202 $redirectedLocation = false;
203 if ( !$isTemp ) {
204 // Check for file redirect
205 // Since redirects are associated with pages, not versions of files,
206 // we look for the most current version to see if its a redirect.
207 $possRedirFile = $localRepo->findFile( $img->getName() );
208 if ( $possRedirFile && $possRedirFile->getRedirected() !== null ) {
209 $redirTarget = $possRedirFile->getName();
210 $targetFile = $localRepo->newFile( Title::makeTitleSafe( NS_FILE, $redirTarget ) );
211 if ( $targetFile->exists() ) {
212 $newThumbName = $targetFile->thumbName( $params );
213 if ( $isOld ) {
214 /** @var array $bits */
215 $newThumbUrl = $targetFile->getArchiveThumbUrl(
216 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
217 } else {
218 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
220 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT );
225 if ( $redirectedLocation ) {
226 // File has been moved. Give redirect.
227 $response = RequestContext::getMain()->getRequest()->response();
228 $response->statusHeader( 302 );
229 $response->header( 'Location: ' . $redirectedLocation );
230 $response->header( 'Expires: ' .
231 gmdate( 'D, d M Y H:i:s', time() + 12 * 3600 ) . ' GMT' );
232 if ( $wgVaryOnXFP ) {
233 $varyHeader[] = 'X-Forwarded-Proto';
235 if ( count( $varyHeader ) ) {
236 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
238 $response->header( 'Content-Length: 0' );
239 return;
242 // If its not a redirect that has a target as a local file, give 404.
243 wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
244 return;
245 } elseif ( $img->getPath() === false ) {
246 wfThumbErrorText( 400, "The source file '$fileName' is not locally accessible." );
247 return;
250 // Check IMS against the source file
251 // This means that clients can keep a cached copy even after it has been deleted on the server
252 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
253 // Fix IE brokenness
254 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
255 // Calculate time
256 AtEase::suppressWarnings();
257 $imsUnix = strtotime( $imsString );
258 AtEase::restoreWarnings();
259 if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
260 HttpStatus::header( 304 );
261 return;
265 $rel404 = $params['rel404'] ?? null;
266 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
267 unset( $params['f'] ); // We're done with 'f' parameter.
268 unset( $params['rel404'] ); // moved to $rel404
270 // Get the normalized thumbnail name from the parameters...
271 try {
272 $thumbName = $img->thumbName( $params );
273 if ( !strlen( $thumbName ) ) { // invalid params?
274 throw new MediaTransformInvalidParametersException(
275 'Empty return from File::thumbName'
278 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
279 } catch ( MediaTransformInvalidParametersException $e ) {
280 wfThumbError(
281 400,
282 'The specified thumbnail parameters are not valid: ' . $e->getMessage()
284 return;
285 } catch ( MWException $e ) {
286 wfThumbError( 500, $e->getHTML(), 'Exception caught while extracting thumb name',
287 [ 'exception' => $e ] );
288 return;
291 // For 404 handled thumbnails, we only use the base name of the URI
292 // for the thumb params and the parent directory for the source file name.
293 // Check that the zone relative path matches up so CDN caches won't pick
294 // up thumbs that would not be purged on source file deletion (T36231).
295 if ( $rel404 !== null ) { // thumbnail was handled via 404
296 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
297 // Request for the canonical thumbnail name
298 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
299 // Request for the "long" thumbnail name; redirect to canonical name
300 $response = RequestContext::getMain()->getRequest()->response();
301 $response->statusHeader( 301 );
302 $response->header( 'Location: ' .
303 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
304 $response->header( 'Expires: ' .
305 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
306 if ( $wgVaryOnXFP ) {
307 $varyHeader[] = 'X-Forwarded-Proto';
309 if ( count( $varyHeader ) ) {
310 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
312 return;
313 } else {
314 wfThumbErrorText( 404, "The given path of the specified thumbnail is incorrect;
315 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
316 rawurldecode( $rel404 ) . "'." );
317 return;
321 $dispositionType = isset( $params['download'] ) ? 'attachment' : 'inline';
323 // Suggest a good name for users downloading this thumbnail
324 $headers[] =
325 'Content-Disposition: ' . $img->getThumbDisposition( $thumbName, $dispositionType );
327 if ( count( $varyHeader ) ) {
328 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
331 // Stream the file if it exists already...
332 $thumbPath = $img->getThumbPath( $thumbName );
333 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
334 $starttime = microtime( true );
335 $status = $img->getRepo()->streamFileWithStatus( $thumbPath, $headers );
336 $streamtime = microtime( true ) - $starttime;
338 if ( $status->isOK() ) {
339 MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
340 'media.thumbnail.stream', $streamtime
342 } else {
343 wfThumbError( 500, 'Could not stream the file', null, [ 'file' => $thumbName,
344 'path' => $thumbPath, 'error' => $status->getWikiText( false, false, 'en' ) ] );
346 return;
349 $user = RequestContext::getMain()->getUser();
350 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
351 wfThumbError( 429, wfMessage( 'actionthrottledtext' )->parse() );
352 return;
353 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
354 wfThumbError( 429, wfMessage( 'actionthrottledtext' )->parse() );
355 return;
358 $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
360 if ( strlen( $thumbProxyUrl ) ) {
361 wfProxyThumbnailRequest( $img, $thumbName );
362 // No local fallback when in proxy mode
363 return;
364 } else {
365 // Generate the thumbnail locally
366 list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
369 /** @var MediaTransformOutput|MediaTransformError|bool $thumb */
371 // Check for thumbnail generation errors...
372 $msg = wfMessage( 'thumbnail_error' );
373 $errorCode = 500;
375 if ( !$thumb ) {
376 $errorMsg = $errorMsg ?: $msg->rawParams( 'File::transform() returned false' )->escaped();
377 if ( $errorMsg instanceof MessageSpecifier &&
378 $errorMsg->getKey() === 'thumbnail_image-failure-limit'
380 $errorCode = 429;
382 } elseif ( $thumb->isError() ) {
383 $errorMsg = $thumb->getHtmlMsg();
384 $errorCode = $thumb->getHttpStatusCode();
385 } elseif ( !$thumb->hasFile() ) {
386 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
387 } elseif ( $thumb->fileIsSource() ) {
388 $errorMsg = $msg
389 ->rawParams( 'Image was not scaled, is the requested width bigger than the source?' )
390 ->escaped();
391 $errorCode = 400;
394 if ( $errorMsg !== false ) {
395 wfThumbError( $errorCode, $errorMsg, null, [ 'file' => $thumbName, 'path' => $thumbPath ] );
396 } else {
397 // Stream the file if there were no errors
398 $status = $thumb->streamFileWithStatus( $headers );
399 if ( !$status->isOK() ) {
400 wfThumbError( 500, 'Could not stream the file', null, [
401 'file' => $thumbName, 'path' => $thumbPath,
402 'error' => $status->getWikiText( false, false, 'en' ) ] );
408 * Proxies thumbnail request to a service that handles thumbnailing
410 * @param File $img
411 * @param string $thumbName
413 function wfProxyThumbnailRequest( $img, $thumbName ) {
414 $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
416 // Instead of generating the thumbnail ourselves, we proxy the request to another service
417 $thumbProxiedUrl = $thumbProxyUrl . $img->getThumbRel( $thumbName );
419 $req = MWHttpRequest::factory( $thumbProxiedUrl );
420 $secret = $img->getRepo()->getThumbProxySecret();
422 // Pass a secret key shared with the proxied service if any
423 if ( strlen( $secret ) ) {
424 $req->setHeader( 'X-Swift-Secret', $secret );
427 // Send request to proxied service
428 $status = $req->execute();
430 MediaWiki\HeaderCallback::warnIfHeadersSent();
432 // Simply serve the response from the proxied service as-is
433 header( 'HTTP/1.1 ' . $req->getStatus() );
435 $headers = $req->getResponseHeaders();
437 foreach ( $headers as $key => $values ) {
438 foreach ( $values as $value ) {
439 header( $key . ': ' . $value, false );
443 echo $req->getContent();
447 * Actually try to generate a new thumbnail
449 * @param File $file
450 * @param array $params
451 * @param string $thumbName
452 * @param string $thumbPath
453 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
455 function wfGenerateThumbnail( File $file, array $params, $thumbName, $thumbPath ) {
456 global $wgAttemptFailureEpoch;
458 $cache = ObjectCache::getLocalClusterInstance();
459 $key = $cache->makeKey(
460 'attempt-failures',
461 $wgAttemptFailureEpoch,
462 $file->getRepo()->getName(),
463 $file->getSha1(),
464 md5( $thumbName )
467 // Check if this file keeps failing to render
468 if ( $cache->get( $key ) >= 4 ) {
469 return [ false, wfMessage( 'thumbnail_image-failure-limit', 4 ) ];
472 $done = false;
473 // Record failures on PHP fatals in addition to caching exceptions
474 register_shutdown_function( static function () use ( $cache, &$done, $key ) {
475 if ( !$done ) { // transform() gave a fatal
476 // Randomize TTL to reduce stampedes
477 $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
479 } );
481 $thumb = false;
482 $errorHtml = false;
484 // guard thumbnail rendering with PoolCounter to avoid stampedes
485 // expensive files use a separate PoolCounter config so it is possible
486 // to set up a global limit on them
487 if ( $file->isExpensiveToThumbnail() ) {
488 $poolCounterType = 'FileRenderExpensive';
489 } else {
490 $poolCounterType = 'FileRender';
493 // Thumbnail isn't already there, so create the new thumbnail...
494 try {
495 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
497 'doWork' => static function () use ( $file, $params ) {
498 return $file->transform( $params, File::RENDER_NOW );
500 'doCachedWork' => static function () use ( $file, $params, $thumbPath ) {
501 // If the worker that finished made this thumbnail then use it.
502 // Otherwise, it probably made a different thumbnail for this file.
503 return $file->getRepo()->fileExists( $thumbPath )
504 ? $file->transform( $params, File::RENDER_NOW )
505 : false; // retry once more in exclusive mode
507 'error' => static function ( Status $status ) {
508 return wfMessage( 'generic-pool-error' )->parse() . '<hr>' . $status->getHTML();
512 $result = $work->execute();
513 if ( $result instanceof MediaTransformOutput ) {
514 $thumb = $result;
515 } elseif ( is_string( $result ) ) { // error
516 $errorHtml = $result;
518 } catch ( Exception $e ) {
519 // Tried to select a page on a non-paged file?
522 /** @noinspection PhpUnusedLocalVariableInspection */
523 $done = true; // no PHP fatal occurred
525 if ( !$thumb || $thumb->isError() ) {
526 // Randomize TTL to reduce stampedes
527 $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
530 return [ $thumb, $errorHtml ];
534 * Convert pathinfo type parameter, into normal request parameters
536 * So for example, if the request was redirected from
537 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
538 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
539 * This method is responsible for turning that into an array
540 * with the following keys:
541 * * f => the filename (Foo.png)
542 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
543 * * archived => 1 (If the request is for an archived thumb)
544 * * temp => 1 (If the file is in the "temporary" zone)
545 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
547 * Transform specific parameters are set later via wfExtractThumbParams().
549 * @param string $thumbRel Thumbnail path relative to the thumb zone
550 * @return array|null Associative params array or null
552 function wfExtractThumbRequestInfo( $thumbRel ) {
553 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
555 $hashDirReg = $subdirReg = '';
556 $hashLevels = $repo->getHashLevels();
557 for ( $i = 0; $i < $hashLevels; $i++ ) {
558 $subdirReg .= '[0-9a-f]';
559 $hashDirReg .= "$subdirReg/";
562 // Check if this is a thumbnail of an original in the local file repo
563 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
564 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
565 // Check if this is a thumbnail of an temp file in the local file repo
566 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
567 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
568 } else {
569 return null; // not a valid looking thumbnail request
572 $params = [ 'f' => $filename, 'rel404' => $rel ];
573 if ( $archOrTemp === 'archive/' ) {
574 $params['archived'] = 1;
575 } elseif ( $archOrTemp === 'temp/' ) {
576 $params['temp'] = 1;
579 $params['thumbName'] = $thumbname;
580 return $params;
584 * Convert a thumbnail name (122px-foo.png) to parameters, using
585 * file handler.
587 * @param File $file File object for file in question
588 * @param array $params Array of parameters so far
589 * @return array|null Parameters array with more parameters, or null
591 function wfExtractThumbParams( $file, $params ) {
592 if ( !isset( $params['thumbName'] ) ) {
593 throw new InvalidArgumentException( "No thumbnail name passed to wfExtractThumbParams" );
596 $thumbname = $params['thumbName'];
597 unset( $params['thumbName'] );
599 // FIXME: Files in the temp zone don't set a MIME type, which means
600 // they don't have a handler. Which means we can't parse the param
601 // string. However, not a big issue as what good is a param string
602 // if you have no handler to make use of the param string and
603 // actually generate the thumbnail.
604 $handler = $file->getHandler();
606 // Based on UploadStash::parseKey
607 $fileNamePos = strrpos( $thumbname, $params['f'] );
608 if ( $fileNamePos === false ) {
609 // Maybe using a short filename? (see FileRepo::nameForThumb)
610 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
613 if ( $handler && $fileNamePos !== false ) {
614 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
615 $extraParams = $handler->parseParamString( $paramString );
616 if ( $extraParams !== false ) {
617 return $params + $extraParams;
621 // As a last ditch fallback, use the traditional common parameters
622 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
623 list( /* all */, /* pagefull */, $pagenum, $size ) = $matches;
624 $params['width'] = $size;
625 if ( $pagenum ) {
626 $params['page'] = $pagenum;
628 return $params; // valid thumbnail URL
630 return null;
634 * Output a thumbnail generation error message
636 * @param int $status
637 * @param string $msgText Plain text (will be html escaped)
638 * @return void
640 function wfThumbErrorText( $status, $msgText ) {
641 wfThumbError( $status, htmlspecialchars( $msgText, ENT_NOQUOTES ) );
645 * Output a thumbnail generation error message
647 * @param int $status
648 * @param string $msgHtml HTML
649 * @param string|null $msgText Short error description, for internal logging. Defaults to $msgHtml.
650 * Only used for HTTP 500 errors.
651 * @param array $context Error context, for internal logging. Only used for HTTP 500 errors.
652 * @return void
654 function wfThumbError( $status, $msgHtml, $msgText = null, $context = [] ) {
655 global $wgShowHostnames;
657 MediaWiki\HeaderCallback::warnIfHeadersSent();
659 if ( headers_sent() ) {
660 LoggerFactory::getInstance( 'thumbnail' )->error(
661 'Error after output had been started. Output may be corrupt or truncated. ' .
662 'Original error: ' . ( $msgText ?: $msgHtml ) . " (Status $status)",
663 $context
665 return;
668 header( 'Cache-Control: no-cache' );
669 header( 'Content-Type: text/html; charset=utf-8' );
670 if ( $status == 400 || $status == 404 || $status == 429 ) {
671 HttpStatus::header( $status );
672 } elseif ( $status == 403 ) {
673 HttpStatus::header( 403 );
674 header( 'Vary: Cookie' );
675 } else {
676 LoggerFactory::getInstance( 'thumbnail' )->error( $msgText ?: $msgHtml, $context );
677 HttpStatus::header( 500 );
679 if ( $wgShowHostnames ) {
680 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
681 $url = htmlspecialchars(
682 $_SERVER['REQUEST_URI'] ?? '',
683 ENT_NOQUOTES
685 $hostname = htmlspecialchars( wfHostname(), ENT_NOQUOTES );
686 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
687 } else {
688 $debug = '';
690 $content = <<<EOT
691 <!DOCTYPE html>
692 <html><head>
693 <meta charset="UTF-8" />
694 <title>Error generating thumbnail</title>
695 </head>
696 <body>
697 <h1>Error generating thumbnail</h1>
699 $msgHtml
700 </p>
701 $debug
702 </body>
703 </html>
705 EOT;
706 header( 'Content-Length: ' . strlen( $content ) );
707 echo $content;