Remove $wgDebugFunctionEntry, unused
[mediawiki.git] / thumb.php
blob7352dc4c5b8270c0cc038da8ae3fcaf5a7fee2f2
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;
96 $headers = array(); // HTTP headers to send
98 $fileName = isset( $params['f'] ) ? $params['f'] : '';
100 // Backwards compatibility parameters
101 if ( isset( $params['w'] ) ) {
102 $params['width'] = $params['w'];
103 unset( $params['w'] );
105 if ( isset( $params['width'] ) && substr( $params['width'], -2 ) == 'px' ) {
106 // strip the px (pixel) suffix, if found
107 $params['width'] = substr( $params['width'], 0, -2 );
109 if ( isset( $params['p'] ) ) {
110 $params['page'] = $params['p'];
113 // Is this a thumb of an archived file?
114 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
115 unset( $params['archived'] ); // handlers don't care
117 // Is this a thumb of a temp file?
118 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
119 unset( $params['temp'] ); // handlers don't care
121 // Some basic input validation
122 $fileName = strtr( $fileName, '\\/', '__' );
124 // Actually fetch the image. Method depends on whether it is archived or not.
125 if ( $isTemp ) {
126 $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo();
127 $img = new UnregisteredLocalFile( null, $repo,
128 # Temp files are hashed based on the name without the timestamp.
129 # The thumbnails will be hashed based on the entire name however.
130 # @todo fix this convention to actually be reasonable.
131 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
133 } elseif ( $isOld ) {
134 // Format is <timestamp>!<name>
135 $bits = explode( '!', $fileName, 2 );
136 if ( count( $bits ) != 2 ) {
137 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
138 return;
140 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
141 if ( !$title ) {
142 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
143 return;
145 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
146 } else {
147 $img = wfLocalFile( $fileName );
150 // Check the source file title
151 if ( !$img ) {
152 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
153 return;
156 // Check permissions if there are read restrictions
157 $varyHeader = array();
158 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
159 if ( !$img->getTitle() || !$img->getTitle()->userCan( 'read' ) ) {
160 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
161 'the source file.' );
162 return;
164 $headers[] = 'Cache-Control: private';
165 $varyHeader[] = 'Cookie';
168 // Check if the file is hidden
169 if ( $img->isDeleted( File::DELETED_FILE ) ) {
170 wfThumbError( 404, "The source file '$fileName' does not exist." );
171 return;
174 // Do rendering parameters extraction from thumbnail name.
175 if ( isset( $params['thumbName'] ) ) {
176 $params = wfExtractThumbParams( $img, $params );
178 if ( $params == null ) {
179 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
180 return;
183 // Check the source file storage path
184 if ( !$img->exists() ) {
185 $redirectedLocation = false;
186 if ( !$isTemp ) {
187 // Check for file redirect
188 // Since redirects are associated with pages, not versions of files,
189 // we look for the most current version to see if its a redirect.
190 $possRedirFile = RepoGroup::singleton()->getLocalRepo()->findFile( $img->getName() );
191 if ( $possRedirFile && !is_null( $possRedirFile->getRedirected() ) ) {
192 $redirTarget = $possRedirFile->getName();
193 $targetFile = wfLocalFile( Title::makeTitleSafe( NS_FILE, $redirTarget ) );
194 if ( $targetFile->exists() ) {
195 $newThumbName = $targetFile->thumbName( $params );
196 if ( $isOld ) {
197 $newThumbUrl = $targetFile->getArchiveThumbUrl(
198 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
199 } else {
200 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
202 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT );
207 if ( $redirectedLocation ) {
208 // File has been moved. Give redirect.
209 $response = RequestContext::getMain()->getRequest()->response();
210 $response->header( "HTTP/1.1 302 " . HttpStatus::getMessage( 302 ) );
211 $response->header( 'Location: ' . $redirectedLocation );
212 $response->header( 'Expires: ' .
213 gmdate( 'D, d M Y H:i:s', time() + 12 * 3600 ) . ' GMT' );
214 if ( $wgVaryOnXFP ) {
215 $varyHeader[] = 'X-Forwarded-Proto';
217 if ( count( $varyHeader ) ) {
218 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
220 return;
223 // If its not a redirect that has a target as a local file, give 404.
224 wfThumbError( 404, "The source file '$fileName' does not exist." );
225 return;
226 } elseif ( $img->getPath() === false ) {
227 wfThumbError( 500, "The source file '$fileName' is not locally accessible." );
228 return;
231 // Check IMS against the source file
232 // This means that clients can keep a cached copy even after it has been deleted on the server
233 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
234 // Fix IE brokenness
235 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
236 // Calculate time
237 wfSuppressWarnings();
238 $imsUnix = strtotime( $imsString );
239 wfRestoreWarnings();
240 if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
241 header( 'HTTP/1.1 304 Not Modified' );
242 return;
246 $rel404 = isset( $params['rel404'] ) ? $params['rel404'] : null;
247 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
248 unset( $params['f'] ); // We're done with 'f' parameter.
249 unset( $params['rel404'] ); // moved to $rel404
251 // Get the normalized thumbnail name from the parameters...
252 try {
253 $thumbName = $img->thumbName( $params );
254 if ( !strlen( $thumbName ) ) { // invalid params?
255 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
256 return;
258 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
259 } catch ( MWException $e ) {
260 wfThumbError( 500, $e->getHTML() );
261 return;
264 // For 404 handled thumbnails, we only use the base name of the URI
265 // for the thumb params and the parent directory for the source file name.
266 // Check that the zone relative path matches up so squid caches won't pick
267 // up thumbs that would not be purged on source file deletion (bug 34231).
268 if ( $rel404 !== null ) { // thumbnail was handled via 404
269 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
270 // Request for the canonical thumbnail name
271 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
272 // Request for the "long" thumbnail name; redirect to canonical name
273 $response = RequestContext::getMain()->getRequest()->response();
274 $response->header( "HTTP/1.1 301 " . HttpStatus::getMessage( 301 ) );
275 $response->header( 'Location: ' .
276 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
277 $response->header( 'Expires: ' .
278 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
279 if ( $wgVaryOnXFP ) {
280 $varyHeader[] = 'X-Forwarded-Proto';
282 if ( count( $varyHeader ) ) {
283 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
285 return;
286 } else {
287 wfThumbError( 404, "The given path of the specified thumbnail is incorrect;
288 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
289 rawurldecode( $rel404 ) . "'." );
290 return;
294 $dispositionType = isset( $params['download'] ) ? 'attachment' : 'inline';
296 // Suggest a good name for users downloading this thumbnail
297 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName, $dispositionType )}";
299 if ( count( $varyHeader ) ) {
300 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
303 // Stream the file if it exists already...
304 $thumbPath = $img->getThumbPath( $thumbName );
305 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
306 $img->getRepo()->streamFile( $thumbPath, $headers );
307 return;
310 $user = RequestContext::getMain()->getUser();
311 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
312 wfThumbError( 500, wfMessage( 'actionthrottledtext' )->parse() );
313 return;
314 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
315 wfThumbError( 500, wfMessage( 'actionthrottledtext' )->parse() );
316 return;
319 // Actually generate a new thumbnail
320 list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
322 // Check for thumbnail generation errors...
323 $msg = wfMessage( 'thumbnail_error' );
324 if ( !$thumb ) {
325 $errorMsg = $errorMsg ?: $msg->rawParams( 'File::transform() returned false' )->escaped();
326 } elseif ( $thumb->isError() ) {
327 $errorMsg = $thumb->getHtmlMsg();
328 } elseif ( !$thumb->hasFile() ) {
329 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
330 } elseif ( $thumb->fileIsSource() ) {
331 $errorMsg = $msg->
332 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
335 if ( $errorMsg !== false ) {
336 wfThumbError( 500, $errorMsg );
337 } else {
338 // Stream the file if there were no errors
339 $thumb->streamFile( $headers );
344 * Actually try to generate a new thumbnail
346 * @param File $file
347 * @param array $params
348 * @param string $thumbName
349 * @param string $thumbPath
350 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
352 function wfGenerateThumbnail( File $file, array $params, $thumbName, $thumbPath ) {
353 global $wgMemc, $wgAttemptFailureEpoch;
355 $key = wfMemcKey( 'attempt-failures', $wgAttemptFailureEpoch,
356 $file->getRepo()->getName(), $file->getSha1(), md5( $thumbName ) );
358 // Check if this file keeps failing to render
359 if ( $wgMemc->get( $key ) >= 4 ) {
360 return array( false, wfMessage( 'thumbnail_image-failure-limit', 4 ) );
363 $done = false;
364 // Record failures on PHP fatals in addition to caching exceptions
365 register_shutdown_function( function () use ( &$done, $key ) {
366 if ( !$done ) { // transform() gave a fatal
367 global $wgMemc;
368 // Randomize TTL to reduce stampedes
369 $wgMemc->incrWithInit( $key, 3600 + mt_rand( 0, 300 ) );
371 } );
373 $thumb = false;
374 $errorHtml = false;
376 // guard thumbnail rendering with PoolCounter to avoid stampedes
377 // expensive files use a separate PoolCounter config so it is possible
378 // to set up a global limit on them
379 if ( $file->isExpensiveToThumbnail() ) {
380 $poolCounterType = 'FileRenderExpensive';
381 } else {
382 $poolCounterType = 'FileRender';
385 // Thumbnail isn't already there, so create the new thumbnail...
386 try {
387 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
388 array(
389 'doWork' => function () use ( $file, $params ) {
390 return $file->transform( $params, File::RENDER_NOW );
392 'getCachedWork' => function () use ( $file, $params, $thumbPath ) {
393 // If the worker that finished made this thumbnail then use it.
394 // Otherwise, it probably made a different thumbnail for this file.
395 return $file->getRepo()->fileExists( $thumbPath )
396 ? $file->transform( $params, File::RENDER_NOW )
397 : false; // retry once more in exclusive mode
399 'fallback' => function () {
400 return wfMessage( 'generic-pool-error' )->parse();
402 'error' => function ( $status ) {
403 return $status->getHTML();
407 $result = $work->execute();
408 if ( $result instanceof MediaTransformOutput ) {
409 $thumb = $result;
410 } elseif ( is_string( $result ) ) { // error
411 $errorHtml = $result;
413 } catch ( Exception $e ) {
414 // Tried to select a page on a non-paged file?
417 $done = true; // no PHP fatal occured
419 if ( !$thumb || $thumb->isError() ) {
420 // Randomize TTL to reduce stampedes
421 $wgMemc->incrWithInit( $key, 3600 + mt_rand( 0, 300 ) );
424 return array( $thumb, $errorHtml );
428 * Returns true if this thumbnail is one that MediaWiki generates
429 * links to on file description pages and possibly parser output.
431 * $params is considered non-standard if they involve a non-standard
432 * width or any non-default parameters aside from width and page number.
433 * The number of possible files with standard parameters is far less than
434 * that of all combinations; rate-limiting for them can thus be more generious.
436 * @param File $file
437 * @param array $params
438 * @return bool
440 function wfThumbIsStandard( File $file, array $params ) {
441 global $wgThumbLimits, $wgImageLimits;
443 $handler = $file->getHandler();
444 if ( !$handler || !isset( $params['width'] ) ) {
445 return false;
448 $basicParams = array();
449 if ( isset( $params['page'] ) ) {
450 $basicParams['page'] = $params['page'];
453 // Check if the width matches one of $wgThumbLimits
454 if ( in_array( $params['width'], $wgThumbLimits ) ) {
455 $normalParams = $basicParams + array( 'width' => $params['width'] );
456 // Append any default values to the map (e.g. "lossy", "lossless", ...)
457 $handler->normaliseParams( $file, $normalParams );
458 } else {
459 // If not, then check if the width matchs one of $wgImageLimits
460 $match = false;
461 foreach ( $wgImageLimits as $pair ) {
462 $normalParams = $basicParams + array( 'width' => $pair[0], 'height' => $pair[1] );
463 // Decide whether the thumbnail should be scaled on width or height.
464 // Also append any default values to the map (e.g. "lossy", "lossless", ...)
465 $handler->normaliseParams( $file, $normalParams );
466 // Check if this standard thumbnail size maps to the given width
467 if ( $normalParams['width'] == $params['width'] ) {
468 $match = true;
469 break;
472 if ( !$match ) {
473 return false; // not standard for description pages
477 // Check that the given values for non-page, non-width, params are just defaults
478 foreach ( $params as $key => $value ) {
479 if ( !isset( $normalParams[$key] ) || $normalParams[$key] != $value ) {
480 return false;
484 return true;
488 * Convert pathinfo type parameter, into normal request parameters
490 * So for example, if the request was redirected from
491 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
492 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
493 * This method is responsible for turning that into an array
494 * with the folowing keys:
495 * * f => the filename (Foo.png)
496 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
497 * * archived => 1 (If the request is for an archived thumb)
498 * * temp => 1 (If the file is in the "temporary" zone)
499 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
501 * Transform specific parameters are set later via wfExtractThumbParams().
503 * @param string $thumbRel Thumbnail path relative to the thumb zone
504 * @return array|null Associative params array or null
506 function wfExtractThumbRequestInfo( $thumbRel ) {
507 $repo = RepoGroup::singleton()->getLocalRepo();
509 $hashDirReg = $subdirReg = '';
510 $hashLevels = $repo->getHashLevels();
511 for ( $i = 0; $i < $hashLevels; $i++ ) {
512 $subdirReg .= '[0-9a-f]';
513 $hashDirReg .= "$subdirReg/";
516 // Check if this is a thumbnail of an original in the local file repo
517 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
518 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
519 // Check if this is a thumbnail of an temp file in the local file repo
520 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
521 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
522 } else {
523 return null; // not a valid looking thumbnail request
526 $params = array( 'f' => $filename, 'rel404' => $rel );
527 if ( $archOrTemp === 'archive/' ) {
528 $params['archived'] = 1;
529 } elseif ( $archOrTemp === 'temp/' ) {
530 $params['temp'] = 1;
533 $params['thumbName'] = $thumbname;
534 return $params;
538 * Convert a thumbnail name (122px-foo.png) to parameters, using
539 * file handler.
541 * @param File $file File object for file in question
542 * @param array $params Array of parameters so far
543 * @return array Parameters array with more parameters
545 function wfExtractThumbParams( $file, $params ) {
546 if ( !isset( $params['thumbName'] ) ) {
547 throw new MWException( "No thumbnail name passed to wfExtractThumbParams" );
550 $thumbname = $params['thumbName'];
551 unset( $params['thumbName'] );
553 // Do the hook first for older extensions that rely on it.
554 if ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
555 // Check hooks if parameters can be extracted
556 // Hooks return false if they manage to *resolve* the parameters
557 // This hook should be considered deprecated
558 wfDeprecated( 'ExtractThumbParameters', '1.22' );
559 return $params; // valid thumbnail URL (via extension or config)
562 // FIXME: Files in the temp zone don't set a MIME type, which means
563 // they don't have a handler. Which means we can't parse the param
564 // string. However, not a big issue as what good is a param string
565 // if you have no handler to make use of the param string and
566 // actually generate the thumbnail.
567 $handler = $file->getHandler();
569 // Based on UploadStash::parseKey
570 $fileNamePos = strrpos( $thumbname, $params['f'] );
571 if ( $fileNamePos === false ) {
572 // Maybe using a short filename? (see FileRepo::nameForThumb)
573 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
576 if ( $handler && $fileNamePos !== false ) {
577 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
578 $extraParams = $handler->parseParamString( $paramString );
579 if ( $extraParams !== false ) {
580 return $params + $extraParams;
584 // As a last ditch fallback, use the traditional common parameters
585 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
586 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
587 $params['width'] = $size;
588 if ( $pagenum ) {
589 $params['page'] = $pagenum;
591 return $params; // valid thumbnail URL
593 return null;
597 * Output a thumbnail generation error message
599 * @param int $status
600 * @param string $msg HTML
601 * @return void
603 function wfThumbError( $status, $msg ) {
604 global $wgShowHostnames;
606 header( 'Cache-Control: no-cache' );
607 header( 'Content-Type: text/html; charset=utf-8' );
608 if ( $status == 404 ) {
609 header( 'HTTP/1.1 404 Not found' );
610 } elseif ( $status == 403 ) {
611 header( 'HTTP/1.1 403 Forbidden' );
612 header( 'Vary: Cookie' );
613 } else {
614 header( 'HTTP/1.1 500 Internal server error' );
616 if ( $wgShowHostnames ) {
617 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
618 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
619 $hostname = htmlspecialchars( wfHostname() );
620 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
621 } else {
622 $debug = '';
624 echo <<<EOT
625 <html><head><title>Error generating thumbnail</title></head>
626 <body>
627 <h1>Error generating thumbnail</h1>
629 $msg
630 </p>
631 $debug
632 </body>
633 </html>
635 EOT;