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