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