Namespace WebInstaller classes
[mediawiki.git] / thumb.php
blobb4cb15a16d119cb2e02287aa0f2d47e70ff2c48a
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\Permissions\PermissionStatus;
32 use MediaWiki\PoolCounter\PoolCounterWorkViaCallback;
33 use MediaWiki\Profiler\ProfilingContext;
34 use MediaWiki\Request\WebRequest;
35 use MediaWiki\Status\Status;
36 use MediaWiki\Title\Title;
37 use Wikimedia\AtEase\AtEase;
39 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
40 // T241340: thumb.php is included by thumb_handler.php which already defined
41 // MW_ENTRY_POINT to 'thumb_handler'
42 if ( !defined( 'MW_ENTRY_POINT' ) ) {
43 define( 'MW_ENTRY_POINT', 'thumb' );
45 require __DIR__ . '/includes/WebStart.php';
47 wfThumbMain();
49 function wfThumbMain() {
50 global $wgTrivialMimeDetection, $wgRequest;
52 ProfilingContext::singleton()->init( MW_ENTRY_POINT, 'stream' );
54 // Don't use fancy MIME detection, just check the file extension for jpg/gif/png
55 $wgTrivialMimeDetection = true;
57 if ( defined( 'THUMB_HANDLER' ) ) {
58 // Called from thumb_handler.php via 404; extract params from the URI...
59 wfThumbHandle404();
60 } else {
61 // Called directly, use $_GET params
62 wfStreamThumb( $wgRequest->getQueryValuesOnly() );
65 $mediawiki = new MediaWiki();
66 $mediawiki->doPostOutputShutdown();
69 /**
70 * Handle a thumbnail request via thumbnail file URL
72 * @return void
74 function wfThumbHandle404() {
75 global $wgThumbPath;
77 if ( $wgThumbPath ) {
78 $relPath = WebRequest::getRequestPathSuffix( $wgThumbPath );
79 } else {
80 // Determine the request path relative to the thumbnail zone base
81 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
82 $baseUrl = $repo->getZoneUrl( 'thumb' );
83 if ( substr( $baseUrl, 0, 1 ) === '/' ) {
84 $basePath = $baseUrl;
85 } else {
86 $basePath = parse_url( $baseUrl, PHP_URL_PATH );
88 $relPath = WebRequest::getRequestPathSuffix( $basePath );
91 $params = wfExtractThumbRequestInfo( $relPath ); // basic wiki URL param extracting
92 if ( $params == null ) {
93 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
94 return;
97 wfStreamThumb( $params ); // stream the thumbnail
101 * Stream a thumbnail specified by parameters
103 * @param array $params List of thumbnailing parameters. In addition to parameters
104 * passed to the MediaHandler, this may also includes the keys:
105 * f (for filename), archived (if archived file), temp (if temp file),
106 * w (alias for width), p (alias for page), r (ignored; historical),
107 * rel404 (path for render on 404 to verify hash path correct),
108 * thumbName (thumbnail name to potentially extract more parameters from
109 * e.g. 'lossy-page1-120px-Foo.tiff' would add page, lossy and width
110 * to the parameters)
111 * @return void
113 function wfStreamThumb( array $params ) {
114 global $wgVaryOnXFP;
116 $headers = []; // HTTP headers to send
118 $fileName = $params['f'] ?? '';
120 // Backwards compatibility parameters
121 if ( isset( $params['w'] ) ) {
122 $params['width'] = $params['w'];
123 unset( $params['w'] );
125 if ( isset( $params['width'] ) && substr( $params['width'], -2 ) == 'px' ) {
126 // strip the px (pixel) suffix, if found
127 $params['width'] = substr( $params['width'], 0, -2 );
129 if ( isset( $params['p'] ) ) {
130 $params['page'] = $params['p'];
133 // Is this a thumb of an archived file?
134 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
135 unset( $params['archived'] ); // handlers don't care
137 // Is this a thumb of a temp file?
138 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
139 unset( $params['temp'] ); // handlers don't care
141 $services = MediaWikiServices::getInstance();
143 // Some basic input validation
144 $fileName = strtr( $fileName, '\\/', '__' );
145 $localRepo = $services->getRepoGroup()->getLocalRepo();
147 // Actually fetch the image. Method depends on whether it is archived or not.
148 if ( $isTemp ) {
149 $repo = $localRepo->getTempRepo();
150 $img = new UnregisteredLocalFile( null, $repo,
151 # Temp files are hashed based on the name without the timestamp.
152 # The thumbnails will be hashed based on the entire name however.
153 # @todo fix this convention to actually be reasonable.
154 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
156 } elseif ( $isOld ) {
157 // Format is <timestamp>!<name>
158 $bits = explode( '!', $fileName, 2 );
159 if ( count( $bits ) != 2 ) {
160 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
161 return;
163 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
164 if ( !$title ) {
165 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
166 return;
168 $img = $localRepo->newFromArchiveName( $title, $fileName );
169 } else {
170 $img = $localRepo->newFile( $fileName );
173 // Check the source file title
174 if ( !$img ) {
175 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
176 return;
179 // Check permissions if there are read restrictions
180 $varyHeader = [];
181 if ( !$services->getGroupPermissionsLookup()->groupHasPermission( '*', 'read' ) ) {
182 $authority = RequestContext::getMain()->getAuthority();
183 $imgTitle = $img->getTitle();
185 if ( !$imgTitle || !$authority->authorizeRead( 'read', $imgTitle ) ) {
186 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
187 'the source file.' );
188 return;
190 $headers[] = 'Cache-Control: private';
191 $varyHeader[] = 'Cookie';
194 // Check if the file is hidden
195 if ( $img->isDeleted( File::DELETED_FILE ) ) {
196 wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
197 return;
200 // Do rendering parameters extraction from thumbnail name.
201 if ( isset( $params['thumbName'] ) ) {
202 $params = wfExtractThumbParams( $img, $params );
204 if ( $params == null ) {
205 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
206 return;
209 // Check the source file storage path
210 if ( !$img->exists() ) {
211 $redirectedLocation = false;
212 if ( !$isTemp ) {
213 // Check for file redirect
214 // Since redirects are associated with pages, not versions of files,
215 // we look for the most current version to see if its a redirect.
216 $possRedirFile = $localRepo->findFile( $img->getName() );
217 if ( $possRedirFile && $possRedirFile->getRedirected() !== null ) {
218 $redirTarget = $possRedirFile->getName();
219 $targetFile = $localRepo->newFile( Title::makeTitleSafe( NS_FILE, $redirTarget ) );
220 if ( $targetFile->exists() ) {
221 $newThumbName = $targetFile->thumbName( $params );
222 if ( $isOld ) {
223 /** @var array $bits */
224 $newThumbUrl = $targetFile->getArchiveThumbUrl(
225 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
226 } else {
227 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
229 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT );
234 if ( $redirectedLocation ) {
235 // File has been moved. Give redirect.
236 $response = RequestContext::getMain()->getRequest()->response();
237 $response->statusHeader( 302 );
238 $response->header( 'Location: ' . $redirectedLocation );
239 $response->header( 'Expires: ' .
240 gmdate( 'D, d M Y H:i:s', time() + 12 * 3600 ) . ' GMT' );
241 if ( $wgVaryOnXFP ) {
242 $varyHeader[] = 'X-Forwarded-Proto';
244 if ( count( $varyHeader ) ) {
245 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
247 $response->header( 'Content-Length: 0' );
248 return;
251 // If its not a redirect that has a target as a local file, give 404.
252 wfThumbErrorText( 404, "The source file '$fileName' does not exist." );
253 return;
254 } elseif ( $img->getPath() === false ) {
255 wfThumbErrorText( 400, "The source file '$fileName' is not locally accessible." );
256 return;
259 // Check IMS against the source file
260 // This means that clients can keep a cached copy even after it has been deleted on the server
261 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
262 // Fix IE brokenness
263 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
264 // Calculate time
265 AtEase::suppressWarnings();
266 $imsUnix = strtotime( $imsString );
267 AtEase::restoreWarnings();
268 if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
269 HttpStatus::header( 304 );
270 return;
274 $rel404 = $params['rel404'] ?? null;
275 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
276 unset( $params['f'] ); // We're done with 'f' parameter.
277 unset( $params['rel404'] ); // moved to $rel404
279 // Get the normalized thumbnail name from the parameters...
280 try {
281 $thumbName = $img->thumbName( $params );
282 if ( !strlen( $thumbName ?? '' ) ) { // invalid params?
283 throw new MediaTransformInvalidParametersException(
284 'Empty return from File::thumbName'
287 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
288 } catch ( MediaTransformInvalidParametersException $e ) {
289 wfThumbError(
290 400,
291 'The specified thumbnail parameters are not valid: ' . $e->getMessage()
293 return;
294 } catch ( MWException $e ) {
295 wfThumbError( 500, $e->getHTML(), 'Exception caught while extracting thumb name',
296 [ 'exception' => $e ] );
297 return;
300 // For 404 handled thumbnails, we only use the base name of the URI
301 // for the thumb params and the parent directory for the source file name.
302 // Check that the zone relative path matches up so CDN caches won't pick
303 // up thumbs that would not be purged on source file deletion (T36231).
304 if ( $rel404 !== null ) { // thumbnail was handled via 404
305 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
306 // Request for the canonical thumbnail name
307 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
308 // Request for the "long" thumbnail name; redirect to canonical name
309 $response = RequestContext::getMain()->getRequest()->response();
310 $response->statusHeader( 301 );
311 $response->header( 'Location: ' .
312 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
313 $response->header( 'Expires: ' .
314 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
315 if ( $wgVaryOnXFP ) {
316 $varyHeader[] = 'X-Forwarded-Proto';
318 if ( count( $varyHeader ) ) {
319 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
321 return;
322 } else {
323 wfThumbErrorText( 404, "The given path of the specified thumbnail is incorrect;
324 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
325 rawurldecode( $rel404 ) . "'." );
326 return;
330 $dispositionType = isset( $params['download'] ) ? 'attachment' : 'inline';
332 // Suggest a good name for users downloading this thumbnail
333 $headers[] =
334 'Content-Disposition: ' . $img->getThumbDisposition( $thumbName, $dispositionType );
336 if ( count( $varyHeader ) ) {
337 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
340 // Stream the file if it exists already...
341 $thumbPath = $img->getThumbPath( $thumbName );
342 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
343 $starttime = microtime( true );
344 $status = $img->getRepo()->streamFileWithStatus( $thumbPath, $headers );
345 $streamtime = microtime( true ) - $starttime;
347 if ( $status->isOK() ) {
348 $services->getStatsdDataFactory()->timing(
349 'media.thumbnail.stream', $streamtime
351 } else {
352 wfThumbError( 500, 'Could not stream the file', null, [ 'file' => $thumbName,
353 'path' => $thumbPath, 'error' => $status->getWikiText( false, false, 'en' ) ] );
355 return;
358 $authority = RequestContext::getMain()->getAuthority();
359 $status = PermissionStatus::newEmpty();
360 if ( !wfThumbIsStandard( $img, $params )
361 && !$authority->authorizeAction( 'renderfile-nonstandard', $status )
363 $statusFormatter = $services->getFormatterFactory()
364 ->getStatusFormatter( RequestContext::getMain() );
366 wfThumbError( 429, $statusFormatter->getHTML( $status ) );
367 return;
368 } elseif ( !$authority->authorizeAction( 'renderfile', $status ) ) {
369 $statusFormatter = $services->getFormatterFactory()
370 ->getStatusFormatter( RequestContext::getMain() );
372 wfThumbError( 429, $statusFormatter->getHTML( $status ) );
373 return;
376 $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
378 if ( strlen( $thumbProxyUrl ?? '' ) ) {
379 wfProxyThumbnailRequest( $img, $thumbName );
380 // No local fallback when in proxy mode
381 return;
382 } else {
383 // Generate the thumbnail locally
384 [ $thumb, $errorMsg ] = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
387 /** @var MediaTransformOutput|MediaTransformError|bool $thumb */
389 // Check for thumbnail generation errors...
390 $msg = wfMessage( 'thumbnail_error' );
391 $errorCode = 500;
393 if ( !$thumb ) {
394 $errorMsg = $errorMsg ?: $msg->rawParams( 'File::transform() returned false' )->escaped();
395 if ( $errorMsg instanceof MessageSpecifier &&
396 $errorMsg->getKey() === 'thumbnail_image-failure-limit'
398 $errorCode = 429;
400 } elseif ( $thumb->isError() ) {
401 $errorMsg = $thumb->getHtmlMsg();
402 $errorCode = $thumb->getHttpStatusCode();
403 } elseif ( !$thumb->hasFile() ) {
404 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
405 } elseif ( $thumb->fileIsSource() ) {
406 $errorMsg = $msg
407 ->rawParams( 'Image was not scaled, is the requested width bigger than the source?' )
408 ->escaped();
409 $errorCode = 400;
412 if ( $errorMsg !== false ) {
413 wfThumbError( $errorCode, $errorMsg, null, [ 'file' => $thumbName, 'path' => $thumbPath ] );
414 } else {
415 // Stream the file if there were no errors
416 $status = $thumb->streamFileWithStatus( $headers );
417 if ( !$status->isOK() ) {
418 wfThumbError( 500, 'Could not stream the file', null, [
419 'file' => $thumbName, 'path' => $thumbPath,
420 'error' => $status->getWikiText( false, false, 'en' ) ] );
426 * Proxies thumbnail request to a service that handles thumbnailing
428 * @param File $img
429 * @param string $thumbName
431 function wfProxyThumbnailRequest( $img, $thumbName ) {
432 $thumbProxyUrl = $img->getRepo()->getThumbProxyUrl();
434 // Instead of generating the thumbnail ourselves, we proxy the request to another service
435 $thumbProxiedUrl = $thumbProxyUrl . $img->getThumbRel( $thumbName );
437 $req = MediaWikiServices::getInstance()->getHttpRequestFactory()->create( $thumbProxiedUrl );
438 $secret = $img->getRepo()->getThumbProxySecret();
440 // Pass a secret key shared with the proxied service if any
441 if ( strlen( $secret ?? '' ) ) {
442 $req->setHeader( 'X-Swift-Secret', $secret );
445 // Send request to proxied service
446 $req->execute();
448 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
450 // Simply serve the response from the proxied service as-is
451 header( 'HTTP/1.1 ' . $req->getStatus() );
453 $headers = $req->getResponseHeaders();
455 foreach ( $headers as $key => $values ) {
456 foreach ( $values as $value ) {
457 header( $key . ': ' . $value, false );
461 echo $req->getContent();
465 * Actually try to generate a new thumbnail
467 * @param File $file
468 * @param array $params
469 * @param string $thumbName
470 * @param string $thumbPath
471 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
473 function wfGenerateThumbnail( File $file, array $params, $thumbName, $thumbPath ) {
474 global $wgAttemptFailureEpoch;
476 $cache = ObjectCache::getLocalClusterInstance();
477 $key = $cache->makeKey(
478 'attempt-failures',
479 $wgAttemptFailureEpoch,
480 $file->getRepo()->getName(),
481 $file->getSha1(),
482 md5( $thumbName )
485 // Check if this file keeps failing to render
486 if ( $cache->get( $key ) >= 4 ) {
487 return [ false, wfMessage( 'thumbnail_image-failure-limit', 4 ) ];
490 $done = false;
491 // Record failures on PHP fatals in addition to caching exceptions
492 register_shutdown_function( static function () use ( $cache, &$done, $key ) {
493 if ( !$done ) { // transform() gave a fatal
494 // Randomize TTL to reduce stampedes
495 $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
497 } );
499 $thumb = false;
500 $errorHtml = false;
502 // guard thumbnail rendering with PoolCounter to avoid stampedes
503 // expensive files use a separate PoolCounter config so it is possible
504 // to set up a global limit on them
505 if ( $file->isExpensiveToThumbnail() ) {
506 $poolCounterType = 'FileRenderExpensive';
507 } else {
508 $poolCounterType = 'FileRender';
511 // Thumbnail isn't already there, so create the new thumbnail...
512 try {
513 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
515 'doWork' => static function () use ( $file, $params ) {
516 return $file->transform( $params, File::RENDER_NOW );
518 'doCachedWork' => static function () use ( $file, $params, $thumbPath ) {
519 // If the worker that finished made this thumbnail then use it.
520 // Otherwise, it probably made a different thumbnail for this file.
521 return $file->getRepo()->fileExists( $thumbPath )
522 ? $file->transform( $params, File::RENDER_NOW )
523 : false; // retry once more in exclusive mode
525 'error' => static function ( Status $status ) {
526 return wfMessage( 'generic-pool-error' )->parse() . '<hr>' . $status->getHTML();
530 $result = $work->execute();
531 if ( $result instanceof MediaTransformOutput ) {
532 $thumb = $result;
533 } elseif ( is_string( $result ) ) { // error
534 $errorHtml = $result;
536 } catch ( Exception $e ) {
537 // Tried to select a page on a non-paged file?
540 /** @noinspection PhpUnusedLocalVariableInspection */
541 $done = true; // no PHP fatal occurred
543 if ( !$thumb || $thumb->isError() ) {
544 // Randomize TTL to reduce stampedes
545 $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
548 return [ $thumb, $errorHtml ];
552 * Convert pathinfo type parameter, into normal request parameters
554 * So for example, if the request was redirected from
555 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
556 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
557 * This method is responsible for turning that into an array
558 * with the following keys:
559 * * f => the filename (Foo.png)
560 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
561 * * archived => 1 (If the request is for an archived thumb)
562 * * temp => 1 (If the file is in the "temporary" zone)
563 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
565 * Transform specific parameters are set later via wfExtractThumbParams().
567 * @param string $thumbRel Thumbnail path relative to the thumb zone
568 * @return array|null Associative params array or null
570 function wfExtractThumbRequestInfo( $thumbRel ) {
571 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
573 $hashDirReg = $subdirReg = '';
574 $hashLevels = $repo->getHashLevels();
575 for ( $i = 0; $i < $hashLevels; $i++ ) {
576 $subdirReg .= '[0-9a-f]';
577 $hashDirReg .= "$subdirReg/";
580 // Check if this is a thumbnail of an original in the local file repo
581 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
582 [ /*all*/, $rel, $archOrTemp, $filename, $thumbname ] = $m;
583 // Check if this is a thumbnail of a temp file in the local file repo
584 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
585 [ /*all*/, $archOrTemp, $rel, $filename, $thumbname ] = $m;
586 } else {
587 return null; // not a valid looking thumbnail request
590 $params = [ 'f' => $filename, 'rel404' => $rel ];
591 if ( $archOrTemp === 'archive/' ) {
592 $params['archived'] = 1;
593 } elseif ( $archOrTemp === 'temp/' ) {
594 $params['temp'] = 1;
597 $params['thumbName'] = $thumbname;
598 return $params;
602 * Convert a thumbnail name (122px-foo.png) to parameters, using
603 * file handler.
605 * @param File $file File object for file in question
606 * @param array $params Array of parameters so far
607 * @return array|null Parameters array with more parameters, or null
609 function wfExtractThumbParams( $file, $params ) {
610 if ( !isset( $params['thumbName'] ) ) {
611 throw new InvalidArgumentException( "No thumbnail name passed to wfExtractThumbParams" );
614 $thumbname = $params['thumbName'];
615 unset( $params['thumbName'] );
617 // FIXME: Files in the temp zone don't set a MIME type, which means
618 // they don't have a handler. Which means we can't parse the param
619 // string. However, not a big issue as what good is a param string
620 // if you have no handler to make use of the param string and
621 // actually generate the thumbnail.
622 $handler = $file->getHandler();
624 // Based on UploadStash::parseKey
625 $fileNamePos = strrpos( $thumbname, $params['f'] );
626 if ( $fileNamePos === false ) {
627 // Maybe using a short filename? (see FileRepo::nameForThumb)
628 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
631 if ( $handler && $fileNamePos !== false ) {
632 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
633 $extraParams = $handler->parseParamString( $paramString );
634 if ( $extraParams !== false ) {
635 return $params + $extraParams;
639 // As a last ditch fallback, use the traditional common parameters
640 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
641 [ /* all */, /* pagefull */, $pagenum, $size ] = $matches;
642 $params['width'] = $size;
643 if ( $pagenum ) {
644 $params['page'] = $pagenum;
646 return $params; // valid thumbnail URL
648 return null;
652 * Output a thumbnail generation error message
654 * @param int $status
655 * @param string $msgText Plain text (will be html escaped)
656 * @return void
658 function wfThumbErrorText( $status, $msgText ) {
659 wfThumbError( $status, htmlspecialchars( $msgText, ENT_NOQUOTES ) );
663 * Output a thumbnail generation error message
665 * @param int $status
666 * @param string $msgHtml HTML
667 * @param string|null $msgText Short error description, for internal logging. Defaults to $msgHtml.
668 * Only used for HTTP 500 errors.
669 * @param array $context Error context, for internal logging. Only used for HTTP 500 errors.
670 * @return void
672 function wfThumbError( $status, $msgHtml, $msgText = null, $context = [] ) {
673 global $wgShowHostnames;
675 \MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
677 if ( headers_sent() ) {
678 LoggerFactory::getInstance( 'thumbnail' )->error(
679 'Error after output had been started. Output may be corrupt or truncated. ' .
680 'Original error: ' . ( $msgText ?: $msgHtml ) . " (Status $status)",
681 $context
683 return;
686 header( 'Cache-Control: no-cache' );
687 header( 'Content-Type: text/html; charset=utf-8' );
688 if ( $status == 400 || $status == 404 || $status == 429 ) {
689 HttpStatus::header( $status );
690 } elseif ( $status == 403 ) {
691 HttpStatus::header( 403 );
692 header( 'Vary: Cookie' );
693 } else {
694 LoggerFactory::getInstance( 'thumbnail' )->error( $msgText ?: $msgHtml, $context );
695 HttpStatus::header( 500 );
697 if ( $wgShowHostnames ) {
698 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
699 $url = htmlspecialchars(
700 $_SERVER['REQUEST_URI'] ?? '',
701 ENT_NOQUOTES
703 $hostname = htmlspecialchars( wfHostname(), ENT_NOQUOTES );
704 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
705 } else {
706 $debug = '';
708 $content = <<<EOT
709 <!DOCTYPE html>
710 <html><head>
711 <meta charset="UTF-8" />
712 <title>Error generating thumbnail</title>
713 </head>
714 <body>
715 <h1>Error generating thumbnail</h1>
717 $msgHtml
718 </p>
719 $debug
720 </body>
721 </html>
723 EOT;
724 header( 'Content-Length: ' . strlen( $content ) );
725 echo $content;