Move up devunt's name to Developers
[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 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
25 require __DIR__ . '/includes/WebStart.php';
26
27 // Don't use fancy MIME detection, just check the file extension for jpg/gif/png
28 $wgTrivialMimeDetection = true;
29
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 );
36 }
37
38 wfLogProfilingData();
39 // Commit and close up!
40 $factory = wfGetLBFactory();
41 $factory->commitMasterChanges();
42 $factory->shutdown();
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
96 $headers = array(); // HTTP headers to send
97
98 $fileName = isset( $params['f'] ) ? $params['f'] : '';
99
100 // Backwards compatibility parameters
101 if ( isset( $params['w'] ) ) {
102 $params['width'] = $params['w'];
103 unset( $params['w'] );
104 }
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 );
108 }
109 if ( isset( $params['p'] ) ) {
110 $params['page'] = $params['p'];
111 }
112
113 // Is this a thumb of an archived file?
114 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
115 unset( $params['archived'] ); // handlers don't care
116
117 // Is this a thumb of a temp file?
118 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
119 unset( $params['temp'] ); // handlers don't care
120
121 // Some basic input validation
122 $fileName = strtr( $fileName, '\\/', '__' );
123
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
132 );
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;
139 }
140 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
141 if ( !$title ) {
142 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
143 return;
144 }
145 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
146 } else {
147 $img = wfLocalFile( $fileName );
148 }
149
150 // Check the source file title
151 if ( !$img ) {
152 wfThumbError( 404, wfMessage( 'badtitletext' )->parse() );
153 return;
154 }
155
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;
163 }
164 $headers[] = 'Cache-Control: private';
165 $varyHeader[] = 'Cookie';
166 }
167
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;
172 }
173
174 // Do rendering parameters extraction from thumbnail name.
175 if ( isset( $params['thumbName'] ) ) {
176 $params = wfExtractThumbParams( $img, $params );
177 }
178 if ( $params == null ) {
179 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
180 return;
181 }
182
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 );
201 }
202 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT );
203 }
204 }
205 }
206
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';
216 }
217 if ( count( $varyHeader ) ) {
218 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
219 }
220 return;
221 }
222
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;
229 }
230
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;
243 }
244 }
245
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
250
251 // Get the normalized thumbnail name from the parameters...
252 try {
253 $thumbName = $img->thumbName( $params );
254 if ( !strlen( $thumbName ) ) { // invalid params?
255 throw new MediaTransformInvalidParametersException( 'Empty return from File::thumbName' );
256 }
257 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
258 } catch ( MediaTransformInvalidParametersException $e ) {
259 wfThumbError( 400, 'The specified thumbnail parameters are not valid: ' . $e->getMessage() );
260 return;
261 } catch ( MWException $e ) {
262 wfThumbError( 500, $e->getHTML() );
263 return;
264 }
265
266 // For 404 handled thumbnails, we only use the base name of the URI
267 // for the thumb params and the parent directory for the source file name.
268 // Check that the zone relative path matches up so squid caches won't pick
269 // up thumbs that would not be purged on source file deletion (bug 34231).
270 if ( $rel404 !== null ) { // thumbnail was handled via 404
271 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
272 // Request for the canonical thumbnail name
273 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
274 // Request for the "long" thumbnail name; redirect to canonical name
275 $response = RequestContext::getMain()->getRequest()->response();
276 $response->header( "HTTP/1.1 301 " . HttpStatus::getMessage( 301 ) );
277 $response->header( 'Location: ' .
278 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
279 $response->header( 'Expires: ' .
280 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
281 if ( $wgVaryOnXFP ) {
282 $varyHeader[] = 'X-Forwarded-Proto';
283 }
284 if ( count( $varyHeader ) ) {
285 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
286 }
287 return;
288 } else {
289 wfThumbError( 404, "The given path of the specified thumbnail is incorrect;
290 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
291 rawurldecode( $rel404 ) . "'." );
292 return;
293 }
294 }
295
296 $dispositionType = isset( $params['download'] ) ? 'attachment' : 'inline';
297
298 // Suggest a good name for users downloading this thumbnail
299 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName, $dispositionType )}";
300
301 if ( count( $varyHeader ) ) {
302 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
303 }
304
305 // Stream the file if it exists already...
306 $thumbPath = $img->getThumbPath( $thumbName );
307 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
308 $success = $img->getRepo()->streamFile( $thumbPath, $headers );
309 if ( !$success ) {
310 wfThumbError( 500, 'Could not stream the file' );
311 }
312 return;
313 }
314
315 $user = RequestContext::getMain()->getUser();
316 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
317 wfThumbError( 500, wfMessage( 'actionthrottledtext' )->parse() );
318 return;
319 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
320 wfThumbError( 500, wfMessage( 'actionthrottledtext' )->parse() );
321 return;
322 }
323
324 // Actually generate a new thumbnail
325 list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName, $thumbPath );
326 /** @var MediaTransformOutput|bool $thumb */
327
328 // Check for thumbnail generation errors...
329 $msg = wfMessage( 'thumbnail_error' );
330 $errorCode = 500;
331 if ( !$thumb ) {
332 $errorMsg = $errorMsg ?: $msg->rawParams( 'File::transform() returned false' )->escaped();
333 } elseif ( $thumb->isError() ) {
334 $errorMsg = $thumb->getHtmlMsg();
335 } elseif ( !$thumb->hasFile() ) {
336 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
337 } elseif ( $thumb->fileIsSource() ) {
338 $errorMsg = $msg->
339 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
340 $errorCode = 400;
341 }
342
343 if ( $errorMsg !== false ) {
344 wfThumbError( $errorCode, $errorMsg );
345 } else {
346 // Stream the file if there were no errors
347 $success = $thumb->streamFile( $headers );
348 if ( !$success ) {
349 wfThumbError( 500, 'Could not stream the file' );
350 }
351 }
352 }
353
354 /**
355 * Actually try to generate a new thumbnail
356 *
357 * @param File $file
358 * @param array $params
359 * @param string $thumbName
360 * @param string $thumbPath
361 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
362 */
363 function wfGenerateThumbnail( File $file, array $params, $thumbName, $thumbPath ) {
364 global $wgMemc, $wgAttemptFailureEpoch;
365
366 $key = wfMemcKey( 'attempt-failures', $wgAttemptFailureEpoch,
367 $file->getRepo()->getName(), $file->getSha1(), md5( $thumbName ) );
368
369 // Check if this file keeps failing to render
370 if ( $wgMemc->get( $key ) >= 4 ) {
371 return array( false, wfMessage( 'thumbnail_image-failure-limit', 4 ) );
372 }
373
374 $done = false;
375 // Record failures on PHP fatals in addition to caching exceptions
376 register_shutdown_function( function () use ( &$done, $key ) {
377 if ( !$done ) { // transform() gave a fatal
378 global $wgMemc;
379 // Randomize TTL to reduce stampedes
380 $wgMemc->incrWithInit( $key, 3600 + mt_rand( 0, 300 ) );
381 }
382 } );
383
384 $thumb = false;
385 $errorHtml = false;
386
387 // guard thumbnail rendering with PoolCounter to avoid stampedes
388 // expensive files use a separate PoolCounter config so it is possible
389 // to set up a global limit on them
390 if ( $file->isExpensiveToThumbnail() ) {
391 $poolCounterType = 'FileRenderExpensive';
392 } else {
393 $poolCounterType = 'FileRender';
394 }
395
396 // Thumbnail isn't already there, so create the new thumbnail...
397 try {
398 $work = new PoolCounterWorkViaCallback( $poolCounterType, sha1( $file->getName() ),
399 array(
400 'doWork' => function () use ( $file, $params ) {
401 return $file->transform( $params, File::RENDER_NOW );
402 },
403 'getCachedWork' => function () use ( $file, $params, $thumbPath ) {
404 // If the worker that finished made this thumbnail then use it.
405 // Otherwise, it probably made a different thumbnail for this file.
406 return $file->getRepo()->fileExists( $thumbPath )
407 ? $file->transform( $params, File::RENDER_NOW )
408 : false; // retry once more in exclusive mode
409 },
410 'fallback' => function () {
411 return wfMessage( 'generic-pool-error' )->parse();
412 },
413 'error' => function ( $status ) {
414 return $status->getHTML();
415 }
416 )
417 );
418 $result = $work->execute();
419 if ( $result instanceof MediaTransformOutput ) {
420 $thumb = $result;
421 } elseif ( is_string( $result ) ) { // error
422 $errorHtml = $result;
423 }
424 } catch ( Exception $e ) {
425 // Tried to select a page on a non-paged file?
426 }
427
428 $done = true; // no PHP fatal occured
429
430 if ( !$thumb || $thumb->isError() ) {
431 // Randomize TTL to reduce stampedes
432 $wgMemc->incrWithInit( $key, 3600 + mt_rand( 0, 300 ) );
433 }
434
435 return array( $thumb, $errorHtml );
436 }
437
438 /**
439 * Convert pathinfo type parameter, into normal request parameters
440 *
441 * So for example, if the request was redirected from
442 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
443 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
444 * This method is responsible for turning that into an array
445 * with the folowing keys:
446 * * f => the filename (Foo.png)
447 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
448 * * archived => 1 (If the request is for an archived thumb)
449 * * temp => 1 (If the file is in the "temporary" zone)
450 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
451 *
452 * Transform specific parameters are set later via wfExtractThumbParams().
453 *
454 * @param string $thumbRel Thumbnail path relative to the thumb zone
455 * @return array|null Associative params array or null
456 */
457 function wfExtractThumbRequestInfo( $thumbRel ) {
458 $repo = RepoGroup::singleton()->getLocalRepo();
459
460 $hashDirReg = $subdirReg = '';
461 $hashLevels = $repo->getHashLevels();
462 for ( $i = 0; $i < $hashLevels; $i++ ) {
463 $subdirReg .= '[0-9a-f]';
464 $hashDirReg .= "$subdirReg/";
465 }
466
467 // Check if this is a thumbnail of an original in the local file repo
468 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
469 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
470 // Check if this is a thumbnail of an temp file in the local file repo
471 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
472 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
473 } else {
474 return null; // not a valid looking thumbnail request
475 }
476
477 $params = array( 'f' => $filename, 'rel404' => $rel );
478 if ( $archOrTemp === 'archive/' ) {
479 $params['archived'] = 1;
480 } elseif ( $archOrTemp === 'temp/' ) {
481 $params['temp'] = 1;
482 }
483
484 $params['thumbName'] = $thumbname;
485 return $params;
486 }
487
488 /**
489 * Convert a thumbnail name (122px-foo.png) to parameters, using
490 * file handler.
491 *
492 * @param File $file File object for file in question
493 * @param array $params Array of parameters so far
494 * @return array Parameters array with more parameters
495 */
496 function wfExtractThumbParams( $file, $params ) {
497 if ( !isset( $params['thumbName'] ) ) {
498 throw new MWException( "No thumbnail name passed to wfExtractThumbParams" );
499 }
500
501 $thumbname = $params['thumbName'];
502 unset( $params['thumbName'] );
503
504 // Do the hook first for older extensions that rely on it.
505 if ( !Hooks::run( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
506 // Check hooks if parameters can be extracted
507 // Hooks return false if they manage to *resolve* the parameters
508 // This hook should be considered deprecated
509 wfDeprecated( 'ExtractThumbParameters', '1.22' );
510 return $params; // valid thumbnail URL (via extension or config)
511 }
512
513 // FIXME: Files in the temp zone don't set a MIME type, which means
514 // they don't have a handler. Which means we can't parse the param
515 // string. However, not a big issue as what good is a param string
516 // if you have no handler to make use of the param string and
517 // actually generate the thumbnail.
518 $handler = $file->getHandler();
519
520 // Based on UploadStash::parseKey
521 $fileNamePos = strrpos( $thumbname, $params['f'] );
522 if ( $fileNamePos === false ) {
523 // Maybe using a short filename? (see FileRepo::nameForThumb)
524 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
525 }
526
527 if ( $handler && $fileNamePos !== false ) {
528 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
529 $extraParams = $handler->parseParamString( $paramString );
530 if ( $extraParams !== false ) {
531 return $params + $extraParams;
532 }
533 }
534
535 // As a last ditch fallback, use the traditional common parameters
536 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
537 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
538 $params['width'] = $size;
539 if ( $pagenum ) {
540 $params['page'] = $pagenum;
541 }
542 return $params; // valid thumbnail URL
543 }
544 return null;
545 }
546
547 /**
548 * Output a thumbnail generation error message
549 *
550 * @param int $status
551 * @param string $msg HTML
552 * @return void
553 */
554 function wfThumbError( $status, $msg ) {
555 global $wgShowHostnames;
556
557 header( 'Cache-Control: no-cache' );
558 header( 'Content-Type: text/html; charset=utf-8' );
559 if ( $status == 400 ) {
560 header( 'HTTP/1.1 400 Bad request' );
561 } elseif ( $status == 404 ) {
562 header( 'HTTP/1.1 404 Not found' );
563 } elseif ( $status == 403 ) {
564 header( 'HTTP/1.1 403 Forbidden' );
565 header( 'Vary: Cookie' );
566 } else {
567 header( 'HTTP/1.1 500 Internal server error' );
568 }
569 if ( $wgShowHostnames ) {
570 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
571 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
572 $hostname = htmlspecialchars( wfHostname() );
573 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
574 } else {
575 $debug = '';
576 }
577 echo <<<EOT
578 <!DOCTYPE html>
579 <html><head>
580 <meta charset="UTF-8" />
581 <title>Error generating thumbnail</title>
582 </head>
583 <body>
584 <h1>Error generating thumbnail</h1>
585 <p>
586 $msg
587 </p>
588 $debug
589 </body>
590 </html>
591
592 EOT;
593 }