split general cache helper functionality to its own class, so we can also easily...
[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() || !$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 // For 404 handled thumbnails, we only use the the base name of the URI
177 // for the thumb params and the parent directory for the source file name.
178 // Check that the zone relative path matches up so squid caches won't pick
179 // up thumbs that would not be purged on source file deletion (bug 34231).
180 if ( isset( $params['rel404'] ) // thumbnail was handled via 404
181 && urldecode( $params['rel404'] ) !== $img->getThumbRel( $thumbName ) )
182 {
183 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
184 wfProfileOut( __METHOD__ );
185 return;
186 }
187 $thumbPath = $img->getThumbPath( $thumbName );
188 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
189 $img->getRepo()->streamFile( $thumbPath, $headers );
190 wfProfileOut( __METHOD__ );
191 return;
192 }
193 }
194 } catch ( MWException $e ) {
195 wfThumbError( 500, $e->getHTML() );
196 wfProfileOut( __METHOD__ );
197 return;
198 }
199
200 // Thumbnail isn't already there, so create the new thumbnail...
201 try {
202 $thumb = $img->transform( $params, File::RENDER_NOW );
203 } catch ( Exception $ex ) {
204 // Tried to select a page on a non-paged file?
205 $thumb = false;
206 }
207
208 // Check for thumbnail generation errors...
209 $errorMsg = false;
210 if ( !$thumb ) {
211 $errorMsg = wfMsgHtml( 'thumbnail_error', 'File::transform() returned false' );
212 } elseif ( $thumb->isError() ) {
213 $errorMsg = $thumb->getHtmlMsg();
214 } elseif ( !$thumb->hasFile() ) {
215 $errorMsg = wfMsgHtml( 'thumbnail_error', 'No path supplied in thumbnail object' );
216 } elseif ( $thumb->fileIsSource() ) {
217 $errorMsg = wfMsgHtml( 'thumbnail_error',
218 'Image was not scaled, is the requested width bigger than the source?' );
219 }
220
221 if ( $errorMsg !== false ) {
222 wfThumbError( 500, $errorMsg );
223 } else {
224 // Stream the file if there were no errors
225 $thumb->streamFile( $headers );
226 }
227
228 wfProfileOut( __METHOD__ );
229 }
230
231 /**
232 * Extract the required params for thumb.php from the thumbnail request URI.
233 * At least 'width' and 'f' should be set if the result is an array.
234 *
235 * @param $uri String Thumbnail request URI path
236 * @return Array|null associative params array or null
237 */
238 function wfExtractThumbParams( $uri ) {
239 $repo = RepoGroup::singleton()->getLocalRepo();
240
241 $zoneURI = $repo->getZoneUrl( 'thumb' );
242 if ( substr( $zoneURI, 0, 1 ) !== '/' ) {
243 $bits = wfParseUrl( $zoneURI );
244 if ( $bits && isset( $bits['path'] ) ) {
245 $zoneURI = $bits['path'];
246 } else {
247 return null;
248 }
249 }
250 $zoneUrlRegex = preg_quote( $zoneURI );
251
252 $hashDirRegex = $subdirRegex = '';
253 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
254 $subdirRegex .= '[0-9a-f]';
255 $hashDirRegex .= "$subdirRegex/";
256 }
257
258 $thumbUrlRegex = "!^$zoneUrlRegex/((archive/|temp/)?$hashDirRegex([^/]*)/([^/]*))$!";
259
260 // Check if this is a valid looking thumbnail request...
261 if ( preg_match( $thumbUrlRegex, $uri, $matches ) ) {
262 list( /* all */, $rel, $archOrTemp, $filename, $thumbname ) = $matches;
263 $filename = urldecode( $filename );
264 $thumbname = urldecode( $thumbname );
265
266 $params = array( 'f' => $filename, 'rel404' => $rel );
267 if ( $archOrTemp == 'archive/' ) {
268 $params['archived'] = 1;
269 } elseif ( $archOrTemp == 'temp/' ) {
270 $params['temp'] = 1;
271 }
272
273 // Check if the parameters can be extracted from the thumbnail name...
274 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
275 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
276 $params['width'] = $size;
277 if ( $pagenum ) {
278 $params['page'] = $pagenum;
279 }
280 return $params; // valid thumbnail URL
281 // Hooks return false if they manage to *resolve* the parameters
282 } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
283 return $params; // valid thumbnail URL (via extension or config)
284 }
285 }
286
287 return null; // not a valid thumbnail URL
288 }
289
290 /**
291 * Output a thumbnail generation error message
292 *
293 * @param $status integer
294 * @param $msg string
295 * @return void
296 */
297 function wfThumbError( $status, $msg ) {
298 global $wgShowHostnames;
299
300 header( 'Cache-Control: no-cache' );
301 header( 'Content-Type: text/html; charset=utf-8' );
302 if ( $status == 404 ) {
303 header( 'HTTP/1.1 404 Not found' );
304 } elseif ( $status == 403 ) {
305 header( 'HTTP/1.1 403 Forbidden' );
306 header( 'Vary: Cookie' );
307 } else {
308 header( 'HTTP/1.1 500 Internal server error' );
309 }
310 if ( $wgShowHostnames ) {
311 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
312 $hostname = htmlspecialchars( wfHostname() );
313 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
314 } else {
315 $debug = "";
316 }
317 echo <<<EOT
318 <html><head><title>Error generating thumbnail</title></head>
319 <body>
320 <h1>Error generating thumbnail</h1>
321 <p>
322 $msg
323 </p>
324 $debug
325 </body>
326 </html>
327
328 EOT;
329 }