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