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