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