Bcp47Code fixes to ParsoidParser and LanguageVariantConverterUnitTest
[mediawiki.git] / thumb.php
blobd96f522b7da5931d018e25660ff039d97f201c25
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 MediaWiki\Profiler\ProfilingContext;
32 use MediaWiki\Title\Title;
33 use Wikimedia\AtEase\AtEase;
35 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
36 // T241340: thumb.php is included by thumb_handler.php which already defined
37 // MW_ENTRY_POINT to 'thumb_handler'
38 if ( !defined( 'MW_ENTRY_POINT' ) ) {
39 define( 'MW_ENTRY_POINT', 'thumb' );
41 require __DIR__ . '/includes/WebStart.php';
43 wfThumbMain();
45 function wfThumbMain() {
46 global $wgTrivialMimeDetection, $wgRequest;
48 ProfilingContext::singleton()->init( MW_ENTRY_POINT, 'stream' );
50 // Don't use fancy MIME detection, just check the file extension for jpg/gif/png
51 $wgTrivialMimeDetection = true;
53 if ( defined( 'THUMB_HANDLER' ) ) {
54 // Called from thumb_handler.php via 404; extract params from the URI...
55 wfThumbHandle404();
56 } else {
57 // Called directly, use $_GET params
58 wfStreamThumb( $wgRequest->getQueryValuesOnly() );
61 $mediawiki = new MediaWiki();
62 $mediawiki->doPostOutputShutdown();
65 /**
66 * Handle a thumbnail request via thumbnail file URL
68 * @return void
70 function wfThumbHandle404() {
71 global $wgThumbPath;
73 if ( $wgThumbPath ) {
74 $relPath = WebRequest::getRequestPathSuffix( $wgThumbPath );
75 } else {
76 // Determine the request path relative to the thumbnail zone base
77 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
78 $baseUrl = $repo->getZoneUrl( 'thumb' );
79 if ( substr( $baseUrl, 0, 1 ) === '/' ) {
80 $basePath = $baseUrl;
81 } else {
82 $basePath = parse_url( $baseUrl, PHP_URL_PATH );
84 $relPath = WebRequest::getRequestPathSuffix( $basePath );
87 $params = wfExtractThumbRequestInfo( $relPath ); // basic wiki URL param extracting
88 if ( $params == null ) {
89 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
90 return;
93 wfStreamThumb( $params ); // stream the thumbnail
96 /**
97 * Stream a thumbnail specified by parameters
99 * @param array $params List of thumbnailing parameters. In addition to parameters
100 * passed to the MediaHandler, this may also includes the keys:
101 * f (for filename), archived (if archived file), temp (if temp file),
102 * w (alias for width), p (alias for page), r (ignored; historical),
103 * rel404 (path for render on 404 to verify hash path correct),
104 * thumbName (thumbnail name to potentially extract more parameters from
105 * e.g. 'lossy-page1-120px-Foo.tiff' would add page, lossy and width
106 * to the parameters)
107 * @return void
109 function wfStreamThumb( array $params ) {
110 global $wgVaryOnXFP;
112 $headers = []; // HTTP headers to send
114 $fileName = $params['f'] ?? '';
116 // Backwards compatibility parameters
117 if ( isset( $params['w'] ) ) {
118 $params['width'] = $params['w'];
119 unset( $params['w'] );
121 if ( isset( $params['width'] ) && substr( $params['width'], -2 ) == 'px' ) {
122 // strip the px (pixel) suffix, if found
123 $params['width'] = substr( $params['width'], 0, -2 );
125 if ( isset( $params['p'] ) ) {
126 $params['page'] = $params['p'];
129 // Is this a thumb of an archived file?
130 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
131 unset( $params['archived'] ); // handlers don't care
133 // Is this a thumb of a temp file?
134 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
135 unset( $params['temp'] ); // handlers don't care
137 $services = MediaWikiServices::getInstance();
139 // Some basic input validation
140 $fileName = strtr( $fileName, '\\/', '__' );
141 $localRepo = $services->getRepoGroup()->getLocalRepo();
143 // Actually fetch the image. Method depends on whether it is archived or not.
144 if ( $isTemp ) {
145 $repo = $localRepo->getTempRepo();
146 $img = new UnregisteredLocalFile( null, $repo,
147 # Temp files are hashed based on the name without the timestamp.
148 # The thumbnails will be hashed based on the entire name however.
149 # @todo fix this convention to actually be reasonable.
150 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
152 } elseif ( $isOld ) {
153 // Format is <timestamp>!<name>
154 $bits = explode( '!', $fileName, 2 );
155 if ( count( $bits ) != 2 ) {
156 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
157 return;
159 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
160 if ( !$title ) {
161 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
162 return;
164 $img = $localRepo->newFromArchiveName( $title, $fileName );
165 } else {
166 $img = $localRepo->newFile( $fileName );
169 // Check the source file title
170 if ( !$img ) {
171 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
172 return;
175 // Check permissions if there are read restrictions
176 $varyHeader = [];
177 if ( !$services->getGroupPermissionsLookup()->groupHasPermission( '*', 'read' ) ) {
178 $user = RequestContext::getMain()->getUser();
179 $imgTitle = $img->getTitle();
181 if ( !$imgTitle || !$services->getPermissionManager()->userCan( 'read', $user, $imgTitle ) ) {
182 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
183 'the source file.' );
184 return;
186 $headers[] = 'Cache-Control: private';
187 $varyHeader[] = 'Cookie';
190 // Check if the file is hidden
191 if ( $img->isDeleted( File::DELETED_FILE ) ) {
192 wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
193 return;
196 // Do rendering parameters extraction from thumbnail name.
197 if ( isset( $params['thumbName'] ) ) {
198 $params = wfExtractThumbParams( $img, $params );
200 if ( $params == null ) {
201 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
202 return;
205 // Check the source file storage path
206 if ( !$img->exists() ) {
207 $redirectedLocation = false;
208 if ( !$isTemp ) {
209 // Check for file redirect
210 // Since redirects are associated with pages, not versions of files,
211 // we look for the most current version to see if its a redirect.
212 $possRedirFile = $localRepo->findFile( $img->getName() );
213 if ( $possRedirFile && $possRedirFile->getRedirected() !== null ) {
214 $redirTarget = $possRedirFile->getName();
215 $targetFile = $localRepo->newFile( Title::makeTitleSafe( NS_FILE, $redirTarget ) );
216 if ( $targetFile->exists() ) {
217 $newThumbName = $targetFile->thumbName( $params );
218 if ( $isOld ) {
219 /** @var array $bits */
220 $newThumbUrl = $targetFile->getArchiveThumbUrl(
221 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
222 } else {
223 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
225 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT );
230 if ( $redirectedLocation ) {
231 // File has been moved. Give redirect.
232 $response = RequestContext::getMain()->getRequest()->response();
233 $response->statusHeader( 302 );
234 $response->header( 'Location: ' . $redirectedLocation );
235 $response->header( 'Expires: ' .
236 gmdate( 'D, d M Y H:i:s', time() + 12 * 3600 ) . ' GMT' );
237 if ( $wgVaryOnXFP ) {
238 $varyHeader[] = 'X-Forwarded-Proto';
240 if ( count( $varyHeader ) ) {
241 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
243 $response->header( 'Content-Length: 0' );
244 return;
247 // If its not a redirect that has a target as a local file, give 404.
248 wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
249 return;
250 } elseif ( $img->getPath() === false ) {
251 wfThumbErrorText( 400, "The source file '$fileName' is not locally accessible." );
252 return;
255 // Check IMS against the source file
256 // This means that clients can keep a cached copy even after it has been deleted on the server
257 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
258 // Fix IE brokenness
259 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
260 // Calculate time
261 AtEase::suppressWarnings();
262 $imsUnix = strtotime( $imsString );
263 AtEase::restoreWarnings();
264 if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
265 HttpStatus::header( 304 );
266 return;
270 $rel404 = $params['rel404'] ?? null;
271 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
272 unset( $params['f'] ); // We're done with 'f' parameter.
273 unset( $params['rel404'] ); // moved to $rel404
275 // Get the normalized thumbnail name from the parameters...
276 try {
277 $thumbName = $img->thumbName( $params );
278 if ( !strlen( $thumbName ) ) { // invalid params?
279 throw new MediaTransformInvalidParametersException(
280 'Empty return from File::thumbName'
283 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
284 } catch ( MediaTransformInvalidParametersException $e ) {
285 wfThumbError(
286 400,
287 'The specified thumbnail parameters are not valid: ' . $e->getMessage()
289 return;
290 } catch ( MWException $e ) {
291 wfThumbError( 500, $e->getHTML(), 'Exception caught while extracting thumb name',
292 [ 'exception' => $e ] );
293 return;
296 // For 404 handled thumbnails, we only use the base name of the URI
297 // for the thumb params and the parent directory for the source file name.
298 // Check that the zone relative path matches up so CDN caches won't pick
299 // up thumbs that would not be purged on source file deletion (T36231).
300 if ( $rel404 !== null ) { // thumbnail was handled via 404
301 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
302 // Request for the canonical thumbnail name
303 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
304 // Request for the "long" thumbnail name; redirect to canonical name
305 $response = RequestContext::getMain()->getRequest()->response();
306 $response->statusHeader( 301 );
307 $response->header( 'Location: ' .
308 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
309 $response->header( 'Expires: ' .
310 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
311 if ( $wgVaryOnXFP ) {
312 $varyHeader[] = 'X-Forwarded-Proto';
314 if ( count( $varyHeader ) ) {
315 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
317 return;
318 } else {
319 wfThumbErrorText( 404, "The given path of the specified thumbnail is incorrect;
320 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
321 rawurldecode( $rel404 ) . "'." );
322 return;
326 $dispositionType = isset( $params['download'] ) ? 'attachment' : 'inline';
328 // Suggest a good name for users downloading this thumbnail
329 $headers[] =
330 'Content-Disposition: ' . $img->getThumbDisposition( $thumbName, $dispositionType );
332 if ( count( $varyHeader ) ) {
333 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
336 // Stream the file if it exists already...
337 $thumbPath = $img->getThumbPath( $thumbName );
338 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
339 $starttime = microtime( true );
340 $status = $img->getRepo()->streamFileWithStatus( $thumbPath, $headers );
341 $streamtime = microtime( true ) - $starttime;
343 if ( $status->isOK() ) {
344 $services->getStatsdDataFactory()->timing(
345 'media.thumbnail.stream', $streamtime
347 } else {
348 wfThumbError( 500, 'Could not stream the file', null, [ 'file' => $thumbName,
349 'path' => $thumbPath, 'error' => $status->getWikiText( false, false, 'en' ) ] );
351 return;
354 $user = RequestContext::getMain()->getUser();
355 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
356 wfThumbError( 429, wfMessage( 'actionthrottledtext' )->parse() );
357 return;
358 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
359 wfThumbError( 429, wfMessage( 'actionthrottledtext' )->parse() );
360 return;
363 $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
365 if ( strlen( $thumbProxyUrl ) ) {
366 wfProxyThumbnailRequest( $img, $thumbName );
367 // No local fallback when in proxy mode
368 return;
369 } else {
370 // Generate the thumbnail locally
371 [ $thumb, $errorMsg ] = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
374 /** @var MediaTransformOutput|MediaTransformError|bool $thumb */
376 // Check for thumbnail generation errors...
377 $msg = wfMessage( 'thumbnail_error' );
378 $errorCode = 500;
380 if ( !$thumb ) {
381 $errorMsg = $errorMsg ?: $msg->rawParams( 'File::transform() returned false' )->escaped();
382 if ( $errorMsg instanceof MessageSpecifier &&
383 $errorMsg->getKey() === 'thumbnail_image-failure-limit'
385 $errorCode = 429;
387 } elseif ( $thumb->isError() ) {
388 $errorMsg = $thumb->getHtmlMsg();
389 $errorCode = $thumb->getHttpStatusCode();
390 } elseif ( !$thumb->hasFile() ) {
391 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
392 } elseif ( $thumb->fileIsSource() ) {
393 $errorMsg = $msg
394 ->rawParams( 'Image was not scaled, is the requested width bigger than the source?' )
395 ->escaped();
396 $errorCode = 400;
399 if ( $errorMsg !== false ) {
400 wfThumbError( $errorCode, $errorMsg, null, [ 'file' => $thumbName, 'path' => $thumbPath ] );
401 } else {
402 // Stream the file if there were no errors
403 $status = $thumb->streamFileWithStatus( $headers );
404 if ( !$status->isOK() ) {
405 wfThumbError( 500, 'Could not stream the file', null, [
406 'file' => $thumbName, 'path' => $thumbPath,
407 'error' => $status->getWikiText( false, false, 'en' ) ] );
413 * Proxies thumbnail request to a service that handles thumbnailing
415 * @param File $img
416 * @param string $thumbName
418 function wfProxyThumbnailRequest( $img, $thumbName ) {
419 $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
421 // Instead of generating the thumbnail ourselves, we proxy the request to another service
422 $thumbProxiedUrl = $thumbProxyUrl . $img->getThumbRel( $thumbName );
424 $req = MediaWikiServices::getInstance()->getHttpRequestFactory()->create( $thumbProxiedUrl );
425 $secret = $img->getRepo()->getThumbProxySecret();
427 // Pass a secret key shared with the proxied service if any
428 if ( strlen( $secret ) ) {
429 $req->setHeader( 'X-Swift-Secret', $secret );
432 // Send request to proxied service
433 $req->execute();
435 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
437 // Simply serve the response from the proxied service as-is
438 header( 'HTTP/1.1 ' . $req->getStatus() );
440 $headers = $req->getResponseHeaders();
442 foreach ( $headers as $key => $values ) {
443 foreach ( $values as $value ) {
444 header( $key . ': ' . $value, false );
448 echo $req->getContent();
452 * Actually try to generate a new thumbnail
454 * @param File $file
455 * @param array $params
456 * @param string $thumbName
457 * @param string $thumbPath
458 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
460 function wfGenerateThumbnail( File $file, array $params, $thumbName, $thumbPath ) {
461 global $wgAttemptFailureEpoch;
463 $cache = ObjectCache::getLocalClusterInstance();
464 $key = $cache->makeKey(
465 'attempt-failures',
466 $wgAttemptFailureEpoch,
467 $file->getRepo()->getName(),
468 $file->getSha1(),
469 md5( $thumbName )
472 // Check if this file keeps failing to render
473 if ( $cache->get( $key ) >= 4 ) {
474 return [ false, wfMessage( 'thumbnail_image-failure-limit', 4 ) ];
477 $done = false;
478 // Record failures on PHP fatals in addition to caching exceptions
479 register_shutdown_function( static function () use ( $cache, &$done, $key ) {
480 if ( !$done ) { // transform() gave a fatal
481 // Randomize TTL to reduce stampedes
482 $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
484 } );
486 $thumb = false;
487 $errorHtml = false;
489 // guard thumbnail rendering with PoolCounter to avoid stampedes
490 // expensive files use a separate PoolCounter config so it is possible
491 // to set up a global limit on them
492 if ( $file->isExpensiveToThumbnail() ) {
493 $poolCounterType = 'FileRenderExpensive';
494 } else {
495 $poolCounterType = 'FileRender';
498 // Thumbnail isn't already there, so create the new thumbnail...
499 try {
500 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
502 'doWork' => static function () use ( $file, $params ) {
503 return $file->transform( $params, File::RENDER_NOW );
505 'doCachedWork' => static function () use ( $file, $params, $thumbPath ) {
506 // If the worker that finished made this thumbnail then use it.
507 // Otherwise, it probably made a different thumbnail for this file.
508 return $file->getRepo()->fileExists( $thumbPath )
509 ? $file->transform( $params, File::RENDER_NOW )
510 : false; // retry once more in exclusive mode
512 'error' => static function ( Status $status ) {
513 return wfMessage( 'generic-pool-error' )->parse() . '<hr>' . $status->getHTML();
517 $result = $work->execute();
518 if ( $result instanceof MediaTransformOutput ) {
519 $thumb = $result;
520 } elseif ( is_string( $result ) ) { // error
521 $errorHtml = $result;
523 } catch ( Exception $e ) {
524 // Tried to select a page on a non-paged file?
527 /** @noinspection PhpUnusedLocalVariableInspection */
528 $done = true; // no PHP fatal occurred
530 if ( !$thumb || $thumb->isError() ) {
531 // Randomize TTL to reduce stampedes
532 $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
535 return [ $thumb, $errorHtml ];
539 * Convert pathinfo type parameter, into normal request parameters
541 * So for example, if the request was redirected from
542 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
543 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
544 * This method is responsible for turning that into an array
545 * with the following keys:
546 * * f => the filename (Foo.png)
547 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
548 * * archived => 1 (If the request is for an archived thumb)
549 * * temp => 1 (If the file is in the "temporary" zone)
550 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
552 * Transform specific parameters are set later via wfExtractThumbParams().
554 * @param string $thumbRel Thumbnail path relative to the thumb zone
555 * @return array|null Associative params array or null
557 function wfExtractThumbRequestInfo( $thumbRel ) {
558 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
560 $hashDirReg = $subdirReg = '';
561 $hashLevels = $repo->getHashLevels();
562 for ( $i = 0; $i < $hashLevels; $i++ ) {
563 $subdirReg .= '[0-9a-f]';
564 $hashDirReg .= "$subdirReg/";
567 // Check if this is a thumbnail of an original in the local file repo
568 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
569 [ /*all*/, $rel, $archOrTemp, $filename, $thumbname ] = $m;
570 // Check if this is a thumbnail of a temp file in the local file repo
571 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
572 [ /*all*/, $archOrTemp, $rel, $filename, $thumbname ] = $m;
573 } else {
574 return null; // not a valid looking thumbnail request
577 $params = [ 'f' => $filename, 'rel404' => $rel ];
578 if ( $archOrTemp === 'archive/' ) {
579 $params['archived'] = 1;
580 } elseif ( $archOrTemp === 'temp/' ) {
581 $params['temp'] = 1;
584 $params['thumbName'] = $thumbname;
585 return $params;
589 * Convert a thumbnail name (122px-foo.png) to parameters, using
590 * file handler.
592 * @param File $file File object for file in question
593 * @param array $params Array of parameters so far
594 * @return array|null Parameters array with more parameters, or null
596 function wfExtractThumbParams( $file, $params ) {
597 if ( !isset( $params['thumbName'] ) ) {
598 throw new InvalidArgumentException( "No thumbnail name passed to wfExtractThumbParams" );
601 $thumbname = $params['thumbName'];
602 unset( $params['thumbName'] );
604 // FIXME: Files in the temp zone don't set a MIME type, which means
605 // they don't have a handler. Which means we can't parse the param
606 // string. However, not a big issue as what good is a param string
607 // if you have no handler to make use of the param string and
608 // actually generate the thumbnail.
609 $handler = $file->getHandler();
611 // Based on UploadStash::parseKey
612 $fileNamePos = strrpos( $thumbname, $params['f'] );
613 if ( $fileNamePos === false ) {
614 // Maybe using a short filename? (see FileRepo::nameForThumb)
615 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
618 if ( $handler && $fileNamePos !== false ) {
619 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
620 $extraParams = $handler->parseParamString( $paramString );
621 if ( $extraParams !== false ) {
622 return $params + $extraParams;
626 // As a last ditch fallback, use the traditional common parameters
627 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
628 list( /* all */, /* pagefull */, $pagenum, $size ) = $matches;
629 $params['width'] = $size;
630 if ( $pagenum ) {
631 $params['page'] = $pagenum;
633 return $params; // valid thumbnail URL
635 return null;
639 * Output a thumbnail generation error message
641 * @param int $status
642 * @param string $msgText Plain text (will be html escaped)
643 * @return void
645 function wfThumbErrorText( $status, $msgText ) {
646 wfThumbError( $status, htmlspecialchars( $msgText, ENT_NOQUOTES ) );
650 * Output a thumbnail generation error message
652 * @param int $status
653 * @param string $msgHtml HTML
654 * @param string|null $msgText Short error description, for internal logging. Defaults to $msgHtml.
655 * Only used for HTTP 500 errors.
656 * @param array $context Error context, for internal logging. Only used for HTTP 500 errors.
657 * @return void
659 function wfThumbError( $status, $msgHtml, $msgText = null, $context = [] ) {
660 global $wgShowHostnames;
662 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
664 if ( headers_sent() ) {
665 LoggerFactory::getInstance( 'thumbnail' )->error(
666 'Error after output had been started. Output may be corrupt or truncated. ' .
667 'Original error: ' . ( $msgText ?: $msgHtml ) . " (Status $status)",
668 $context
670 return;
673 header( 'Cache-Control: no-cache' );
674 header( 'Content-Type: text/html; charset=utf-8' );
675 if ( $status == 400 || $status == 404 || $status == 429 ) {
676 HttpStatus::header( $status );
677 } elseif ( $status == 403 ) {
678 HttpStatus::header( 403 );
679 header( 'Vary: Cookie' );
680 } else {
681 LoggerFactory::getInstance( 'thumbnail' )->error( $msgText ?: $msgHtml, $context );
682 HttpStatus::header( 500 );
684 if ( $wgShowHostnames ) {
685 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
686 $url = htmlspecialchars(
687 $_SERVER['REQUEST_URI'] ?? '',
688 ENT_NOQUOTES
690 $hostname = htmlspecialchars( wfHostname(), ENT_NOQUOTES );
691 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
692 } else {
693 $debug = '';
695 $content = <<<EOT
696 <!DOCTYPE html>
697 <html><head>
698 <meta charset="UTF-8" />
699 <title>Error generating thumbnail</title>
700 </head>
701 <body>
702 <h1>Error generating thumbnail</h1>
704 $msgHtml
705 </p>
706 $debug
707 </body>
708 </html>
710 EOT;
711 header( 'Content-Length: ' . strlen( $content ) );
712 echo $content;