Added some simple path validation to resolveContainerPath() in FSFileBackend. This...
[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( 'phase3/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'] );
101
102 // Some basic input validation
103 $fileName = strtr( $fileName, '\\/', '__' );
104
105 // Actually fetch the image. Method depends on whether it is archived or not.
106 if ( $isOld ) {
107 // Format is <timestamp>!<name>
108 $bits = explode( '!', $fileName, 2 );
109 if ( count( $bits ) != 2 ) {
110 wfThumbError( 404, wfMsg( 'badtitletext' ) );
111 wfProfileOut( __METHOD__ );
112 return;
113 }
114 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
115 if ( !$title ) {
116 wfThumbError( 404, wfMsg( 'badtitletext' ) );
117 wfProfileOut( __METHOD__ );
118 return;
119 }
120 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
121 } else {
122 $img = wfLocalFile( $fileName );
123 }
124
125 // Check permissions if there are read restrictions
126 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
127 if ( !$img->getTitle()->userCan( 'read' ) ) {
128 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
129 'the source file.' );
130 wfProfileOut( __METHOD__ );
131 return;
132 }
133 $headers[] = 'Cache-Control: private';
134 $headers[] = 'Vary: Cookie';
135 }
136
137 // Check the source file storage path
138 if ( !$img ) {
139 wfThumbError( 404, wfMsg( 'badtitletext' ) );
140 wfProfileOut( __METHOD__ );
141 return;
142 }
143 if ( !$img->exists() ) {
144 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
145 wfProfileOut( __METHOD__ );
146 return;
147 }
148 $sourcePath = $img->getPath();
149 if ( $sourcePath === false ) {
150 wfThumbError( 500, 'The source file is not locally accessible.' );
151 wfProfileOut( __METHOD__ );
152 return;
153 }
154
155 // Check IMS against the source file
156 // This means that clients can keep a cached copy even after it has been deleted on the server
157 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
158 // Fix IE brokenness
159 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
160 // Calculate time
161 wfSuppressWarnings();
162 $imsUnix = strtotime( $imsString );
163 wfRestoreWarnings();
164 $sourceTsUnix = wfTimestamp( TS_UNIX, $img->getTimestamp() );
165 if ( $sourceTsUnix <= $imsUnix ) {
166 header( 'HTTP/1.1 304 Not Modified' );
167 wfProfileOut( __METHOD__ );
168 return;
169 }
170 }
171
172 // Stream the file if it exists already...
173 try {
174 $thumbName = $img->thumbName( $params );
175 if ( strlen( $thumbName ) ) { // valid params?
176 $thumbPath = $img->getThumbPath( $thumbName );
177 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
178 $img->getRepo()->streamFile( $thumbPath, $headers );
179 wfProfileOut( __METHOD__ );
180 return;
181 }
182 }
183 } catch ( MWException $e ) {
184 wfThumbError( 500, $e->getHTML() );
185 wfProfileOut( __METHOD__ );
186 return;
187 }
188
189 // Thumbnail isn't already there, so create the new thumbnail...
190 try {
191 $thumb = $img->transform( $params, File::RENDER_NOW );
192 } catch ( Exception $ex ) {
193 // Tried to select a page on a non-paged file?
194 $thumb = false;
195 }
196
197 // Check for thumbnail generation errors...
198 $errorMsg = false;
199 if ( !$thumb ) {
200 $errorMsg = wfMsgHtml( 'thumbnail_error', 'File::transform() returned false' );
201 } elseif ( $thumb->isError() ) {
202 $errorMsg = $thumb->getHtmlMsg();
203 } elseif ( !$thumb->hasFile() ) {
204 $errorMsg = wfMsgHtml( 'thumbnail_error', 'No path supplied in thumbnail object' );
205 } elseif ( $thumb->fileIsSource() ) {
206 $errorMsg = wfMsgHtml( 'thumbnail_error',
207 'Image was not scaled, is the requested width bigger than the source?' );
208 }
209
210 if ( $errorMsg !== false ) {
211 wfThumbError( 500, $errorMsg );
212 } else {
213 // Stream the file if there were no errors
214 $thumb->streamFile( $headers );
215 }
216
217 wfProfileOut( __METHOD__ );
218 }
219
220 /**
221 * Extract the required params for thumb.php from the thumbnail request URI.
222 * At least 'width' and 'f' should be set if the result is an array.
223 *
224 * @param $uri String Thumbnail request URI path
225 * @return Array|null associative params array or null
226 */
227 function wfExtractThumbParams( $uri ) {
228 $repo = RepoGroup::singleton()->getLocalRepo();
229
230 $zoneURI = $repo->getZoneUrl( 'thumb' );
231 if ( substr( $zoneURI, 0, 1 ) !== '/' ) {
232 $bits = wfParseUrl( $zoneURI );
233 if ( $bits && isset( $bits['path'] ) ) {
234 $zoneURI = $bits['path'];
235 } else {
236 return null;
237 }
238 }
239 $zoneUrlRegex = preg_quote( $zoneURI );
240
241 $hashDirRegex = $subdirRegex = '';
242 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
243 $subdirRegex .= '[0-9a-f]';
244 $hashDirRegex .= "$subdirRegex/";
245 }
246
247 $thumbUrlRegex = "!^$zoneUrlRegex(/archive|/temp|)/$hashDirRegex([^/]*)/([^/]*)$!";
248
249 // Check if this is a valid looking thumbnail request...
250 if ( preg_match( $thumbUrlRegex, $uri, $matches ) ) {
251 list( /* all */, $archOrTemp, $filename, $thumbname ) = $matches;
252 $filename = urldecode( $filename );
253 $thumbname = urldecode( $thumbname );
254
255 $params = array( 'f' => $filename );
256 if ( $archOrTemp == '/archive' ) {
257 $params['archived'] = 1;
258 } elseif ( $archOrTemp == '/temp' ) {
259 $params['temp'] = 1;
260 }
261
262 // Check if the parameters can be extracted from the thumbnail name...
263 // @TODO: remove 'page' stuff and make ProofreadPage handle it via hook.
264 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
265 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
266 $params['width'] = $size;
267 if ( $pagenum ) {
268 $params['page'] = $pagenum;
269 }
270 return $params; // valid thumbnail URL
271 // Hooks return false if they manage to *resolve* the parameters
272 } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
273 return $params; // valid thumbnail URL (via extension or config)
274 }
275 }
276
277 return null; // not a valid thumbnail URL
278 }
279
280 /**
281 * Output a thumbnail generation error message
282 *
283 * @param $status integer
284 * @param $msg string
285 * @return void
286 */
287 function wfThumbError( $status, $msg ) {
288 global $wgShowHostnames;
289
290 header( 'Cache-Control: no-cache' );
291 header( 'Content-Type: text/html; charset=utf-8' );
292 if ( $status == 404 ) {
293 header( 'HTTP/1.1 404 Not found' );
294 } elseif ( $status == 403 ) {
295 header( 'HTTP/1.1 403 Forbidden' );
296 header( 'Vary: Cookie' );
297 } else {
298 header( 'HTTP/1.1 500 Internal server error' );
299 }
300 if ( $wgShowHostnames ) {
301 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
302 $hostname = htmlspecialchars( wfHostname() );
303 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
304 } else {
305 $debug = "";
306 }
307 echo <<<EOT
308 <html><head><title>Error generating thumbnail</title></head>
309 <body>
310 <h1>Error generating thumbnail</h1>
311 <p>
312 $msg
313 </p>
314 $debug
315 </body>
316 </html>
317
318 EOT;
319 }