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