merged master
[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 if ( isset( $_SERVER['MW_COMPILED'] ) ) {
26 require( 'core/includes/WebStart.php' );
27 } else {
28 require( __DIR__ . '/includes/WebStart.php' );
29 }
30
31 // Don't use fancy mime detection, just check the file extension for jpg/gif/png
32 $wgTrivialMimeDetection = true;
33
34 if ( defined( 'THUMB_HANDLER' ) ) {
35 // Called from thumb_handler.php via 404; extract params from the URI...
36 wfThumbHandle404();
37 } else {
38 // Called directly, use $_REQUEST params
39 wfThumbHandleRequest();
40 }
41 wfLogProfilingData();
42
43 //--------------------------------------------------------------------------
44
45 /**
46 * Handle a thumbnail request via query parameters
47 *
48 * @return void
49 */
50 function wfThumbHandleRequest() {
51 $params = get_magic_quotes_gpc()
52 ? array_map( 'stripslashes', $_REQUEST )
53 : $_REQUEST;
54
55 wfStreamThumb( $params ); // stream the thumbnail
56 }
57
58 /**
59 * Handle a thumbnail request via thumbnail file URL
60 *
61 * @return void
62 */
63 function wfThumbHandle404() {
64 # lighttpd puts the original request in REQUEST_URI, while sjs sets
65 # that to the 404 handler, and puts the original request in REDIRECT_URL.
66 if ( isset( $_SERVER['REDIRECT_URL'] ) ) {
67 # The URL is un-encoded, so put it back how it was
68 $uriPath = str_replace( "%2F", "/", urlencode( $_SERVER['REDIRECT_URL'] ) );
69 } else {
70 $uriPath = $_SERVER['REQUEST_URI'];
71 }
72 # Just get the URI path (REDIRECT_URL/REQUEST_URI is either a full URL or a path)
73 if ( substr( $uriPath, 0, 1 ) !== '/' ) {
74 $uri = new Uri( $uriPath );
75 $uriPath = $uri->getPath();
76 if ( $uriPath === null ) {
77 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
78 return;
79 }
80 }
81
82 $params = wfExtractThumbParams( $uriPath ); // basic wiki URL param extracting
83 if ( $params == null ) {
84 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
85 return;
86 }
87
88 wfStreamThumb( $params ); // stream the thumbnail
89 }
90
91 /**
92 * Stream a thumbnail specified by parameters
93 *
94 * @param $params Array
95 * @return void
96 */
97 function wfStreamThumb( array $params ) {
98 global $wgVaryOnXFP;
99 wfProfileIn( __METHOD__ );
100
101 $headers = array(); // HTTP headers to send
102
103 $fileName = isset( $params['f'] ) ? $params['f'] : '';
104 unset( $params['f'] );
105
106 // Backwards compatibility parameters
107 if ( isset( $params['w'] ) ) {
108 $params['width'] = $params['w'];
109 unset( $params['w'] );
110 }
111 if ( isset( $params['p'] ) ) {
112 $params['page'] = $params['p'];
113 }
114 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
115
116 // Is this a thumb of an archived file?
117 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
118 unset( $params['archived'] ); // handlers don't care
119
120 // Is this a thumb of a temp file?
121 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
122 unset( $params['temp'] ); // handlers don't care
123
124 // Some basic input validation
125 $fileName = strtr( $fileName, '\\/', '__' );
126
127 // Actually fetch the image. Method depends on whether it is archived or not.
128 if ( $isOld ) {
129 // Format is <timestamp>!<name>
130 $bits = explode( '!', $fileName, 2 );
131 if ( count( $bits ) != 2 ) {
132 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
133 wfProfileOut( __METHOD__ );
134 return;
135 }
136 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
137 if ( !$title ) {
138 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
139 wfProfileOut( __METHOD__ );
140 return;
141 }
142 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
143 } elseif ( $isTemp ) {
144 $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo();
145 // Format is <timestamp>!<name> or just <name>
146 $bits = explode( '!', $fileName, 2 );
147 // Get the name without the timestamp so hash paths are correctly computed
148 $title = Title::makeTitleSafe( NS_FILE, isset( $bits[1] ) ? $bits[1] : $fileName );
149 if ( !$title ) {
150 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
151 wfProfileOut( __METHOD__ );
152 return;
153 }
154 $img = new UnregisteredLocalFile( $title, $repo,
155 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
156 );
157 } else {
158 $img = wfLocalFile( $fileName );
159 }
160
161 // Check permissions if there are read restrictions
162 $varyHeader = array();
163 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
164 if ( !$img->getTitle() || !$img->getTitle()->userCan( 'read' ) ) {
165 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
166 'the source file.' );
167 wfProfileOut( __METHOD__ );
168 return;
169 }
170 $headers[] = 'Cache-Control: private';
171 $varyHeader[] = 'Cookie';
172 }
173
174 // Check the source file storage path
175 if ( !$img ) {
176 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
177 wfProfileOut( __METHOD__ );
178 return;
179 }
180 if ( !$img->exists() ) {
181 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
182 wfProfileOut( __METHOD__ );
183 return;
184 }
185 $sourcePath = $img->getPath();
186 if ( $sourcePath === false ) {
187 wfThumbError( 500, 'The source file is not locally accessible.' );
188 wfProfileOut( __METHOD__ );
189 return;
190 }
191
192 // Check IMS against the source file
193 // This means that clients can keep a cached copy even after it has been deleted on the server
194 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
195 // Fix IE brokenness
196 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
197 // Calculate time
198 wfSuppressWarnings();
199 $imsUnix = strtotime( $imsString );
200 wfRestoreWarnings();
201 $sourceTsUnix = wfTimestamp( TS_UNIX, $img->getTimestamp() );
202 if ( $sourceTsUnix <= $imsUnix ) {
203 header( 'HTTP/1.1 304 Not Modified' );
204 wfProfileOut( __METHOD__ );
205 return;
206 }
207 }
208
209 $thumbName = $img->thumbName( $params );
210 if ( !strlen( $thumbName ) ) { // invalid params?
211 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
212 wfProfileOut( __METHOD__ );
213 return;
214 }
215
216 $disposition = $img->getThumbDisposition( $thumbName );
217 $headers[] = "Content-Disposition: $disposition";
218
219 // Stream the file if it exists already...
220 try {
221 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
222 // For 404 handled thumbnails, we only use the the base name of the URI
223 // for the thumb params and the parent directory for the source file name.
224 // Check that the zone relative path matches up so squid caches won't pick
225 // up thumbs that would not be purged on source file deletion (bug 34231).
226 if ( isset( $params['rel404'] ) ) { // thumbnail was handled via 404
227 if ( urldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName ) ) {
228 // Request for the canonical thumbnail name
229 } elseif ( urldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName2 ) ) {
230 // Request for the "long" thumbnail name; redirect to canonical name
231 $response = RequestContext::getMain()->getRequest()->response();
232 $response->header( "HTTP/1.1 301 " . HttpStatus::getMessage( 301 ) );
233 $response->header( 'Location: ' . wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
234 $response->header( 'Expires: ' .
235 gmdate( 'D, d M Y H:i:s', time() + 7*86400 ) . ' GMT' );
236 if ( $wgVaryOnXFP ) {
237 $varyHeader[] = 'X-Forwarded-Proto';
238 }
239 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
240 wfProfileOut( __METHOD__ );
241 return;
242 } else {
243 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
244 wfProfileOut( __METHOD__ );
245 return;
246 }
247 }
248 $thumbPath = $img->getThumbPath( $thumbName );
249 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
250 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
251 $img->getRepo()->streamFile( $thumbPath, $headers );
252 wfProfileOut( __METHOD__ );
253 return;
254 }
255 } catch ( MWException $e ) {
256 wfThumbError( 500, $e->getHTML() );
257 wfProfileOut( __METHOD__ );
258 return;
259 }
260 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
261
262 // Thumbnail isn't already there, so create the new thumbnail...
263 try {
264 $thumb = $img->transform( $params, File::RENDER_NOW );
265 } catch ( Exception $ex ) {
266 // Tried to select a page on a non-paged file?
267 $thumb = false;
268 }
269
270 // Check for thumbnail generation errors...
271 $errorMsg = false;
272 $msg = wfMessage( 'thumbnail_error' );
273 if ( !$thumb ) {
274 $errorMsg = $msg->rawParams( 'File::transform() returned false' )->escaped();
275 } elseif ( $thumb->isError() ) {
276 $errorMsg = $thumb->getHtmlMsg();
277 } elseif ( !$thumb->hasFile() ) {
278 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
279 } elseif ( $thumb->fileIsSource() ) {
280 $errorMsg = $msg->
281 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
282 }
283
284 if ( $errorMsg !== false ) {
285 wfThumbError( 500, $errorMsg );
286 } else {
287 // Stream the file if there were no errors
288 $thumb->streamFile( $headers );
289 }
290
291 wfProfileOut( __METHOD__ );
292 }
293
294 /**
295 * Extract the required params for thumb.php from the thumbnail request URI.
296 * At least 'width' and 'f' should be set if the result is an array.
297 *
298 * @param $uriPath String Thumbnail request URI path
299 * @return Array|null associative params array or null
300 */
301 function wfExtractThumbParams( $uriPath ) {
302 $repo = RepoGroup::singleton()->getLocalRepo();
303
304 $zoneUriPath = $repo->getZoneHandlerUrl( 'thumb' )
305 ? $repo->getZoneHandlerUrl( 'thumb' ) // custom URL
306 : $repo->getZoneUrl( 'thumb' ); // default to main URL
307 // URL might be relative ("/images") or protocol-relative ("//lang.site/image")
308 $bits = wfParseUrl( wfExpandUrl( $zoneUriPath, PROTO_INTERNAL ) );
309 if ( $bits && isset( $bits['path'] ) ) {
310 $zoneUriPath = $bits['path'];
311 } else {
312 return null;
313 }
314
315 $hashDirRegex = $subdirRegex = '';
316 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
317 $subdirRegex .= '[0-9a-f]';
318 $hashDirRegex .= "$subdirRegex/";
319 }
320
321 $thumbPathRegex = "!^" . preg_quote( $zoneUriPath ) .
322 "/((archive/|temp/)?$hashDirRegex([^/]*)/([^/]*))$!";
323
324 // Check if this is a valid looking thumbnail request...
325 if ( preg_match( $thumbPathRegex, $uriPath, $matches ) ) {
326 list( /* all */, $rel, $archOrTemp, $filename, $thumbname ) = $matches;
327 $filename = urldecode( $filename );
328 $thumbname = urldecode( $thumbname );
329
330 $params = array( 'f' => $filename, 'rel404' => $rel );
331 if ( $archOrTemp == 'archive/' ) {
332 $params['archived'] = 1;
333 } elseif ( $archOrTemp == 'temp/' ) {
334 $params['temp'] = 1;
335 }
336
337 // Check if the parameters can be extracted from the thumbnail name...
338 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
339 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
340 $params['width'] = $size;
341 if ( $pagenum ) {
342 $params['page'] = $pagenum;
343 }
344 return $params; // valid thumbnail URL
345 // Hooks return false if they manage to *resolve* the parameters
346 } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
347 return $params; // valid thumbnail URL (via extension or config)
348 }
349 }
350
351 return null; // not a valid thumbnail URL
352 }
353
354 /**
355 * Output a thumbnail generation error message
356 *
357 * @param $status integer
358 * @param $msg string
359 * @return void
360 */
361 function wfThumbError( $status, $msg ) {
362 global $wgShowHostnames;
363
364 header( 'Cache-Control: no-cache' );
365 header( 'Content-Type: text/html; charset=utf-8' );
366 if ( $status == 404 ) {
367 header( 'HTTP/1.1 404 Not found' );
368 } elseif ( $status == 403 ) {
369 header( 'HTTP/1.1 403 Forbidden' );
370 header( 'Vary: Cookie' );
371 } else {
372 header( 'HTTP/1.1 500 Internal server error' );
373 }
374 if ( $wgShowHostnames ) {
375 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
376 $hostname = htmlspecialchars( wfHostname() );
377 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
378 } else {
379 $debug = "";
380 }
381 echo <<<EOT
382 <html><head><title>Error generating thumbnail</title></head>
383 <body>
384 <h1>Error generating thumbnail</h1>
385 <p>
386 $msg
387 </p>
388 $debug
389 </body>
390 </html>
391
392 EOT;
393 }