2b689278348eb4581c6c15458abf88423feb2e80
[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 = wfExtractThumbParams( $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
92 * @return void
93 */
94 function wfStreamThumb( array $params ) {
95 global $wgVaryOnXFP;
96
97 $section = new ProfileSection( __METHOD__ );
98
99 $headers = array(); // HTTP headers to send
100
101 $fileName = isset( $params['f'] ) ? $params['f'] : '';
102 unset( $params['f'] );
103
104 // Backwards compatibility parameters
105 if ( isset( $params['w'] ) ) {
106 $params['width'] = $params['w'];
107 unset( $params['w'] );
108 }
109 if ( isset( $params['p'] ) ) {
110 $params['page'] = $params['p'];
111 }
112 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
113
114 // Is this a thumb of an archived file?
115 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
116 unset( $params['archived'] ); // handlers don't care
117
118 // Is this a thumb of a temp file?
119 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
120 unset( $params['temp'] ); // handlers don't care
121
122 // Some basic input validation
123 $fileName = strtr( $fileName, '\\/', '__' );
124
125 // Actually fetch the image. Method depends on whether it is archived or not.
126 if ( $isTemp ) {
127 $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo();
128 $img = new UnregisteredLocalFile( null, $repo,
129 # Temp files are hashed based on the name without the timestamp.
130 # The thumbnails will be hashed based on the entire name however.
131 # @todo fix this convention to actually be reasonable.
132 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
133 );
134 } elseif ( $isOld ) {
135 // Format is <timestamp>!<name>
136 $bits = explode( '!', $fileName, 2 );
137 if ( count( $bits ) != 2 ) {
138 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
139 return;
140 }
141 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
142 if ( !$title ) {
143 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
144 return;
145 }
146 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
147 } else {
148 $img = wfLocalFile( $fileName );
149 }
150
151 // Check the source file title
152 if ( !$img ) {
153 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
154 return;
155 }
156
157 // Check permissions if there are read restrictions
158 $varyHeader = array();
159 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
160 if ( !$img->getTitle() || !$img->getTitle()->userCan( 'read' ) ) {
161 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
162 'the source file.' );
163 return;
164 }
165 $headers[] = 'Cache-Control: private';
166 $varyHeader[] = 'Cookie';
167 }
168
169 // Check the source file storage path
170 if ( !$img->exists() ) {
171 $redirectedLocation = false;
172 if ( !$isTemp ) {
173 // Check for file redirect
174 if ( $isOld ) {
175 // Since redirects are associated with pages, not versions of files,
176 // we look for the most current version to see if its a redirect.
177 $possibleRedirFile = RepoGroup::singleton()->getLocalRepo()->findFile( $img->getName() );
178 } else {
179 $possibleRedirFile = RepoGroup::singleton()->getLocalRepo()->findFile( $fileName );
180 }
181 if ( $possibleRedirFile && !is_null( $possibleRedirFile->getRedirected() ) ) {
182 $redirTarget = $possibleRedirFile->getName();
183 $targetFile = wfLocalFile( Title::makeTitleSafe( NS_FILE, $redirTarget ) );
184 if ( $targetFile->exists() ) {
185 $newThumbName = $targetFile->thumbName( $params );
186 if ( $isOld ) {
187 $newThumbUrl = $targetFile->getArchiveThumbUrl( $bits[0] . '!' . $targetFile->getName(), $newThumbName );
188 } else {
189 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
190 }
191 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT );
192 }
193 }
194 }
195
196 if ( $redirectedLocation ) {
197 // File has been moved. Give redirect.
198 $response = RequestContext::getMain()->getRequest()->response();
199 $response->header( "HTTP/1.1 302 " . HttpStatus::getMessage( 302 ) );
200 $response->header( 'Location: ' . $redirectedLocation );
201 $response->header( 'Expires: ' .
202 gmdate( 'D, d M Y H:i:s', time() + 12 * 3600 ) . ' GMT' );
203 if ( $wgVaryOnXFP ) {
204 $varyHeader[] = 'X-Forwarded-Proto';
205 }
206 if ( count( $varyHeader ) ) {
207 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
208 }
209 return;
210 }
211
212 // If its not a redirect that has a target as a local file, give 404.
213 wfThumbError( 404, "The source file '$fileName' does not exist." );
214 return;
215 } elseif ( $img->getPath() === false ) {
216 wfThumbError( 500, "The source file '$fileName' is not locally accessible." );
217 return;
218 }
219
220 // Check IMS against the source file
221 // This means that clients can keep a cached copy even after it has been deleted on the server
222 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
223 // Fix IE brokenness
224 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
225 // Calculate time
226 wfSuppressWarnings();
227 $imsUnix = strtotime( $imsString );
228 wfRestoreWarnings();
229 if ( wfTimestamp( TS_UNIX, $img->getTimestamp() ) <= $imsUnix ) {
230 header( 'HTTP/1.1 304 Not Modified' );
231 return;
232 }
233 }
234
235 // Get the normalized thumbnail name from the parameters...
236 try {
237 $thumbName = $img->thumbName( $params );
238 if ( !strlen( $thumbName ) ) { // invalid params?
239 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
240 return;
241 }
242 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
243 } catch ( MWException $e ) {
244 wfThumbError( 500, $e->getHTML() );
245 return;
246 }
247
248 // For 404 handled thumbnails, we only use the the base name of the URI
249 // for the thumb params and the parent directory for the source file name.
250 // Check that the zone relative path matches up so squid caches won't pick
251 // up thumbs that would not be purged on source file deletion (bug 34231).
252 if ( isset( $params['rel404'] ) ) { // thumbnail was handled via 404
253 if ( rawurldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName ) ) {
254 // Request for the canonical thumbnail name
255 } elseif ( rawurldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName2 ) ) {
256 // Request for the "long" thumbnail name; redirect to canonical name
257 $response = RequestContext::getMain()->getRequest()->response();
258 $response->header( "HTTP/1.1 301 " . HttpStatus::getMessage( 301 ) );
259 $response->header( 'Location: ' .
260 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
261 $response->header( 'Expires: ' .
262 gmdate( 'D, d M Y H:i:s', time() + 7 * 86400 ) . ' GMT' );
263 if ( $wgVaryOnXFP ) {
264 $varyHeader[] = 'X-Forwarded-Proto';
265 }
266 if ( count( $varyHeader ) ) {
267 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
268 }
269 return;
270 } else {
271 wfThumbError( 404, "The given path of the specified thumbnail is incorrect;
272 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
273 rawurldecode( $params['rel404'] ) . "'." );
274 return;
275 }
276 }
277
278 // Suggest a good name for users downloading this thumbnail
279 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName )}";
280
281 if ( count( $varyHeader ) ) {
282 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
283 }
284
285 // Stream the file if it exists already...
286 $thumbPath = $img->getThumbPath( $thumbName );
287 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
288 $img->getRepo()->streamFile( $thumbPath, $headers );
289 return;
290 }
291
292 // Thumbnail isn't already there, so create the new thumbnail...
293 try {
294 $thumb = $img->transform( $params, File::RENDER_NOW );
295 } catch ( Exception $ex ) {
296 // Tried to select a page on a non-paged file?
297 $thumb = false;
298 }
299
300 // Check for thumbnail generation errors...
301 $errorMsg = false;
302 $msg = wfMessage( 'thumbnail_error' );
303 if ( !$thumb ) {
304 $errorMsg = $msg->rawParams( 'File::transform() returned false' )->escaped();
305 } elseif ( $thumb->isError() ) {
306 $errorMsg = $thumb->getHtmlMsg();
307 } elseif ( !$thumb->hasFile() ) {
308 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
309 } elseif ( $thumb->fileIsSource() ) {
310 $errorMsg = $msg->
311 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
312 }
313
314 if ( $errorMsg !== false ) {
315 wfThumbError( 500, $errorMsg );
316 } else {
317 // Stream the file if there were no errors
318 $thumb->streamFile( $headers );
319 }
320 }
321
322 /**
323 * Extract the required params for thumb.php from the thumbnail request URI.
324 * At least 'width' and 'f' should be set if the result is an array.
325 *
326 * @param $thumbRel String Thumbnail path relative to the thumb zone
327 * @return Array|null associative params array or null
328 */
329 function wfExtractThumbParams( $thumbRel ) {
330 $repo = RepoGroup::singleton()->getLocalRepo();
331
332 $hashDirReg = $subdirReg = '';
333 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
334 $subdirReg .= '[0-9a-f]';
335 $hashDirReg .= "$subdirReg/";
336 }
337
338 // Check if this is a thumbnail of an original in the local file repo
339 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
340 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
341 // Check if this is a thumbnail of an temp file in the local file repo
342 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
343 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
344 } else {
345 return null; // not a valid looking thumbnail request
346 }
347
348 $params = array( 'f' => $filename, 'rel404' => $rel );
349 if ( $archOrTemp === 'archive/' ) {
350 $params['archived'] = 1;
351 } elseif ( $archOrTemp === 'temp/' ) {
352 $params['temp'] = 1;
353 }
354
355 // Check hooks if parameters can be extracted
356 // Hooks return false if they manage to *resolve* the parameters
357 if ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
358 return $params; // valid thumbnail URL (via extension or config)
359 // Check if the parameters can be extracted from the thumbnail name...
360 } elseif ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
361 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
362 $params['width'] = $size;
363 if ( $pagenum ) {
364 $params['page'] = $pagenum;
365 }
366 return $params; // valid thumbnail URL
367 }
368
369 return null; // not a valid thumbnail URL
370 }
371
372 /**
373 * Output a thumbnail generation error message
374 *
375 * @param $status integer
376 * @param $msg string
377 * @return void
378 */
379 function wfThumbError( $status, $msg ) {
380 global $wgShowHostnames;
381
382 header( 'Cache-Control: no-cache' );
383 header( 'Content-Type: text/html; charset=utf-8' );
384 if ( $status == 404 ) {
385 header( 'HTTP/1.1 404 Not found' );
386 } elseif ( $status == 403 ) {
387 header( 'HTTP/1.1 403 Forbidden' );
388 header( 'Vary: Cookie' );
389 } else {
390 header( 'HTTP/1.1 500 Internal server error' );
391 }
392 if ( $wgShowHostnames ) {
393 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
394 $hostname = htmlspecialchars( wfHostname() );
395 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
396 } else {
397 $debug = '';
398 }
399 echo <<<EOT
400 <html><head><title>Error generating thumbnail</title></head>
401 <body>
402 <h1>Error generating thumbnail</h1>
403 <p>
404 $msg
405 </p>
406 $debug
407 </body>
408 </html>
409
410 EOT;
411 }