Merge "Update formatting for CSS files in skins/"
[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 wfThumbHandleRequest();
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 query parameters
48 *
49 * @return void
50 */
51 function wfThumbHandleRequest() {
52 $params = get_magic_quotes_gpc()
53 ? array_map( 'stripslashes', $_GET )
54 : $_GET;
55
56 wfStreamThumb( $params ); // stream the thumbnail
57 }
58
59 /**
60 * Handle a thumbnail request via thumbnail file URL
61 *
62 * @return void
63 */
64 function wfThumbHandle404() {
65 global $wgArticlePath;
66
67 # Set action base paths so that WebRequest::getPathInfo()
68 # recognizes the "X" as the 'title' in ../thumb_handler.php/X urls.
69 # Note: If Custom per-extension repo paths are set, this may break.
70 $repo = RepoGroup::singleton()->getLocalRepo();
71 $oldArticlePath = $wgArticlePath;
72 $wgArticlePath = $repo->getZoneUrl( 'thumb' ) . '/$1';
73
74 $matches = WebRequest::getPathInfo();
75
76 $wgArticlePath = $oldArticlePath;
77
78 if ( !isset( $matches['title'] ) ) {
79 wfThumbError( 404, 'Could not determine the name of the requested thumbnail.' );
80 return;
81 }
82
83 $params = wfExtractThumbRequestInfo( $matches['title'] ); // basic wiki URL param extracting
84 if ( $params == null ) {
85 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
86 return;
87 }
88
89 wfStreamThumb( $params ); // stream the thumbnail
90 }
91
92 /**
93 * Stream a thumbnail specified by parameters
94 *
95 * @param array $params List of thumbnailing parameters. In addition to parameters
96 * passed to the MediaHandler, this may also includes the keys:
97 * f (for filename), archived (if archived file), temp (if temp file),
98 * w (alias for width), p (alias for page), r (ignored; historical),
99 * rel404 (path for render on 404 to verify hash path correct),
100 * thumbName (thumbnail name to potentially extract more parameters from
101 * e.g. 'lossy-page1-120px-Foo.tiff' would add page, lossy and width
102 * to the parameters)
103 * @return void
104 */
105 function wfStreamThumb( array $params ) {
106 global $wgVaryOnXFP;
107
108 $section = new ProfileSection( __METHOD__ );
109
110 $headers = array(); // HTTP headers to send
111
112 $fileName = isset( $params['f'] ) ? $params['f'] : '';
113
114 // Backwards compatibility parameters
115 if ( isset( $params['w'] ) ) {
116 $params['width'] = $params['w'];
117 unset( $params['w'] );
118 }
119 if ( isset( $params['p'] ) ) {
120 $params['page'] = $params['p'];
121 }
122
123 // Is this a thumb of an archived file?
124 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
125 unset( $params['archived'] ); // handlers don't care
126
127 // Is this a thumb of a temp file?
128 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
129 unset( $params['temp'] ); // handlers don't care
130
131 // Some basic input validation
132 $fileName = strtr( $fileName, '\\/', '__' );
133
134 // Actually fetch the image. Method depends on whether it is archived or not.
135 if ( $isTemp ) {
136 $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo();
137 $img = new UnregisteredLocalFile( null, $repo,
138 # Temp files are hashed based on the name without the timestamp.
139 # The thumbnails will be hashed based on the entire name however.
140 # @todo fix this convention to actually be reasonable.
141 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
142 );
143 } elseif ( $isOld ) {
144 // Format is <timestamp>!<name>
145 $bits = explode( '!', $fileName, 2 );
146 if ( count( $bits ) != 2 ) {
147 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
148 return;
149 }
150 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
151 if ( !$title ) {
152 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
153 return;
154 }
155 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
156 } else {
157 $img = wfLocalFile( $fileName );
158 }
159
160 // Check the source file title
161 if ( !$img ) {
162 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
163 return;
164 }
165
166 // Check if the file is hidden
167 if ( $img->isDeleted( File::DELETED_FILE ) ) {
168 wfThumbError( 404, "The source file '$fileName' does not exist." );
169 return;
170 }
171
172 // Check permissions if there are read restrictions
173 $varyHeader = array();
174 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
175 if ( !$img->getTitle() || !$img->getTitle()->userCan( 'read' ) ) {
176 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
177 'the source file.' );
178 return;
179 }
180 $headers[] = 'Cache-Control: private';
181 $varyHeader[] = 'Cookie';
182 }
183
184 // Do rendering parameters extraction from thumbnail name.
185 if ( isset( $params['thumbName'] ) ) {
186 $params = wfExtractThumbParams( $img, $params );
187 }
188 if ( $params == null ) {
189 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
190 return;
191 }
192
193 // Check the source file storage path
194 if ( !$img->exists() ) {
195 $redirectedLocation = false;
196 if ( !$isTemp ) {
197 // Check for file redirect
198 // Since redirects are associated with pages, not versions of files,
199 // we look for the most current version to see if its a redirect.
200 $possRedirFile = RepoGroup::singleton()->getLocalRepo()->findFile( $img->getName() );
201 if ( $possRedirFile && !is_null( $possRedirFile->getRedirected() ) ) {
202 $redirTarget = $possRedirFile->getName();
203 $targetFile = wfLocalFile( Title::makeTitleSafe( NS_FILE, $redirTarget ) );
204 if ( $targetFile->exists() ) {
205 $newThumbName = $targetFile->thumbName( $params );
206 if ( $isOld ) {
207 $newThumbUrl = $targetFile->getArchiveThumbUrl(
208 $bits[0] . '!' . $targetFile->getName(), $newThumbName );
209 } else {
210 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
211 }
212 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT );
213 }
214 }
215 }
216
217 if ( $redirectedLocation ) {
218 // File has been moved. Give redirect.
219 $response = RequestContext::getMain()->getRequest()->response();
220 $response->header( "HTTP/1.1 302 " . HttpStatus::getMessage( 302 ) );
221 $response->header( 'Location: ' . $redirectedLocation );
222 $response->header( 'Expires: ' .
223 gmdate( 'D, d M Y H:i:s', time() + 12 * 3600 ) . ' GMT' );
224 if ( $wgVaryOnXFP ) {
225 $varyHeader[] = 'X-Forwarded-Proto';
226 }
227 if ( count( $varyHeader ) ) {
228 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
229 }
230 return;
231 }
232
233 // If its not a redirect that has a target as a local file, give 404.
234 wfThumbError( 404, "The source file '$fileName' does not exist." );
235 return;
236 } elseif ( $img->getPath() === false ) {
237 wfThumbError( 500, "The source file '$fileName' is not locally accessible." );
238 return;
239 }
240
241 // Check IMS against the source file
242 // This means that clients can keep a cached copy even after it has been deleted on the server
243 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
244 // Fix IE brokenness
245 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
246 // Calculate time
247 wfSuppressWarnings();
248 $imsUnix = strtotime( $imsString );
249 wfRestoreWarnings();
250 if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
251 header( 'HTTP/1.1 304 Not Modified' );
252 return;
253 }
254 }
255
256 $rel404 = isset( $params['rel404'] ) ? $params['rel404'] : null;
257 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
258 unset( $params['f'] ); // We're done with 'f' parameter.
259 unset( $params['rel404'] ); // moved to $rel404
260
261 // Get the normalized thumbnail name from the parameters...
262 try {
263 $thumbName = $img->thumbName( $params );
264 if ( !strlen( $thumbName ) ) { // invalid params?
265 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
266 return;
267 }
268 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
269 } catch ( MWException $e ) {
270 wfThumbError( 500, $e->getHTML() );
271 return;
272 }
273
274 // For 404 handled thumbnails, we only use the the base name of the URI
275 // for the thumb params and the parent directory for the source file name.
276 // Check that the zone relative path matches up so squid caches won't pick
277 // up thumbs that would not be purged on source file deletion (bug 34231).
278 if ( $rel404 !== null ) { // thumbnail was handled via 404
279 if ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName ) ) {
280 // Request for the canonical thumbnail name
281 } elseif ( rawurldecode( $rel404 ) === $img->getThumbRel( $thumbName2 ) ) {
282 // Request for the "long" thumbnail name; redirect to canonical name
283 $response = RequestContext::getMain()->getRequest()->response();
284 $response->header( "HTTP/1.1 301 " . HttpStatus::getMessage( 301 ) );
285 $response->header( 'Location: ' .
286 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
287 $response->header( 'Expires: ' .
288 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
289 if ( $wgVaryOnXFP ) {
290 $varyHeader[] = 'X-Forwarded-Proto';
291 }
292 if ( count( $varyHeader ) ) {
293 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
294 }
295 return;
296 } else {
297 wfThumbError( 404, "The given path of the specified thumbnail is incorrect;
298 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
299 rawurldecode( $rel404 ) . "'." );
300 return;
301 }
302 }
303
304 $dispositionType = isset( $params['download'] ) ? 'attachment' : 'inline';
305
306 // Suggest a good name for users downloading this thumbnail
307 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName, $dispositionType )}";
308
309 if ( count( $varyHeader ) ) {
310 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
311 }
312
313 // Stream the file if it exists already...
314 $thumbPath = $img->getThumbPath( $thumbName );
315 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
316 $img->getRepo()->streamFile( $thumbPath, $headers );
317 return;
318 }
319
320 $user = RequestContext::getMain()->getUser();
321 if ( !wfThumbIsStandard( $img, $params ) && $user->pingLimiter( 'renderfile-nonstandard' ) ) {
322 wfThumbError( 500, wfMessage( 'actionthrottledtext' ) );
323 return;
324 } elseif ( $user->pingLimiter( 'renderfile' ) ) {
325 wfThumbError( 500, wfMessage( 'actionthrottledtext' ) );
326 return;
327 }
328
329 // Actually generate a new thumbnail
330 list( $thumb, $errorMsg ) = wfGenerateThumbnail( $img, $params, $thumbName );
331
332 // Check for thumbnail generation errors...
333 $msg = wfMessage( 'thumbnail_error' );
334 if ( !$thumb ) {
335 $errorMsg = $errorMsg ?: $msg->rawParams( 'File::transform() returned false' )->escaped();
336 } elseif ( $thumb->isError() ) {
337 $errorMsg = $thumb->getHtmlMsg();
338 } elseif ( !$thumb->hasFile() ) {
339 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
340 } elseif ( $thumb->fileIsSource() ) {
341 $errorMsg = $msg->
342 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
343 }
344
345 if ( $errorMsg !== false ) {
346 wfThumbError( 500, $errorMsg );
347 } else {
348 // Stream the file if there were no errors
349 $thumb->streamFile( $headers );
350 }
351 }
352
353 /**
354 * Actually try to generate a new thumbnail
355 *
356 * @param File $file
357 * @param array $params
358 * @param string $thumbName
359 * @return array (MediaTransformOutput|bool, string|bool error message HTML)
360 */
361 function wfGenerateThumbnail( File $file, array $params, $thumbName ) {
362 global $wgMemc, $wgAttemptFailureEpoch;
363
364 $key = wfMemcKey( 'attempt-failures', $wgAttemptFailureEpoch,
365 $file->getRepo()->getName(), md5( $file->getName() ), md5( $thumbName ) );
366
367 // Check if this file keeps failing to render
368 if ( $wgMemc->get( $key ) >= 4 ) {
369 return array( false, wfMessage( 'thumbnail_image-failure-limit', 4 ) );
370 }
371
372 $done = false;
373 // Record failures on PHP fatals in addition to caching exceptions
374 register_shutdown_function( function() use ( &$done, $key ) {
375 if ( !$done ) { // transform() gave a fatal
376 global $wgMemc;
377 $wgMemc->incrWithInit( $key, 3600 );
378 }
379 } );
380
381 $thumb = false;
382 $errorHtml = false;
383
384 // Thumbnail isn't already there, so create the new thumbnail...
385 try {
386 $work = new PoolCounterWorkViaCallback( 'FileRender', sha1( $file->getName() ),
387 array(
388 'doWork' => function() use ( $file, $params ) {
389 return $file->transform( $params, File::RENDER_NOW );
390 },
391 'getCachedWork' => function() use ( $file, $params ) {
392 return $file->transform( $params );
393 },
394 'fallback' => function() {
395 return wfMessage( 'generic-pool-error' )->parse();
396 },
397 'error' => function ( $status ) {
398 return $status->getHTML();
399 }
400 )
401 );
402 $result = $work->execute();
403 if ( $result instanceof MediaTransformOutput ) {
404 $thumb = $result;
405 } elseif ( is_string( $result ) ) { // error
406 $errorHtml = $result;
407 }
408 } catch ( Exception $e ) {
409 // Tried to select a page on a non-paged file?
410 }
411
412 $done = true; // no PHP fatal occured
413
414 if ( !$thumb || $thumb->isError() ) {
415 $wgMemc->incrWithInit( $key, 3600 );
416 }
417
418 return array( $thumb, $errorHtml );
419 }
420
421 /**
422 * Returns true if this thumbnail is one that MediaWiki generates
423 * links to on file description pages and possibly parser output.
424 *
425 * $params is considered non-standard if they involve a non-standard
426 * width or any parameter aside from width and page number. The number
427 * of possible files with standard parameters is far less than that of all
428 * possible combinations; rate-limiting for them can thus be more generious.
429 *
430 * @param File $img
431 * @param array $params
432 * @return bool
433 */
434 function wfThumbIsStandard( File $img, array $params ) {
435 global $wgThumbLimits, $wgImageLimits;
436 // @TODO: use polymorphism with media handler here
437 if ( array_diff( array_keys( $params ), array( 'width', 'page' ) ) ) {
438 return false; // extra parameters present
439 }
440 if ( isset( $params['width'] ) ) {
441 $widths = $wgThumbLimits;
442 foreach ( $wgImageLimits as $pair ) {
443 $widths[] = $pair[0];
444 }
445 if ( !in_array( $params['width'], $widths ) ) {
446 return false;
447 }
448 }
449 return true;
450 }
451
452 /**
453 * Convert pathinfo type parameter, into normal request parameters
454 *
455 * So for example, if the request was redirected from
456 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
457 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
458 * This method is responsible for turning that into an array
459 * with the folowing keys:
460 * * f => the filename (Foo.png)
461 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
462 * * archived => 1 (If the request is for an archived thumb)
463 * * temp => 1 (If the file is in the "temporary" zone)
464 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
465 *
466 * Transform specific parameters are set later via wfExtractThumbParams().
467 *
468 * @param string $thumbRel Thumbnail path relative to the thumb zone
469 * @return array|null Associative params array or null
470 */
471 function wfExtractThumbRequestInfo( $thumbRel ) {
472 $repo = RepoGroup::singleton()->getLocalRepo();
473
474 $hashDirReg = $subdirReg = '';
475 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
476 $subdirReg .= '[0-9a-f]';
477 $hashDirReg .= "$subdirReg/";
478 }
479
480 // Check if this is a thumbnail of an original in the local file repo
481 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
482 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
483 // Check if this is a thumbnail of an temp file in the local file repo
484 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
485 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
486 } else {
487 return null; // not a valid looking thumbnail request
488 }
489
490 $params = array( 'f' => $filename, 'rel404' => $rel );
491 if ( $archOrTemp === 'archive/' ) {
492 $params['archived'] = 1;
493 } elseif ( $archOrTemp === 'temp/' ) {
494 $params['temp'] = 1;
495 }
496
497 $params['thumbName'] = $thumbname;
498 return $params;
499 }
500
501 /**
502 * Convert a thumbnail name (122px-foo.png) to parameters, using
503 * file handler.
504 *
505 * @param File $file File object for file in question
506 * @param array $param Array of parameters so far
507 * @return array Parameters array with more parameters
508 */
509 function wfExtractThumbParams( $file, $params ) {
510 if ( !isset( $params['thumbName'] ) ) {
511 throw new MWException( "No thumbnail name passed to wfExtractThumbParams" );
512 }
513
514 $thumbname = $params['thumbName'];
515 unset( $params['thumbName'] );
516
517 // Do the hook first for older extensions that rely on it.
518 if ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
519 // Check hooks if parameters can be extracted
520 // Hooks return false if they manage to *resolve* the parameters
521 // This hook should be considered deprecated
522 wfDeprecated( 'ExtractThumbParameters', '1.22' );
523 return $params; // valid thumbnail URL (via extension or config)
524 }
525
526 // FIXME: Files in the temp zone don't set a mime type, which means
527 // they don't have a handler. Which means we can't parse the param
528 // string. However, not a big issue as what good is a param string
529 // if you have no handler to make use of the param string and
530 // actually generate the thumbnail.
531 $handler = $file->getHandler();
532
533 // Based on UploadStash::parseKey
534 $fileNamePos = strrpos( $thumbname, $params['f'] );
535 if ( $fileNamePos === false ) {
536 // Maybe using a short filename? (see FileRepo::nameForThumb)
537 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
538 }
539
540 if ( $handler && $fileNamePos !== false ) {
541 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
542 $extraParams = $handler->parseParamString( $paramString );
543 if ( $extraParams !== false ) {
544 return $params + $extraParams;
545 }
546 }
547
548 // As a last ditch fallback, use the traditional common parameters
549 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
550 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
551 $params['width'] = $size;
552 if ( $pagenum ) {
553 $params['page'] = $pagenum;
554 }
555 return $params; // valid thumbnail URL
556 }
557 return null;
558 }
559
560 /**
561 * Output a thumbnail generation error message
562 *
563 * @param int $status
564 * @param string $msg
565 * @return void
566 */
567 function wfThumbError( $status, $msg ) {
568 global $wgShowHostnames;
569
570 header( 'Cache-Control: no-cache' );
571 header( 'Content-Type: text/html; charset=utf-8' );
572 if ( $status == 404 ) {
573 header( 'HTTP/1.1 404 Not found' );
574 } elseif ( $status == 403 ) {
575 header( 'HTTP/1.1 403 Forbidden' );
576 header( 'Vary: Cookie' );
577 } else {
578 header( 'HTTP/1.1 500 Internal server error' );
579 }
580 if ( $wgShowHostnames ) {
581 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
582 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
583 $hostname = htmlspecialchars( wfHostname() );
584 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
585 } else {
586 $debug = '';
587 }
588 echo <<<EOT
589 <html><head><title>Error generating thumbnail</title></head>
590 <body>
591 <h1>Error generating thumbnail</h1>
592 <p>
593 $msg
594 </p>
595 $debug
596 </body>
597 </html>
598
599 EOT;
600 }