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