Merge "Use CSSJanus via composer"
[mediawiki.git] / thumb.php
blob3d8612d9726988ec17bbb21029b38f2e581905c6
1 <?php
2 /**
3 * PHP script to stream out an image thumbnail.
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.
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.
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
20 * @file
21 * @ingroup Media
24 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
25 require __DIR__ . '/includes/WebStart.php';
27 // Don't use fancy MIME detection, just check the file extension for jpg/gif/png
28 $wgTrivialMimeDetection = true;
30 if ( defined( 'THUMB_HANDLER' ) ) {
31 // Called from thumb_handler.php via 404; extract params from the URI...
32 wfThumbHandle404();
33 } else {
34 // Called directly, use $_GET params
35 wfStreamThumb( $_GET );
38 wfLogProfilingData();
39 // Commit and close up!
40 $factory = wfGetLBFactory();
41 $factory->commitMasterChanges();
42 $factory->shutdown();
44 //--------------------------------------------------------------------------
46 /**
47 * Handle a thumbnail request via thumbnail file URL
49 * @return void
51 function wfThumbHandle404() {
52 global $wgArticlePath;
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';
61 $matches = WebRequest::getPathInfo();
63 $wgArticlePath = $oldArticlePath;
65 if ( !isset( $matches['title'] ) ) {
66 wfThumbError( 404, 'Could not determine the name of the requested thumbnail.' );
67 return;
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;
76 wfStreamThumb( $params ); // stream the thumbnail
79 /**
80 * Stream a thumbnail specified by parameters
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
92 function wfStreamThumb( array $params ) {
93 global $wgVaryOnXFP;
95 $section = new ProfileSection( __METHOD__ );
97 $headers = array(); // HTTP headers to send
99 $fileName = isset( $params['f'] ) ? $params['f'] : '';
101 // Backwards compatibility parameters
102 if ( isset( $params['w'] ) ) {
103 $params['width'] = $params['w'];
104 unset( $params['w'] );
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 );
110 if ( isset( $params['p'] ) ) {
111 $params['page'] = $params['p'];
114 // Is this a thumb of an archived file?
115 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
116 unset( $params['archived'] ); // handlers don't care
118 // Is this a thumb of a temp file?
119 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
120 unset( $params['temp'] ); // handlers don't care
122 // Some basic input validation
123 $fileName = strtr( $fileName, '\\/', '__' );
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
134 } elseif ( $isOld ) {
135 // Format is <timestamp>!<name>
136 $bits = explode( '!', $fileName, 2 );
137 if ( count( $bits ) != 2 ) {
138 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
139 return;
141 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
142 if ( !$title ) {
143 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
144 return;
146 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
147 } else {
148 $img = wfLocalFile( $fileName );
151 // Check the source file title
152 if ( !$img ) {
153 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
154 return;
157 // Check permissions if there are read restrictions
158 $varyHeader = array();
159 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
160 if ( !$img->getTitle() || !$img->getTitle()->userCan( 'read' ) ) {
161 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
162 'the source file.' );
163 return;
165 $headers[] = 'Cache-Control: private';
166 $varyHeader[] = 'Cookie';
169 // Check if the file is hidden
170 if ( $img->isDeleted( File::DELETED_FILE ) ) {
171 wfThumbError( 404, "The source file '$fileName' does not exist." );
172 return;
175 // Do rendering parameters extraction from thumbnail name.
176 if ( isset( $params['thumbName'] ) ) {
177 $params = wfExtractThumbParams( $img, $params );
179 if ( $params == null ) {
180 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
181 return;
184 // Check the source file storage path
185 if ( !$img->exists() ) {
186 $redirectedLocation = false;
187 if ( !$isTemp ) {
188 // Check for file redirect
189 // Since redirects are associated with pages, not versions of files,
190 // we look for the most current version to see if its a redirect.
191 $possRedirFile = RepoGroup::singleton()->getLocalRepo()->findFile( $img->getName() );
192 if ( $possRedirFile && !is_null( $possRedirFile->getRedirected() ) ) {
193 $redirTarget = $possRedirFile->getName();
194 $targetFile = wfLocalFile( Title::makeTitleSafe( NS_FILE, $redirTarget ) );
195 if ( $targetFile->exists() ) {
196 $newThumbName = $targetFile->thumbName( $params );
197 if ( $isOld ) {
198 $newThumbUrl = $targetFile->getArchiveThumbUrl(
199 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
200 } else {
201 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
203 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT );
208 if ( $redirectedLocation ) {
209 // File has been moved. Give redirect.
210 $response = RequestContext::getMain()->getRequest()->response();
211 $response->header( "HTTP/1.1 302 " . HttpStatus::getMessage( 302 ) );
212 $response->header( 'Location: ' . $redirectedLocation );
213 $response->header( 'Expires: ' .
214 gmdate( 'D, d M Y H:i:s', time() + 12 * 3600 ) . ' GMT' );
215 if ( $wgVaryOnXFP ) {
216 $varyHeader[] = 'X-Forwarded-Proto';
218 if ( count( $varyHeader ) ) {
219 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
221 return;
224 // If its not a redirect that has a target as a local file, give 404.
225 wfThumbError( 404, "The source file '$fileName' does not exist." );
226 return;
227 } elseif ( $img->getPath() === false ) {
228 wfThumbError( 500, "The source file '$fileName' is not locally accessible." );
229 return;
232 // Check IMS against the source file
233 // This means that clients can keep a cached copy even after it has been deleted on the server
234 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
235 // Fix IE brokenness
236 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
237 // Calculate time
238 wfSuppressWarnings();
239 $imsUnix = strtotime( $imsString );
240 wfRestoreWarnings();
241 if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
242 header( 'HTTP/1.1 304 Not Modified' );
243 return;
247 $rel404 = isset( $params['rel404'] ) ? $params['rel404'] : null;
248 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
249 unset( $params['f'] ); // We're done with 'f' parameter.
250 unset( $params['rel404'] ); // moved to $rel404
252 // Get the normalized thumbnail name from the parameters...
253 try {
254 $thumbName = $img->thumbName( $params );
255 if ( !strlen( $thumbName ) ) { // invalid params?
256 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
257 return;
259 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
260 } catch ( MWException $e ) {
261 wfThumbError( 500, $e->getHTML() );
262 return;
265 // For 404 handled thumbnails, we only use the the base name of the URI
266 // for the thumb params and the parent directory for the source file name.
267 // Check that the zone relative path matches up so squid caches won't pick
268 // up thumbs that would not be purged on source file deletion (bug 34231).
269 if ( $rel404 !== null ) { // thumbnail was handled via 404
270 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
271 // Request for the canonical thumbnail name
272 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
273 // Request for the "long" thumbnail name; redirect to canonical name
274 $response = RequestContext::getMain()->getRequest()->response();
275 $response->header( "HTTP/1.1 301 " . HttpStatus::getMessage( 301 ) );
276 $response->header( 'Location: ' .
277 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
278 $response->header( 'Expires: ' .
279 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
280 if ( $wgVaryOnXFP ) {
281 $varyHeader[] = 'X-Forwarded-Proto';
283 if ( count( $varyHeader ) ) {
284 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
286 return;
287 } else {
288 wfThumbError( 404, "The given path of the specified thumbnail is incorrect;
289 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
290 rawurldecode( $rel404 ) . "'." );
291 return;
295 $dispositionType = isset( $params['download'] ) ? 'attachment' : 'inline';
297 // Suggest a good name for users downloading this thumbnail
298 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName, $dispositionType )}";
300 if ( count( $varyHeader ) ) {
301 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
304 // Stream the file if it exists already...
305 $thumbPath = $img->getThumbPath( $thumbName );
306 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
307 $img->getRepo()->streamFile( $thumbPath, $headers );
308 return;
311 $user = RequestContext::getMain()->getUser();
312 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
313 wfThumbError( 500, wfMessage( 'actionthrottledtext' ) );
314 return;
315 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
316 wfThumbError( 500, wfMessage( 'actionthrottledtext' ) );
317 return;
320 // Actually generate a new thumbnail
321 list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
323 // Check for thumbnail generation errors...
324 $msg = wfMessage( 'thumbnail_error' );
325 if ( !$thumb ) {
326 $errorMsg = $errorMsg ?: $msg->rawParams( 'File::transform() returned false' )->escaped();
327 } elseif ( $thumb->isError() ) {
328 $errorMsg = $thumb->getHtmlMsg();
329 } elseif ( !$thumb->hasFile() ) {
330 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
331 } elseif ( $thumb->fileIsSource() ) {
332 $errorMsg = $msg->
333 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
336 if ( $errorMsg !== false ) {
337 wfThumbError( 500, $errorMsg );
338 } else {
339 // Stream the file if there were no errors
340 $thumb->streamFile( $headers );
345 * Actually try to generate a new thumbnail
347 * @param File $file
348 * @param array $params
349 * @param string $thumbName
350 * @param string $thumbPath
351 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
353 function wfGenerateThumbnail( File $file, array $params, $thumbName, $thumbPath ) {
354 global $wgMemc, $wgAttemptFailureEpoch;
356 $key = wfMemcKey( 'attempt-failures', $wgAttemptFailureEpoch,
357 $file->getRepo()->getName(), $file->getSha1(), md5( $thumbName ) );
359 // Check if this file keeps failing to render
360 if ( $wgMemc->get( $key ) >= 4 ) {
361 return array( false, wfMessage( 'thumbnail_image-failure-limit', 4 ) );
364 $done = false;
365 // Record failures on PHP fatals in addition to caching exceptions
366 register_shutdown_function( function () use ( &$done, $key ) {
367 if ( !$done ) { // transform() gave a fatal
368 global $wgMemc;
369 // Randomize TTL to reduce stampedes
370 $wgMemc->incrWithInit( $key, 3600 + mt_rand( 0, 300 ) );
372 } );
374 $thumb = false;
375 $errorHtml = false;
377 // guard thumbnail rendering with PoolCounter to avoid stampedes
378 // expensive files use a separate PoolCounter config so it is possible
379 // to set up a global limit on them
380 if ( $file->isExpensiveToThumbnail() ) {
381 $poolCounterType = 'FileRenderExpensive';
382 } else {
383 $poolCounterType = 'FileRender';
386 // Thumbnail isn't already there, so create the new thumbnail...
387 try {
388 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
389 array(
390 'doWork' => function () use ( $file, $params ) {
391 return $file->transform( $params, File::RENDER_NOW );
393 'getCachedWork' => function () use ( $file, $params, $thumbPath ) {
394 // If the worker that finished made this thumbnail then use it.
395 // Otherwise, it probably made a different thumbnail for this file.
396 return $file->getRepo()->fileExists( $thumbPath )
397 ? $file->transform( $params, File::RENDER_NOW )
398 : false; // retry once more in exclusive mode
400 'fallback' => function () {
401 return wfMessage( 'generic-pool-error' )->parse();
403 'error' => function ( $status ) {
404 return $status->getHTML();
408 $result = $work->execute();
409 if ( $result instanceof MediaTransformOutput ) {
410 $thumb = $result;
411 } elseif ( is_string( $result ) ) { // error
412 $errorHtml = $result;
414 } catch ( Exception $e ) {
415 // Tried to select a page on a non-paged file?
418 $done = true; // no PHP fatal occured
420 if ( !$thumb || $thumb->isError() ) {
421 // Randomize TTL to reduce stampedes
422 $wgMemc->incrWithInit( $key, 3600 + mt_rand( 0, 300 ) );
425 return array( $thumb, $errorHtml );
429 * Returns true if this thumbnail is one that MediaWiki generates
430 * links to on file description pages and possibly parser output.
432 * $params is considered non-standard if they involve a non-standard
433 * width or any non-default parameters aside from width and page number.
434 * The number of possible files with standard parameters is far less than
435 * that of all combinations; rate-limiting for them can thus be more generious.
437 * @param File $file
438 * @param array $params
439 * @return bool
441 function wfThumbIsStandard( File $file, array $params ) {
442 global $wgThumbLimits, $wgImageLimits;
444 $handler = $file->getHandler();
445 if ( !$handler || !isset( $params['width'] ) ) {
446 return false;
449 $basicParams = array();
450 if ( isset( $params['page'] ) ) {
451 $basicParams['page'] = $params['page'];
454 // Check if the width matches one of $wgThumbLimits
455 if ( in_array( $params['width'], $wgThumbLimits ) ) {
456 $normalParams = $basicParams + array( 'width' => $params['width'] );
457 // Append any default values to the map (e.g. "lossy", "lossless", ...)
458 $handler->normaliseParams( $file, $normalParams );
459 } else {
460 // If not, then check if the width matchs one of $wgImageLimits
461 $match = false;
462 foreach ( $wgImageLimits as $pair ) {
463 $normalParams = $basicParams + array( 'width' => $pair[0], 'height' => $pair[1] );
464 // Decide whether the thumbnail should be scaled on width or height.
465 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
466 $handler->normaliseParams( $file, $normalParams );
467 // Check if this standard thumbnail size maps to the given width
468 if ( $normalParams['width'] == $params['width'] ) {
469 $match = true;
470 break;
473 if ( !$match ) {
474 return false; // not standard for description pages
478 // Check that the given values for non-page, non-width, params are just defaults
479 foreach ( $params as $key => $value ) {
480 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
481 return false;
485 return true;
489 * Convert pathinfo type parameter, into normal request parameters
491 * So for example, if the request was redirected from
492 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
493 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
494 * This method is responsible for turning that into an array
495 * with the folowing keys:
496 * * f => the filename (Foo.png)
497 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
498 * * archived => 1 (If the request is for an archived thumb)
499 * * temp => 1 (If the file is in the "temporary" zone)
500 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
502 * Transform specific parameters are set later via wfExtractThumbParams().
504 * @param string $thumbRel Thumbnail path relative to the thumb zone
505 * @return array|null Associative params array or null
507 function wfExtractThumbRequestInfo( $thumbRel ) {
508 $repo = RepoGroup::singleton()->getLocalRepo();
510 $hashDirReg = $subdirReg = '';
511 $hashLevels = $repo->getHashLevels();
512 for ( $i = 0; $i < $hashLevels; $i++ ) {
513 $subdirReg .= '[0-9a-f]';
514 $hashDirReg .= "$subdirReg/";
517 // Check if this is a thumbnail of an original in the local file repo
518 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
519 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
520 // Check if this is a thumbnail of an temp file in the local file repo
521 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
522 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
523 } else {
524 return null; // not a valid looking thumbnail request
527 $params = array( 'f' => $filename, 'rel404' => $rel );
528 if ( $archOrTemp === 'archive/' ) {
529 $params['archived'] = 1;
530 } elseif ( $archOrTemp === 'temp/' ) {
531 $params['temp'] = 1;
534 $params['thumbName'] = $thumbname;
535 return $params;
539 * Convert a thumbnail name (122px-foo.png) to parameters, using
540 * file handler.
542 * @param File $file File object for file in question
543 * @param array $params Array of parameters so far
544 * @return array Parameters array with more parameters
546 function wfExtractThumbParams( $file, $params ) {
547 if ( !isset( $params['thumbName'] ) ) {
548 throw new MWException( "No thumbnail name passed to wfExtractThumbParams" );
551 $thumbname = $params['thumbName'];
552 unset( $params['thumbName'] );
554 // Do the hook first for older extensions that rely on it.
555 if ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
556 // Check hooks if parameters can be extracted
557 // Hooks return false if they manage to *resolve* the parameters
558 // This hook should be considered deprecated
559 wfDeprecated( 'ExtractThumbParameters', '1.22' );
560 return $params; // valid thumbnail URL (via extension or config)
563 // FIXME: Files in the temp zone don't set a MIME type, which means
564 // they don't have a handler. Which means we can't parse the param
565 // string. However, not a big issue as what good is a param string
566 // if you have no handler to make use of the param string and
567 // actually generate the thumbnail.
568 $handler = $file->getHandler();
570 // Based on UploadStash::parseKey
571 $fileNamePos = strrpos( $thumbname, $params['f'] );
572 if ( $fileNamePos === false ) {
573 // Maybe using a short filename? (see FileRepo::nameForThumb)
574 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
577 if ( $handler && $fileNamePos !== false ) {
578 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
579 $extraParams = $handler->parseParamString( $paramString );
580 if ( $extraParams !== false ) {
581 return $params + $extraParams;
585 // As a last ditch fallback, use the traditional common parameters
586 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
587 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
588 $params['width'] = $size;
589 if ( $pagenum ) {
590 $params['page'] = $pagenum;
592 return $params; // valid thumbnail URL
594 return null;
598 * Output a thumbnail generation error message
600 * @param int $status
601 * @param string $msg
602 * @return void
604 function wfThumbError( $status, $msg ) {
605 global $wgShowHostnames;
607 header( 'Cache-Control: no-cache' );
608 header( 'Content-Type: text/html; charset=utf-8' );
609 if ( $status == 404 ) {
610 header( 'HTTP/1.1 404 Not found' );
611 } elseif ( $status == 403 ) {
612 header( 'HTTP/1.1 403 Forbidden' );
613 header( 'Vary: Cookie' );
614 } else {
615 header( 'HTTP/1.1 500 Internal server error' );
617 if ( $wgShowHostnames ) {
618 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
619 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
620 $hostname = htmlspecialchars( wfHostname() );
621 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
622 } else {
623 $debug = '';
625 echo <<<EOT
626 <html><head><title>Error generating thumbnail</title></head>
627 <body>
628 <h1>Error generating thumbnail</h1>
630 $msg
631 </p>
632 $debug
633 </body>
634 </html>
636 EOT;