merge latest master into Wikidata branch
[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 ( $isTemp ) {
129 $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo();
130 $img = new UnregisteredLocalFile( null, $repo,
131 # Temp files are hashed based on the name without the timestamp.
132 # The thumbnails will be hashed based on the entire name however.
133 # @TODO: fix this convention to actually be reasonable.
134 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
135 );
136 } elseif ( $isOld ) {
137 // Format is <timestamp>!<name>
138 $bits = explode( '!', $fileName, 2 );
139 if ( count( $bits ) != 2 ) {
140 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
141 wfProfileOut( __METHOD__ );
142 return;
143 }
144 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
145 if ( !$title ) {
146 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
147 wfProfileOut( __METHOD__ );
148 return;
149 }
150 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
151 } else {
152 $img = wfLocalFile( $fileName );
153 }
154
155 // Check permissions if there are read restrictions
156 $varyHeader = array();
157 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
158 if ( !$img->getTitle() || !$img->getTitle()->userCan( 'read' ) ) {
159 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
160 'the source file.' );
161 wfProfileOut( __METHOD__ );
162 return;
163 }
164 $headers[] = 'Cache-Control: private';
165 $varyHeader[] = 'Cookie';
166 }
167
168 // Check the source file storage path
169 if ( !$img ) {
170 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
171 wfProfileOut( __METHOD__ );
172 return;
173 }
174 if ( !$img->exists() ) {
175 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
176 wfProfileOut( __METHOD__ );
177 return;
178 }
179 $sourcePath = $img->getPath();
180 if ( $sourcePath === false ) {
181 wfThumbError( 500, 'The source file is not locally accessible.' );
182 wfProfileOut( __METHOD__ );
183 return;
184 }
185
186 // Check IMS against the source file
187 // This means that clients can keep a cached copy even after it has been deleted on the server
188 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
189 // Fix IE brokenness
190 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
191 // Calculate time
192 wfSuppressWarnings();
193 $imsUnix = strtotime( $imsString );
194 wfRestoreWarnings();
195 $sourceTsUnix = wfTimestamp( TS_UNIX, $img->getTimestamp() );
196 if ( $sourceTsUnix <= $imsUnix ) {
197 header( 'HTTP/1.1 304 Not Modified' );
198 wfProfileOut( __METHOD__ );
199 return;
200 }
201 }
202
203 $thumbName = $img->thumbName( $params );
204 if ( !strlen( $thumbName ) ) { // invalid params?
205 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
206 wfProfileOut( __METHOD__ );
207 return;
208 }
209
210 $disposition = $img->getThumbDisposition( $thumbName );
211 $headers[] = "Content-Disposition: $disposition";
212
213 // Stream the file if it exists already...
214 try {
215 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
216 // For 404 handled thumbnails, we only use the the base name of the URI
217 // for the thumb params and the parent directory for the source file name.
218 // Check that the zone relative path matches up so squid caches won't pick
219 // up thumbs that would not be purged on source file deletion (bug 34231).
220 if ( isset( $params['rel404'] ) ) { // thumbnail was handled via 404
221 if ( urldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName ) ) {
222 // Request for the canonical thumbnail name
223 } elseif ( urldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName2 ) ) {
224 // Request for the "long" thumbnail name; redirect to canonical name
225 $response = RequestContext::getMain()->getRequest()->response();
226 $response->header( "HTTP/1.1 301 " . HttpStatus::getMessage( 301 ) );
227 $response->header( 'Location: ' . wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
228 $response->header( 'Expires: ' .
229 gmdate( 'D, d M Y H:i:s', time() + 7*86400 ) . ' GMT' );
230 if ( $wgVaryOnXFP ) {
231 $varyHeader[] = 'X-Forwarded-Proto';
232 }
233 if ( count( $varyHeader ) ) {
234 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
235 }
236 wfProfileOut( __METHOD__ );
237 return;
238 } else {
239 wfThumbError( 404, 'The given path of the specified thumbnail is incorrect.' );
240 wfProfileOut( __METHOD__ );
241 return;
242 }
243 }
244 $thumbPath = $img->getThumbPath( $thumbName );
245 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
246 if ( count( $varyHeader ) ) {
247 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
248 }
249 $img->getRepo()->streamFile( $thumbPath, $headers );
250 wfProfileOut( __METHOD__ );
251 return;
252 }
253 } catch ( MWException $e ) {
254 wfThumbError( 500, $e->getHTML() );
255 wfProfileOut( __METHOD__ );
256 return;
257 }
258
259 if ( count( $varyHeader ) ) {
260 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
261 }
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 // Zone URL might be relative ("/images") or protocol-relative ("//lang.site/image")
306 $zoneUriPath = $repo->getZoneHandlerUrl( 'thumb' )
307 ? $repo->getZoneHandlerUrl( 'thumb' ) // custom URL
308 : $repo->getZoneUrl( 'thumb' ); // default to main URL
309 $bits = wfParseUrl( wfExpandUrl( $zoneUriPath, PROTO_INTERNAL ) );
310 if ( $bits && isset( $bits['path'] ) ) {
311 $zoneUriPath = $bits['path'];
312 } else {
313 return null; // not a valid thumbnail URL
314 }
315
316 $hashDirReg = $subdirReg = '';
317 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
318 $subdirReg .= '[0-9a-f]';
319 $hashDirReg .= "$subdirReg/";
320 }
321 $zoneReg = preg_quote( $zoneUriPath ); // regex for thumb zone URI
322
323 // Check if this is a thumbnail of an original in the local file repo
324 if ( preg_match( "!^$zoneReg/((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $uriPath, $m ) ) {
325 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
326 // Check if this is a thumbnail of an temp file in the local file repo
327 } elseif ( preg_match( "!^$zoneReg/(temp/)($hashDirReg([^/]*)/([^/]*))$!", $uriPath, $m ) ) {
328 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
329 } else {
330 return null; // not a valid looking thumbnail request
331 }
332
333 $filename = urldecode( $filename );
334 $thumbname = urldecode( $thumbname );
335
336 $params = array( 'f' => $filename, 'rel404' => $rel );
337 if ( $archOrTemp === 'archive/' ) {
338 $params['archived'] = 1;
339 } elseif ( $archOrTemp === 'temp/' ) {
340 $params['temp'] = 1;
341 }
342
343 // Check if the parameters can be extracted from the thumbnail name...
344 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
345 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
346 $params['width'] = $size;
347 if ( $pagenum ) {
348 $params['page'] = $pagenum;
349 }
350 return $params; // valid thumbnail URL
351 // Hooks return false if they manage to *resolve* the parameters
352 } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
353 return $params; // valid thumbnail URL (via extension or config)
354 }
355
356 return null; // not a valid thumbnail URL
357 }
358
359 /**
360 * Output a thumbnail generation error message
361 *
362 * @param $status integer
363 * @param $msg string
364 * @return void
365 */
366 function wfThumbError( $status, $msg ) {
367 global $wgShowHostnames;
368
369 header( 'Cache-Control: no-cache' );
370 header( 'Content-Type: text/html; charset=utf-8' );
371 if ( $status == 404 ) {
372 header( 'HTTP/1.1 404 Not found' );
373 } elseif ( $status == 403 ) {
374 header( 'HTTP/1.1 403 Forbidden' );
375 header( 'Vary: Cookie' );
376 } else {
377 header( 'HTTP/1.1 500 Internal server error' );
378 }
379 if ( $wgShowHostnames ) {
380 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
381 $hostname = htmlspecialchars( wfHostname() );
382 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
383 } else {
384 $debug = "";
385 }
386 echo <<<EOT
387 <html><head><title>Error generating thumbnail</title></head>
388 <body>
389 <h1>Error generating thumbnail</h1>
390 <p>
391 $msg
392 </p>
393 $debug
394 </body>
395 </html>
396
397 EOT;
398 }