merged master (2012-09-11)
[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 wfProfileIn( __METHOD__ );
99
100 $headers = array(); // HTTP headers to send
101
102 $fileName = isset( $params['f'] ) ? $params['f'] : '';
103 unset( $params['f'] );
104
105 // Backwards compatibility parameters
106 if ( isset( $params['w'] ) ) {
107 $params['width'] = $params['w'];
108 unset( $params['w'] );
109 }
110 if ( isset( $params['p'] ) ) {
111 $params['page'] = $params['p'];
112 }
113 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
114
115 // Is this a thumb of an archived file?
116 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
117 unset( $params['archived'] ); // handlers don't care
118
119 // Is this a thumb of a temp file?
120 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
121 unset( $params['temp'] ); // handlers don't care
122
123 // Some basic input validation
124 $fileName = strtr( $fileName, '\\/', '__' );
125
126 // Actually fetch the image. Method depends on whether it is archived or not.
127 if ( $isOld ) {
128 // Format is <timestamp>!<name>
129 $bits = explode( '!', $fileName, 2 );
130 if ( count( $bits ) != 2 ) {
131 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
132 wfProfileOut( __METHOD__ );
133 return;
134 }
135 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
136 if ( !$title ) {
137 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
138 wfProfileOut( __METHOD__ );
139 return;
140 }
141 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
142 } elseif ( $isTemp ) {
143 $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo();
144 // Format is <timestamp>!<name> or just <name>
145 $bits = explode( '!', $fileName, 2 );
146 // Get the name without the timestamp so hash paths are correctly computed
147 $title = Title::makeTitleSafe( NS_FILE, isset( $bits[1] ) ? $bits[1] : $fileName );
148 if ( !$title ) {
149 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
150 wfProfileOut( __METHOD__ );
151 return;
152 }
153 $img = new UnregisteredLocalFile( $title, $repo,
154 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
155 );
156 } else {
157 $img = wfLocalFile( $fileName );
158 }
159
160 // Check permissions if there are read restrictions
161 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
162 if ( !$img->getTitle() || !$img->getTitle()->userCan( 'read' ) ) {
163 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
164 'the source file.' );
165 wfProfileOut( __METHOD__ );
166 return;
167 }
168 $headers[] = 'Cache-Control: private';
169 $headers[] = 'Vary: Cookie';
170 }
171
172 // Check the source file storage path
173 if ( !$img ) {
174 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
175 wfProfileOut( __METHOD__ );
176 return;
177 }
178 if ( !$img->exists() ) {
179 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
180 wfProfileOut( __METHOD__ );
181 return;
182 }
183 $sourcePath = $img->getPath();
184 if ( $sourcePath === false ) {
185 wfThumbError( 500, 'The source file is not locally accessible.' );
186 wfProfileOut( __METHOD__ );
187 return;
188 }
189
190 // Check IMS against the source file
191 // This means that clients can keep a cached copy even after it has been deleted on the server
192 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
193 // Fix IE brokenness
194 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
195 // Calculate time
196 wfSuppressWarnings();
197 $imsUnix = strtotime( $imsString );
198 wfRestoreWarnings();
199 $sourceTsUnix = wfTimestamp( TS_UNIX, $img->getTimestamp() );
200 if ( $sourceTsUnix <= $imsUnix ) {
201 header( 'HTTP/1.1 304 Not Modified' );
202 wfProfileOut( __METHOD__ );
203 return;
204 }
205 }
206
207 $thumbName = $img->thumbName( $params );
208 if ( !strlen( $thumbName ) ) { // invalid params?
209 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
210 wfProfileOut( __METHOD__ );
211 return;
212 }
213
214 $disposition = $img->getThumbDisposition( $thumbName );
215 $headers[] = "Content-Disposition: $disposition";
216
217 // Stream the file if it exists already...
218 try {
219 // For 404 handled thumbnails, we only use the the base name of the URI
220 // for the thumb params and the parent directory for the source file name.
221 // Check that the zone relative path matches up so squid caches won't pick
222 // up thumbs that would not be purged on source file deletion (bug 34231).
223 if ( isset( $params['rel404'] ) // thumbnail was handled via 404
224 && urldecode( $params['rel404'] ) !== $img->getThumbRel( $thumbName ) )
225 {
226 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
227 wfProfileOut( __METHOD__ );
228 return;
229 }
230 $thumbPath = $img->getThumbPath( $thumbName );
231 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
232 $img->getRepo()->streamFile( $thumbPath, $headers );
233 wfProfileOut( __METHOD__ );
234 return;
235 }
236 } catch ( MWException $e ) {
237 wfThumbError( 500, $e->getHTML() );
238 wfProfileOut( __METHOD__ );
239 return;
240 }
241
242 // Thumbnail isn't already there, so create the new thumbnail...
243 try {
244 $thumb = $img->transform( $params, File::RENDER_NOW );
245 } catch ( Exception $ex ) {
246 // Tried to select a page on a non-paged file?
247 $thumb = false;
248 }
249
250 // Check for thumbnail generation errors...
251 $errorMsg = false;
252 $msg = wfMessage( 'thumbnail_error' );
253 if ( !$thumb ) {
254 $errorMsg = $msg->rawParams( 'File::transform() returned false' )->escaped();
255 } elseif ( $thumb->isError() ) {
256 $errorMsg = $thumb->getHtmlMsg();
257 } elseif ( !$thumb->hasFile() ) {
258 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
259 } elseif ( $thumb->fileIsSource() ) {
260 $errorMsg = $msg->
261 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
262 }
263
264 if ( $errorMsg !== false ) {
265 wfThumbError( 500, $errorMsg );
266 } else {
267 // Stream the file if there were no errors
268 $thumb->streamFile( $headers );
269 }
270
271 wfProfileOut( __METHOD__ );
272 }
273
274 /**
275 * Extract the required params for thumb.php from the thumbnail request URI.
276 * At least 'width' and 'f' should be set if the result is an array.
277 *
278 * @param $uriPath String Thumbnail request URI path
279 * @return Array|null associative params array or null
280 */
281 function wfExtractThumbParams( $uriPath ) {
282 $repo = RepoGroup::singleton()->getLocalRepo();
283
284 $zoneUriPath = $repo->getZoneHandlerUrl( 'thumb' )
285 ? $repo->getZoneHandlerUrl( 'thumb' ) // custom URL
286 : $repo->getZoneUrl( 'thumb' ); // default to main URL
287 // URL might be relative ("/images") or protocol-relative ("//lang.site/image")
288 $bits = wfParseUrl( wfExpandUrl( $zoneUriPath, PROTO_INTERNAL ) );
289 if ( $bits && isset( $bits['path'] ) ) {
290 $zoneUriPath = $bits['path'];
291 } else {
292 return null;
293 }
294
295 $hashDirRegex = $subdirRegex = '';
296 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
297 $subdirRegex .= '[0-9a-f]';
298 $hashDirRegex .= "$subdirRegex/";
299 }
300
301 $thumbPathRegex = "!^" . preg_quote( $zoneUriPath ) .
302 "/((archive/|temp/)?$hashDirRegex([^/]*)/([^/]*))$!";
303
304 // Check if this is a valid looking thumbnail request...
305 if ( preg_match( $thumbPathRegex, $uriPath, $matches ) ) {
306 list( /* all */, $rel, $archOrTemp, $filename, $thumbname ) = $matches;
307 $filename = urldecode( $filename );
308 $thumbname = urldecode( $thumbname );
309
310 $params = array( 'f' => $filename, 'rel404' => $rel );
311 if ( $archOrTemp == 'archive/' ) {
312 $params['archived'] = 1;
313 } elseif ( $archOrTemp == 'temp/' ) {
314 $params['temp'] = 1;
315 }
316
317 // Check if the parameters can be extracted from the thumbnail name...
318 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
319 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
320 $params['width'] = $size;
321 if ( $pagenum ) {
322 $params['page'] = $pagenum;
323 }
324 return $params; // valid thumbnail URL
325 // Hooks return false if they manage to *resolve* the parameters
326 } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
327 return $params; // valid thumbnail URL (via extension or config)
328 }
329 }
330
331 return null; // not a valid thumbnail URL
332 }
333
334 /**
335 * Output a thumbnail generation error message
336 *
337 * @param $status integer
338 * @param $msg string
339 * @return void
340 */
341 function wfThumbError( $status, $msg ) {
342 global $wgShowHostnames;
343
344 header( 'Cache-Control: no-cache' );
345 header( 'Content-Type: text/html; charset=utf-8' );
346 if ( $status == 404 ) {
347 header( 'HTTP/1.1 404 Not found' );
348 } elseif ( $status == 403 ) {
349 header( 'HTTP/1.1 403 Forbidden' );
350 header( 'Vary: Cookie' );
351 } else {
352 header( 'HTTP/1.1 500 Internal server error' );
353 }
354 if ( $wgShowHostnames ) {
355 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
356 $hostname = htmlspecialchars( wfHostname() );
357 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
358 } else {
359 $debug = "";
360 }
361 echo <<<EOT
362 <html><head><title>Error generating thumbnail</title></head>
363 <body>
364 <h1>Error generating thumbnail</h1>
365 <p>
366 $msg
367 </p>
368 $debug
369 </body>
370 </html>
371
372 EOT;
373 }