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