Merge "Use LogEntry to add new undeletion log entries."
[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( dirname( __FILE__ ) . '/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 $uri = str_replace( "%2F", "/", urlencode( $_SERVER['REDIRECT_URL'] ) );
69 # Just get the URI path (REDIRECT_URL is either a full URL or a path)
70 if ( $uri[0] !== '/' ) {
71 $bits = wfParseUrl( $uri );
72 if ( $bits && isset( $bits['path'] ) ) {
73 $uri = $bits['path'];
74 }
75 }
76 } else {
77 $uri = $_SERVER['REQUEST_URI'];
78 }
79
80 $params = wfExtractThumbParams( $uri ); // basic wiki URL param extracting
81 if ( $params == null ) {
82 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
83 return;
84 }
85
86 wfStreamThumb( $params ); // stream the thumbnail
87 }
88
89 /**
90 * Stream a thumbnail specified by parameters
91 *
92 * @param $params Array
93 * @return void
94 */
95 function wfStreamThumb( array $params ) {
96 wfProfileIn( __METHOD__ );
97
98 $headers = array(); // HTTP headers to send
99
100 $fileName = isset( $params['f'] ) ? $params['f'] : '';
101 unset( $params['f'] );
102
103 // Backwards compatibility parameters
104 if ( isset( $params['w'] ) ) {
105 $params['width'] = $params['w'];
106 unset( $params['w'] );
107 }
108 if ( isset( $params['p'] ) ) {
109 $params['page'] = $params['p'];
110 }
111 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
112
113 // Is this a thumb of an archived file?
114 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
115 unset( $params['archived'] ); // handlers don't care
116
117 // Is this a thumb of a temp file?
118 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
119 unset( $params['temp'] ); // handlers don't care
120
121 // Some basic input validation
122 $fileName = strtr( $fileName, '\\/', '__' );
123
124 // Actually fetch the image. Method depends on whether it is archived or not.
125 if ( $isOld ) {
126 // Format is <timestamp>!<name>
127 $bits = explode( '!', $fileName, 2 );
128 if ( count( $bits ) != 2 ) {
129 wfThumbError( 404, wfMsg( 'badtitletext' ) );
130 wfProfileOut( __METHOD__ );
131 return;
132 }
133 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
134 if ( !$title ) {
135 wfThumbError( 404, wfMsg( 'badtitletext' ) );
136 wfProfileOut( __METHOD__ );
137 return;
138 }
139 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
140 } elseif ( $isTemp ) {
141 $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo();
142 // Format is <timestamp>!<name> or just <name>
143 $bits = explode( '!', $fileName, 2 );
144 // Get the name without the timestamp so hash paths are correctly computed
145 $title = Title::makeTitleSafe( NS_FILE, isset( $bits[1] ) ? $bits[1] : $fileName );
146 if ( !$title ) {
147 wfThumbError( 404, wfMsg( 'badtitletext' ) );
148 wfProfileOut( __METHOD__ );
149 return;
150 }
151 $img = new UnregisteredLocalFile( $title, $repo,
152 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
153 );
154 } else {
155 $img = wfLocalFile( $fileName );
156 }
157
158 // Check permissions if there are read restrictions
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 wfProfileOut( __METHOD__ );
164 return;
165 }
166 $headers[] = 'Cache-Control: private';
167 $headers[] = 'Vary: Cookie';
168 }
169
170 // Check the source file storage path
171 if ( !$img ) {
172 wfThumbError( 404, wfMsg( 'badtitletext' ) );
173 wfProfileOut( __METHOD__ );
174 return;
175 }
176 if ( !$img->exists() ) {
177 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
178 wfProfileOut( __METHOD__ );
179 return;
180 }
181 $sourcePath = $img->getPath();
182 if ( $sourcePath === false ) {
183 wfThumbError( 500, 'The source file is not locally accessible.' );
184 wfProfileOut( __METHOD__ );
185 return;
186 }
187
188 // Check IMS against the source file
189 // This means that clients can keep a cached copy even after it has been deleted on the server
190 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
191 // Fix IE brokenness
192 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
193 // Calculate time
194 wfSuppressWarnings();
195 $imsUnix = strtotime( $imsString );
196 wfRestoreWarnings();
197 $sourceTsUnix = wfTimestamp( TS_UNIX, $img->getTimestamp() );
198 if ( $sourceTsUnix <= $imsUnix ) {
199 header( 'HTTP/1.1 304 Not Modified' );
200 wfProfileOut( __METHOD__ );
201 return;
202 }
203 }
204
205 // Stream the file if it exists already...
206 try {
207 $thumbName = $img->thumbName( $params );
208 if ( strlen( $thumbName ) ) { // valid params?
209 // For 404 handled thumbnails, we only use the the base name of the URI
210 // for the thumb params and the parent directory for the source file name.
211 // Check that the zone relative path matches up so squid caches won't pick
212 // up thumbs that would not be purged on source file deletion (bug 34231).
213 if ( isset( $params['rel404'] ) // thumbnail was handled via 404
214 && urldecode( $params['rel404'] ) !== $img->getThumbRel( $thumbName ) )
215 {
216 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
217 wfProfileOut( __METHOD__ );
218 return;
219 }
220 $thumbPath = $img->getThumbPath( $thumbName );
221 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
222 $img->getRepo()->streamFile( $thumbPath, $headers );
223 wfProfileOut( __METHOD__ );
224 return;
225 }
226 }
227 } catch ( MWException $e ) {
228 wfThumbError( 500, $e->getHTML() );
229 wfProfileOut( __METHOD__ );
230 return;
231 }
232
233 // Thumbnail isn't already there, so create the new thumbnail...
234 try {
235 $thumb = $img->transform( $params, File::RENDER_NOW );
236 } catch ( Exception $ex ) {
237 // Tried to select a page on a non-paged file?
238 $thumb = false;
239 }
240
241 // Check for thumbnail generation errors...
242 $errorMsg = false;
243 if ( !$thumb ) {
244 $errorMsg = wfMsgHtml( 'thumbnail_error', 'File::transform() returned false' );
245 } elseif ( $thumb->isError() ) {
246 $errorMsg = $thumb->getHtmlMsg();
247 } elseif ( !$thumb->hasFile() ) {
248 $errorMsg = wfMsgHtml( 'thumbnail_error', 'No path supplied in thumbnail object' );
249 } elseif ( $thumb->fileIsSource() ) {
250 $errorMsg = wfMsgHtml( 'thumbnail_error',
251 'Image was not scaled, is the requested width bigger than the source?' );
252 }
253
254 if ( $errorMsg !== false ) {
255 wfThumbError( 500, $errorMsg );
256 } else {
257 // Stream the file if there were no errors
258 $thumb->streamFile( $headers );
259 }
260
261 wfProfileOut( __METHOD__ );
262 }
263
264 /**
265 * Extract the required params for thumb.php from the thumbnail request URI.
266 * At least 'width' and 'f' should be set if the result is an array.
267 *
268 * @param $uri String Thumbnail request URI path
269 * @return Array|null associative params array or null
270 */
271 function wfExtractThumbParams( $uri ) {
272 $repo = RepoGroup::singleton()->getLocalRepo();
273
274 $zoneURI = $repo->getZoneUrl( 'thumb' );
275 if ( substr( $zoneURI, 0, 1 ) !== '/' ) {
276 $bits = wfParseUrl( $zoneURI );
277 if ( $bits && isset( $bits['path'] ) ) {
278 $zoneURI = $bits['path'];
279 } else {
280 return null;
281 }
282 }
283 $zoneUrlRegex = preg_quote( $zoneURI );
284
285 $hashDirRegex = $subdirRegex = '';
286 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
287 $subdirRegex .= '[0-9a-f]';
288 $hashDirRegex .= "$subdirRegex/";
289 }
290
291 $thumbUrlRegex = "!^$zoneUrlRegex/((archive/|temp/)?$hashDirRegex([^/]*)/([^/]*))$!";
292
293 // Check if this is a valid looking thumbnail request...
294 if ( preg_match( $thumbUrlRegex, $uri, $matches ) ) {
295 list( /* all */, $rel, $archOrTemp, $filename, $thumbname ) = $matches;
296 $filename = urldecode( $filename );
297 $thumbname = urldecode( $thumbname );
298
299 $params = array( 'f' => $filename, 'rel404' => $rel );
300 if ( $archOrTemp == 'archive/' ) {
301 $params['archived'] = 1;
302 } elseif ( $archOrTemp == 'temp/' ) {
303 $params['temp'] = 1;
304 }
305
306 // Check if the parameters can be extracted from the thumbnail name...
307 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
308 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
309 $params['width'] = $size;
310 if ( $pagenum ) {
311 $params['page'] = $pagenum;
312 }
313 return $params; // valid thumbnail URL
314 // Hooks return false if they manage to *resolve* the parameters
315 } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
316 return $params; // valid thumbnail URL (via extension or config)
317 }
318 }
319
320 return null; // not a valid thumbnail URL
321 }
322
323 /**
324 * Output a thumbnail generation error message
325 *
326 * @param $status integer
327 * @param $msg string
328 * @return void
329 */
330 function wfThumbError( $status, $msg ) {
331 global $wgShowHostnames;
332
333 header( 'Cache-Control: no-cache' );
334 header( 'Content-Type: text/html; charset=utf-8' );
335 if ( $status == 404 ) {
336 header( 'HTTP/1.1 404 Not found' );
337 } elseif ( $status == 403 ) {
338 header( 'HTTP/1.1 403 Forbidden' );
339 header( 'Vary: Cookie' );
340 } else {
341 header( 'HTTP/1.1 500 Internal server error' );
342 }
343 if ( $wgShowHostnames ) {
344 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
345 $hostname = htmlspecialchars( wfHostname() );
346 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
347 } else {
348 $debug = "";
349 }
350 echo <<<EOT
351 <html><head><title>Error generating thumbnail</title></head>
352 <body>
353 <h1>Error generating thumbnail</h1>
354 <p>
355 $msg
356 </p>
357 $debug
358 </body>
359 </html>
360
361 EOT;
362 }