Fix typo
[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 } elseif ( wfThumbIsAttemptThrottled( $img, $thumbName, 4 ) ) {
328 wfThumbError( 500, wfMessage( 'thumbnail_image-failure-limit', 4 ) );
329 return;
330 }
331
332 // Thumbnail isn't already there, so create the new thumbnail...
333 $thumb = null;
334 try {
335 // Record failures on PHP fatals too
336 register_shutdown_function( function() use ( &$thumb, $img, $thumbName ) {
337 if ( $thumb === null ) { // transform() gave a fatal
338 wfThumbIncrAttemptFailures( $img, $thumbName );
339 }
340 } );
341 $thumb = $img->transform( $params, File::RENDER_NOW );
342 } catch ( Exception $ex ) {
343 // Tried to select a page on a non-paged file?
344 $thumb = false;
345 }
346
347 // Check for thumbnail generation errors...
348 $errorMsg = false;
349 $msg = wfMessage( 'thumbnail_error' );
350 if ( !$thumb ) {
351 $errorMsg = $msg->rawParams( 'File::transform() returned false' )->escaped();
352 } elseif ( $thumb->isError() ) {
353 $errorMsg = $thumb->getHtmlMsg();
354 } elseif ( !$thumb->hasFile() ) {
355 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
356 } elseif ( $thumb->fileIsSource() ) {
357 $errorMsg = $msg->
358 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
359 }
360
361 if ( $errorMsg !== false ) {
362 wfThumbIncrAttemptFailures( $img, $thumbName );
363 wfThumbError( 500, $errorMsg );
364 } else {
365 // Stream the file if there were no errors
366 $thumb->streamFile( $headers );
367 }
368 }
369
370 /**
371 * Returns true if this thumbnail is one that MediaWiki generates
372 * links to on file description pages and possibly parser output.
373 *
374 * $params is considered non-standard if they involve a non-standard
375 * width or any parameter aside from width and page number. The number
376 * of possible files with standard parameters is far less than that of all
377 * possible combinations; rate-limiting for them can thus be more generious.
378 *
379 * @param File $img
380 * @param array $params
381 * @return bool
382 */
383 function wfThumbIsStandard( File $img, array $params ) {
384 global $wgThumbLimits, $wgImageLimits;
385 // @TODO: use polymorphism with media handler here
386 if ( array_diff( array_keys( $params ), array( 'width', 'page' ) ) ) {
387 return false; // extra parameters present
388 }
389 if ( isset( $params['width'] ) ) {
390 $widths = $wgThumbLimits;
391 foreach ( $wgImageLimits as $pair ) {
392 $widths[] = $pair[0];
393 }
394 if ( !in_array( $params['width'], $widths ) ) {
395 return false;
396 }
397 }
398 return true;
399 }
400
401 /**
402 * @param File $img
403 * @param string $thumbName
404 * @param int $limit
405 * @return int|bool
406 */
407 function wfThumbIsAttemptThrottled( File $img, $thumbName, $limit ) {
408 global $wgMemc;
409
410 return ( $wgMemc->get( wfThumbAttemptKey( $img, $thumbName ) ) >= $limit );
411 }
412
413 /**
414 * @param File $img
415 * @param string $thumbName
416 */
417 function wfThumbIncrAttemptFailures( File $img, $thumbName ) {
418 global $wgMemc;
419
420 $key = wfThumbAttemptKey( $img, $thumbName );
421 if ( !$wgMemc->incr( $key, 1 ) ) {
422 if ( !$wgMemc->add( $key, 1, 3600 ) ) {
423 $wgMemc->incr( $key, 1 );
424 }
425 }
426 }
427
428 /**
429 * @param File $img
430 * @param string $thumbName
431 * @return string
432 */
433 function wfThumbAttemptKey( File $img, $thumbName ) {
434 global $wgAttemptFailureEpoch;
435
436 return wfMemcKey( 'attempt-failures', $wgAttemptFailureEpoch,
437 $img->getRepo()->getName(), md5( $img->getName() ), md5( $thumbName ) );
438 }
439
440 /**
441 * Convert pathinfo type parameter, into normal request parameters
442 *
443 * So for example, if the request was redirected from
444 * /w/images/thumb/a/ab/Foo.png/120px-Foo.png. The $thumbRel parameter
445 * of this function would be set to "a/ab/Foo.png/120px-Foo.png".
446 * This method is responsible for turning that into an array
447 * with the folowing keys:
448 * * f => the filename (Foo.png)
449 * * rel404 => the whole thing (a/ab/Foo.png/120px-Foo.png)
450 * * archived => 1 (If the request is for an archived thumb)
451 * * temp => 1 (If the file is in the "temporary" zone)
452 * * thumbName => the thumbnail name, including parameters (120px-Foo.png)
453 *
454 * Transform specific parameters are set later via wfExtractThumbParams().
455 *
456 * @param string $thumbRel Thumbnail path relative to the thumb zone
457 * @return array|null Associative params array or null
458 */
459 function wfExtractThumbRequestInfo( $thumbRel ) {
460 $repo = RepoGroup::singleton()->getLocalRepo();
461
462 $hashDirReg = $subdirReg = '';
463 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
464 $subdirReg .= '[0-9a-f]';
465 $hashDirReg .= "$subdirReg/";
466 }
467
468 // Check if this is a thumbnail of an original in the local file repo
469 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
470 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
471 // Check if this is a thumbnail of an temp file in the local file repo
472 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
473 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
474 } else {
475 return null; // not a valid looking thumbnail request
476 }
477
478 $params = array( 'f' => $filename, 'rel404' => $rel );
479 if ( $archOrTemp === 'archive/' ) {
480 $params['archived'] = 1;
481 } elseif ( $archOrTemp === 'temp/' ) {
482 $params['temp'] = 1;
483 }
484
485 $params['thumbName'] = $thumbname;
486 return $params;
487 }
488
489 /**
490 * Convert a thumbnail name (122px-foo.png) to parameters, using
491 * file handler.
492 *
493 * @param File $file File object for file in question
494 * @param array $param Array of parameters so far
495 * @return array Parameters array with more parameters
496 */
497 function wfExtractThumbParams( $file, $params ) {
498 if ( !isset( $params['thumbName'] ) ) {
499 throw new MWException( "No thumbnail name passed to wfExtractThumbParams" );
500 }
501
502 $thumbname = $params['thumbName'];
503 unset( $params['thumbName'] );
504
505 // Do the hook first for older extensions that rely on it.
506 if ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
507 // Check hooks if parameters can be extracted
508 // Hooks return false if they manage to *resolve* the parameters
509 // This hook should be considered deprecated
510 wfDeprecated( 'ExtractThumbParameters', '1.22' );
511 return $params; // valid thumbnail URL (via extension or config)
512 }
513
514 // FIXME: Files in the temp zone don't set a mime type, which means
515 // they don't have a handler. Which means we can't parse the param
516 // string. However, not a big issue as what good is a param string
517 // if you have no handler to make use of the param string and
518 // actually generate the thumbnail.
519 $handler = $file->getHandler();
520
521 // Based on UploadStash::parseKey
522 $fileNamePos = strrpos( $thumbname, $params['f'] );
523 if ( $fileNamePos === false ) {
524 // Maybe using a short filename? (see FileRepo::nameForThumb)
525 $fileNamePos = strrpos( $thumbname, 'thumbnail' );
526 }
527
528 if ( $handler && $fileNamePos !== false ) {
529 $paramString = substr( $thumbname, 0, $fileNamePos - 1 );
530 $extraParams = $handler->parseParamString( $paramString );
531 if ( $extraParams !== false ) {
532 return $params + $extraParams;
533 }
534 }
535
536 // As a last ditch fallback, use the traditional common parameters
537 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
538 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
539 $params['width'] = $size;
540 if ( $pagenum ) {
541 $params['page'] = $pagenum;
542 }
543 return $params; // valid thumbnail URL
544 }
545 return null;
546 }
547
548 /**
549 * Output a thumbnail generation error message
550 *
551 * @param int $status
552 * @param string $msg
553 * @return void
554 */
555 function wfThumbError( $status, $msg ) {
556 global $wgShowHostnames;
557
558 header( 'Cache-Control: no-cache' );
559 header( 'Content-Type: text/html; charset=utf-8' );
560 if ( $status == 404 ) {
561 header( 'HTTP/1.1 404 Not found' );
562 } elseif ( $status == 403 ) {
563 header( 'HTTP/1.1 403 Forbidden' );
564 header( 'Vary: Cookie' );
565 } else {
566 header( 'HTTP/1.1 500 Internal server error' );
567 }
568 if ( $wgShowHostnames ) {
569 header( 'X-MW-Thumbnail-Renderer: ' . wfHostname() );
570 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
571 $hostname = htmlspecialchars( wfHostname() );
572 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
573 } else {
574 $debug = '';
575 }
576 echo <<<EOT
577 <html><head><title>Error generating thumbnail</title></head>
578 <body>
579 <h1>Error generating thumbnail</h1>
580 <p>
581 $msg
582 </p>
583 $debug
584 </body>
585 </html>
586
587 EOT;
588 }