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