thumb.php now handles short and long thumbnail name formats when possible.
[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 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 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
163 if ( !$img->getTitle() || !$img->getTitle()->userCan( 'read' ) ) {
164 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
165 'the source file.' );
166 wfProfileOut( __METHOD__ );
167 return;
168 }
169 $headers[] = 'Cache-Control: private';
170 $headers[] = 'Vary: Cookie';
171 }
172
173 // Check the source file storage path
174 if ( !$img ) {
175 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
176 wfProfileOut( __METHOD__ );
177 return;
178 }
179 if ( !$img->exists() ) {
180 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
181 wfProfileOut( __METHOD__ );
182 return;
183 }
184 $sourcePath = $img->getPath();
185 if ( $sourcePath === false ) {
186 wfThumbError( 500, 'The source file is not locally accessible.' );
187 wfProfileOut( __METHOD__ );
188 return;
189 }
190
191 // Check IMS against the source file
192 // This means that clients can keep a cached copy even after it has been deleted on the server
193 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
194 // Fix IE brokenness
195 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
196 // Calculate time
197 wfSuppressWarnings();
198 $imsUnix = strtotime( $imsString );
199 wfRestoreWarnings();
200 $sourceTsUnix = wfTimestamp( TS_UNIX, $img->getTimestamp() );
201 if ( $sourceTsUnix <= $imsUnix ) {
202 header( 'HTTP/1.1 304 Not Modified' );
203 wfProfileOut( __METHOD__ );
204 return;
205 }
206 }
207
208 $thumbName = $img->thumbName( $params );
209 if ( !strlen( $thumbName ) ) { // invalid params?
210 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
211 wfProfileOut( __METHOD__ );
212 return;
213 }
214
215 $disposition = $img->getThumbDisposition( $thumbName );
216 $headers[] = "Content-Disposition: $disposition";
217
218 // Stream the file if it exists already...
219 try {
220 $thumbName2 = $img->thumbName( $params, File::THUMB_FULL_NAME ); // b/c; "long" style
221 // For 404 handled thumbnails, we only use the the base name of the URI
222 // for the thumb params and the parent directory for the source file name.
223 // Check that the zone relative path matches up so squid caches won't pick
224 // up thumbs that would not be purged on source file deletion (bug 34231).
225 if ( isset( $params['rel404'] ) ) { // thumbnail was handled via 404
226 if ( urldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName ) ) {
227 // Request for the canonical thumbnail name
228 } elseif ( urldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName2 ) ) {
229 // Request for the "long" thumbnail name; redirect to canonical name
230 $response = RequestContext::getMain()->getRequest()->response();
231 $response->header( "HTTP/1.1 301 " . HttpStatus::getMessage( 301 ) );
232 $response->header( 'Location: ' . wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT ) );
233 $response->header( 'Expires: ' .
234 gmdate( 'D, d M Y H:i:s', time() + 7*86400 ) . ' GMT' );
235 } else {
236 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
237 wfProfileOut( __METHOD__ );
238 return;
239 }
240 }
241 $thumbPath = $img->getThumbPath( $thumbName );
242 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
243 $img->getRepo()->streamFile( $thumbPath, $headers );
244 wfProfileOut( __METHOD__ );
245 return;
246 }
247 } catch ( MWException $e ) {
248 wfThumbError( 500, $e->getHTML() );
249 wfProfileOut( __METHOD__ );
250 return;
251 }
252
253 // Thumbnail isn't already there, so create the new thumbnail...
254 try {
255 $thumb = $img->transform( $params, File::RENDER_NOW );
256 } catch ( Exception $ex ) {
257 // Tried to select a page on a non-paged file?
258 $thumb = false;
259 }
260
261 // Check for thumbnail generation errors...
262 $errorMsg = false;
263 $msg = wfMessage( 'thumbnail_error' );
264 if ( !$thumb ) {
265 $errorMsg = $msg->rawParams( 'File::transform() returned false' )->escaped();
266 } elseif ( $thumb->isError() ) {
267 $errorMsg = $thumb->getHtmlMsg();
268 } elseif ( !$thumb->hasFile() ) {
269 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
270 } elseif ( $thumb->fileIsSource() ) {
271 $errorMsg = $msg->
272 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
273 }
274
275 if ( $errorMsg !== false ) {
276 wfThumbError( 500, $errorMsg );
277 } else {
278 // Stream the file if there were no errors
279 $thumb->streamFile( $headers );
280 }
281
282 wfProfileOut( __METHOD__ );
283 }
284
285 /**
286 * Extract the required params for thumb.php from the thumbnail request URI.
287 * At least 'width' and 'f' should be set if the result is an array.
288 *
289 * @param $uriPath String Thumbnail request URI path
290 * @return Array|null associative params array or null
291 */
292 function wfExtractThumbParams( $uriPath ) {
293 $repo = RepoGroup::singleton()->getLocalRepo();
294
295 $zoneUriPath = $repo->getZoneHandlerUrl( 'thumb' )
296 ? $repo->getZoneHandlerUrl( 'thumb' ) // custom URL
297 : $repo->getZoneUrl( 'thumb' ); // default to main URL
298 // URL might be relative ("/images") or protocol-relative ("//lang.site/image")
299 $bits = wfParseUrl( wfExpandUrl( $zoneUriPath, PROTO_INTERNAL ) );
300 if ( $bits && isset( $bits['path'] ) ) {
301 $zoneUriPath = $bits['path'];
302 } else {
303 return null;
304 }
305
306 $hashDirRegex = $subdirRegex = '';
307 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
308 $subdirRegex .= '[0-9a-f]';
309 $hashDirRegex .= "$subdirRegex/";
310 }
311
312 $thumbPathRegex = "!^" . preg_quote( $zoneUriPath ) .
313 "/((archive/|temp/)?$hashDirRegex([^/]*)/([^/]*))$!";
314
315 // Check if this is a valid looking thumbnail request...
316 if ( preg_match( $thumbPathRegex, $uriPath, $matches ) ) {
317 list( /* all */, $rel, $archOrTemp, $filename, $thumbname ) = $matches;
318 $filename = urldecode( $filename );
319 $thumbname = urldecode( $thumbname );
320
321 $params = array( 'f' => $filename, 'rel404' => $rel );
322 if ( $archOrTemp == 'archive/' ) {
323 $params['archived'] = 1;
324 } elseif ( $archOrTemp == 'temp/' ) {
325 $params['temp'] = 1;
326 }
327
328 // Check if the parameters can be extracted from the thumbnail name...
329 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
330 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
331 $params['width'] = $size;
332 if ( $pagenum ) {
333 $params['page'] = $pagenum;
334 }
335 return $params; // valid thumbnail URL
336 // Hooks return false if they manage to *resolve* the parameters
337 } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
338 return $params; // valid thumbnail URL (via extension or config)
339 }
340 }
341
342 return null; // not a valid thumbnail URL
343 }
344
345 /**
346 * Output a thumbnail generation error message
347 *
348 * @param $status integer
349 * @param $msg string
350 * @return void
351 */
352 function wfThumbError( $status, $msg ) {
353 global $wgShowHostnames;
354
355 header( 'Cache-Control: no-cache' );
356 header( 'Content-Type: text/html; charset=utf-8' );
357 if ( $status == 404 ) {
358 header( 'HTTP/1.1 404 Not found' );
359 } elseif ( $status == 403 ) {
360 header( 'HTTP/1.1 403 Forbidden' );
361 header( 'Vary: Cookie' );
362 } else {
363 header( 'HTTP/1.1 500 Internal server error' );
364 }
365 if ( $wgShowHostnames ) {
366 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
367 $hostname = htmlspecialchars( wfHostname() );
368 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
369 } else {
370 $debug = "";
371 }
372 echo <<<EOT
373 <html><head><title>Error generating thumbnail</title></head>
374 <body>
375 <h1>Error generating thumbnail</h1>
376 <p>
377 $msg
378 </p>
379 $debug
380 </body>
381 </html>
382
383 EOT;
384 }