(bug 38110) provide a way to separate out schema changes
[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 ( urldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName ) ) {
219 // Request for the canonical thumbnail name
220 } elseif ( urldecode( $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 wfProfileOut( __METHOD__ );
239 return;
240 }
241 }
242
243 // Suggest a good name for users downloading this thumbnail
244 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName )}";
245
246 if ( count( $varyHeader ) ) {
247 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
248 }
249
250 // Stream the file if it exists already...
251 $thumbPath = $img->getThumbPath( $thumbName );
252 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
253 $img->getRepo()->streamFile( $thumbPath, $headers );
254 wfProfileOut( __METHOD__ );
255 return;
256 }
257
258 // Thumbnail isn't already there, so create the new thumbnail...
259 try {
260 $thumb = $img->transform( $params, File::RENDER_NOW );
261 } catch ( Exception $ex ) {
262 // Tried to select a page on a non-paged file?
263 $thumb = false;
264 }
265
266 // Check for thumbnail generation errors...
267 $errorMsg = false;
268 $msg = wfMessage( 'thumbnail_error' );
269 if ( !$thumb ) {
270 $errorMsg = $msg->rawParams( 'File::transform() returned false' )->escaped();
271 } elseif ( $thumb->isError() ) {
272 $errorMsg = $thumb->getHtmlMsg();
273 } elseif ( !$thumb->hasFile() ) {
274 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
275 } elseif ( $thumb->fileIsSource() ) {
276 $errorMsg = $msg->
277 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
278 }
279
280 if ( $errorMsg !== false ) {
281 wfThumbError( 500, $errorMsg );
282 } else {
283 // Stream the file if there were no errors
284 $thumb->streamFile( $headers );
285 }
286
287 wfProfileOut( __METHOD__ );
288 }
289
290 /**
291 * Extract the required params for thumb.php from the thumbnail request URI.
292 * At least 'width' and 'f' should be set if the result is an array.
293 *
294 * @param $thumbRel String Thumbnail path relative to the thumb zone
295 * @return Array|null associative params array or null
296 */
297 function wfExtractThumbParams( $thumbRel ) {
298 $repo = RepoGroup::singleton()->getLocalRepo();
299
300 $hashDirReg = $subdirReg = '';
301 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
302 $subdirReg .= '[0-9a-f]';
303 $hashDirReg .= "$subdirReg/";
304 }
305
306 // Check if this is a thumbnail of an original in the local file repo
307 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
308 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
309 // Check if this is a thumbnail of an temp file in the local file repo
310 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
311 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
312 } else {
313 return null; // not a valid looking thumbnail request
314 }
315
316 $params = array( 'f' => $filename, 'rel404' => $rel );
317 if ( $archOrTemp === 'archive/' ) {
318 $params['archived'] = 1;
319 } elseif ( $archOrTemp === 'temp/' ) {
320 $params['temp'] = 1;
321 }
322
323 // Check hooks if parameters can be extracted
324 // Hooks return false if they manage to *resolve* the parameters
325 if ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
326 return $params; // valid thumbnail URL (via extension or config)
327 // Check if the parameters can be extracted from the thumbnail name...
328 } elseif ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
329 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
330 $params['width'] = $size;
331 if ( $pagenum ) {
332 $params['page'] = $pagenum;
333 }
334 return $params; // valid thumbnail URL
335 }
336
337 return null; // not a valid thumbnail URL
338 }
339
340 /**
341 * Output a thumbnail generation error message
342 *
343 * @param $status integer
344 * @param $msg string
345 * @return void
346 */
347 function wfThumbError( $status, $msg ) {
348 global $wgShowHostnames;
349
350 header( 'Cache-Control: no-cache' );
351 header( 'Content-Type: text/html; charset=utf-8' );
352 if ( $status == 404 ) {
353 header( 'HTTP/1.1 404 Not found' );
354 } elseif ( $status == 403 ) {
355 header( 'HTTP/1.1 403 Forbidden' );
356 header( 'Vary: Cookie' );
357 } else {
358 header( 'HTTP/1.1 500 Internal server error' );
359 }
360 if ( $wgShowHostnames ) {
361 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
362 $hostname = htmlspecialchars( wfHostname() );
363 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
364 } else {
365 $debug = "";
366 }
367 echo <<<EOT
368 <html><head><title>Error generating thumbnail</title></head>
369 <body>
370 <h1>Error generating thumbnail</h1>
371 <p>
372 $msg
373 </p>
374 $debug
375 </body>
376 </html>
377
378 EOT;
379 }