Migrate remaining usages of Title::userCan() to PermissionManager
[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
95 $headers = []; // HTTP headers to send
96
97 $fileName = $params['f'] ?? '';
98
99 // Backwards compatibility parameters
100 if ( isset( $params['w'] ) ) {
101 $params['width'] = $params['w'];
102 unset( $params['w'] );
103 }
104 if ( isset( $params['width'] ) && substr( $params['width'], -2 ) == 'px' ) {
105 // strip the px (pixel) suffix, if found
106 $params['width'] = substr( $params['width'], 0, -2 );
107 }
108 if ( isset( $params['p'] ) ) {
109 $params['page'] = $params['p'];
110 }
111
112 // Is this a thumb of an archived file?
113 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
114 unset( $params['archived'] ); // handlers don't care
115
116 // Is this a thumb of a temp file?
117 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
118 unset( $params['temp'] ); // handlers don't care
119
120 // Some basic input validation
121 $fileName = strtr( $fileName, '\\/', '__' );
122
123 // Actually fetch the image. Method depends on whether it is archived or not.
124 if ( $isTemp ) {
125 $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo();
126 $img = new UnregisteredLocalFile( null, $repo,
127 # Temp files are hashed based on the name without the timestamp.
128 # The thumbnails will be hashed based on the entire name however.
129 # @todo fix this convention to actually be reasonable.
130 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
131 );
132 } elseif ( $isOld ) {
133 // Format is <timestamp>!<name>
134 $bits = explode( '!', $fileName, 2 );
135 if ( count( $bits ) != 2 ) {
136 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
137 return;
138 }
139 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
140 if ( !$title ) {
141 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
142 return;
143 }
144 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
145 } else {
146 $img = wfLocalFile( $fileName );
147 }
148
149 // Check the source file title
150 if ( !$img ) {
151 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
152 return;
153 }
154
155 // Check permissions if there are read restrictions
156 $varyHeader = [];
157 if ( !in_array( 'read', User::getGroupPermissions( [ '*' ] ), true ) ) {
158 $user = RequestContext::getMain()->getUser();
159 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
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 // Simply serve the response from the proxied service as-is
417 header( 'HTTP/1.1 ' . $req->getStatus() );
418
419 $headers = $req->getResponseHeaders();
420
421 foreach ( $headers as $key => $values ) {
422 foreach ( $values as $value ) {
423 header( $key . ': ' . $value, false );
424 }
425 }
426
427 echo $req->getContent();
428 }
429
430 /**
431 * Actually try to generate a new thumbnail
432 *
433 * @param File $file
434 * @param array $params
435 * @param string $thumbName
436 * @param string $thumbPath
437 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
438 */
439 function wfGenerateThumbnail( File $file, array $params, $thumbName, $thumbPath ) {
440 global $wgAttemptFailureEpoch;
441
442 $cache = ObjectCache::getLocalClusterInstance();
443 $key = $cache->makeKey(
444 'attempt-failures',
445 $wgAttemptFailureEpoch,
446 $file->getRepo()->getName(),
447 $file->getSha1(),
448 md5( $thumbName )
449 );
450
451 // Check if this file keeps failing to render
452 if ( $cache->get( $key ) >= 4 ) {
453 return [ false, wfMessage( 'thumbnail_image-failure-limit', 4 ) ];
454 }
455
456 $done = false;
457 // Record failures on PHP fatals in addition to caching exceptions
458 register_shutdown_function( function () use ( $cache, &$done, $key ) {
459 if ( !$done ) { // transform() gave a fatal
460 // Randomize TTL to reduce stampedes
461 $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
462 }
463 } );
464
465 $thumb = false;
466 $errorHtml = false;
467
468 // guard thumbnail rendering with PoolCounter to avoid stampedes
469 // expensive files use a separate PoolCounter config so it is possible
470 // to set up a global limit on them
471 if ( $file->isExpensiveToThumbnail() ) {
472 $poolCounterType = 'FileRenderExpensive';
473 } else {
474 $poolCounterType = 'FileRender';
475 }
476
477 // Thumbnail isn't already there, so create the new thumbnail...
478 try {
479 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
480 [
481 'doWork' => function () use ( $file, $params ) {
482 return $file->transform( $params, File::RENDER_NOW );
483 },
484 'doCachedWork' => function () use ( $file, $params, $thumbPath ) {
485 // If the worker that finished made this thumbnail then use it.
486 // Otherwise, it probably made a different thumbnail for this file.
487 return $file->getRepo()->fileExists( $thumbPath )
488 ? $file->transform( $params, File::RENDER_NOW )
489 : false; // retry once more in exclusive mode
490 },
491 'error' => function ( Status $status ) {
492 return wfMessage( 'generic-pool-error' )->parse() . '<hr>' . $status->getHTML();
493 }
494 ]
495 );
496 $result = $work->execute();
497 if ( $result instanceof MediaTransformOutput ) {
498 $thumb = $result;
499 } elseif ( is_string( $result ) ) { // error
500 $errorHtml = $result;
501 }
502 } catch ( Exception $e ) {
503 // Tried to select a page on a non-paged file?
504 }
505
506 /** @noinspection PhpUnusedLocalVariableInspection */
507 $done = true; // no PHP fatal occurred
508
509 if ( !$thumb || $thumb->isError() ) {
510 // Randomize TTL to reduce stampedes
511 $cache->incrWithInit( $key, $cache::TTL_HOUR + mt_rand( 0, 300 ) );
512 }
513
514 return [ $thumb, $errorHtml ];
515 }
516
517 /**
518 * Convert pathinfo type parameter, into normal request parameters
519 *
520 * So for example, if the request was redirected from
521 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
522 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
523 * This method is responsible for turning that into an array
524 * with the folowing keys:
525 * * f => the filename (Foo.png)
526 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
527 * * archived => 1 (If the request is for an archived thumb)
528 * * temp => 1 (If the file is in the "temporary" zone)
529 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
530 *
531 * Transform specific parameters are set later via wfExtractThumbParams().
532 *
533 * @param string $thumbRel Thumbnail path relative to the thumb zone
534 * @return array|null Associative params array or null
535 */
536 function wfExtractThumbRequestInfo( $thumbRel ) {
537 $repo = RepoGroup::singleton()->getLocalRepo();
538
539 $hashDirReg = $subdirReg = '';
540 $hashLevels = $repo->getHashLevels();
541 for ( $i = 0; $i < $hashLevels; $i++ ) {
542 $subdirReg .= '[0-9a-f]';
543 $hashDirReg .= "$subdirReg/";
544 }
545
546 // Check if this is a thumbnail of an original in the local file repo
547 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
548 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
549 // Check if this is a thumbnail of an temp file in the local file repo
550 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
551 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
552 } else {
553 return null; // not a valid looking thumbnail request
554 }
555
556 $params = [ 'f' => $filename, 'rel404' => $rel ];
557 if ( $archOrTemp === 'archive/' ) {
558 $params['archived'] = 1;
559 } elseif ( $archOrTemp === 'temp/' ) {
560 $params['temp'] = 1;
561 }
562
563 $params['thumbName'] = $thumbname;
564 return $params;
565 }
566
567 /**
568 * Convert a thumbnail name (122px-foo.png) to parameters, using
569 * file handler.
570 *
571 * @param File $file File object for file in question
572 * @param array $params Array of parameters so far
573 * @return array Parameters array with more parameters
574 */
575 function wfExtractThumbParams( $file, $params ) {
576 if ( !isset( $params['thumbName'] ) ) {
577 throw new InvalidArgumentException( "No thumbnail name passed to wfExtractThumbParams" );
578 }
579
580 $thumbname = $params['thumbName'];
581 unset( $params['thumbName'] );
582
583 // FIXME: Files in the temp zone don't set a MIME type, which means
584 // they don't have a handler. Which means we can't parse the param
585 // string. However, not a big issue as what good is a param string
586 // if you have no handler to make use of the param string and
587 // actually generate the thumbnail.
588 $handler = $file->getHandler();
589
590 // Based on UploadStash::parseKey
591 $fileNamePos = strrpos( $thumbname, $params['f'] );
592 if ( $fileNamePos === false ) {
593 // Maybe using a short filename? (see FileRepo::nameForThumb)
594 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
595 }
596
597 if ( $handler && $fileNamePos !== false ) {
598 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
599 $extraParams = $handler->parseParamString( $paramString );
600 if ( $extraParams !== false ) {
601 return $params + $extraParams;
602 }
603 }
604
605 // As a last ditch fallback, use the traditional common parameters
606 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
607 list( /* all */, /* pagefull */, $pagenum, $size ) = $matches;
608 $params['width'] = $size;
609 if ( $pagenum ) {
610 $params['page'] = $pagenum;
611 }
612 return $params; // valid thumbnail URL
613 }
614 return null;
615 }
616
617 /**
618 * Output a thumbnail generation error message
619 *
620 * @param int $status
621 * @param string $msgText Plain text (will be html escaped)
622 * @return void
623 */
624 function wfThumbErrorText( $status, $msgText ) {
625 wfThumbError( $status, htmlspecialchars( $msgText, ENT_NOQUOTES ) );
626 }
627
628 /**
629 * Output a thumbnail generation error message
630 *
631 * @param int $status
632 * @param string $msgHtml HTML
633 * @param string|null $msgText Short error description, for internal logging. Defaults to $msgHtml.
634 * Only used for HTTP 500 errors.
635 * @param array $context Error context, for internal logging. Only used for HTTP 500 errors.
636 * @return void
637 */
638 function wfThumbError( $status, $msgHtml, $msgText = null, $context = [] ) {
639 global $wgShowHostnames;
640
641 header( 'Cache-Control: no-cache' );
642 header( 'Content-Type: text/html; charset=utf-8' );
643 if ( $status == 400 || $status == 404 || $status == 429 ) {
644 HttpStatus::header( $status );
645 } elseif ( $status == 403 ) {
646 HttpStatus::header( 403 );
647 header( 'Vary: Cookie' );
648 } else {
649 LoggerFactory::getInstance( 'thumb' )->error( $msgText ?: $msgHtml, $context );
650 HttpStatus::header( 500 );
651 }
652 if ( $wgShowHostnames ) {
653 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
654 $url = htmlspecialchars(
655 $_SERVER['REQUEST_URI'] ?? '',
656 ENT_NOQUOTES
657 );
658 $hostname = htmlspecialchars( wfHostname(), ENT_NOQUOTES );
659 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
660 } else {
661 $debug = '';
662 }
663 $content = <<<EOT
664 <!DOCTYPE html>
665 <html><head>
666 <meta charset="UTF-8" />
667 <title>Error generating thumbnail</title>
668 </head>
669 <body>
670 <h1>Error generating thumbnail</h1>
671 <p>
672 $msgHtml
673 </p>
674 $debug
675 </body>
676 </html>
677
678 EOT;
679 header( 'Content-Length: ' . strlen( $content ) );
680 echo $content;
681 }