4 * PHP script to stream out an image thumbnail.
9 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
10 if ( isset( $_SERVER['MW_COMPILED'] ) ) {
11 require( 'core/includes/WebStart.php' );
13 require( dirname( __FILE__
) . '/includes/WebStart.php' );
16 // Don't use fancy mime detection, just check the file extension for jpg/gif/png
17 $wgTrivialMimeDetection = true;
19 if ( defined( 'THUMB_HANDLER' ) ) {
20 // Called from thumb_handler.php via 404; extract params from the URI...
23 // Called directly, use $_REQUEST params
24 wfThumbHandleRequest();
28 //--------------------------------------------------------------------------
31 * Handle a thumbnail request via query parameters
35 function wfThumbHandleRequest() {
36 $params = get_magic_quotes_gpc()
37 ?
array_map( 'stripslashes', $_REQUEST )
40 wfStreamThumb( $params ); // stream the thumbnail
44 * Handle a thumbnail request via thumbnail file URL
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'] ) ) {
62 $uri = $_SERVER['REQUEST_URI'];
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.' );
71 wfStreamThumb( $params ); // stream the thumbnail
75 * Stream a thumbnail specified by parameters
77 * @param $params Array
80 function wfStreamThumb( array $params ) {
81 wfProfileIn( __METHOD__
);
83 $headers = array(); // HTTP headers to send
85 $fileName = isset( $params['f'] ) ?
$params['f'] : '';
86 unset( $params['f'] );
88 // Backwards compatibility parameters
89 if ( isset( $params['w'] ) ) {
90 $params['width'] = $params['w'];
91 unset( $params['w'] );
93 if ( isset( $params['p'] ) ) {
94 $params['page'] = $params['p'];
96 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
98 // Is this a thumb of an archived file?
99 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
100 unset( $params['archived'] );
102 // Some basic input validation
103 $fileName = strtr( $fileName, '\\/', '__' );
105 // Actually fetch the image. Method depends on whether it is archived or not.
107 // Format is <timestamp>!<name>
108 $bits = explode( '!', $fileName, 2 );
109 if ( count( $bits ) != 2 ) {
110 wfThumbError( 404, wfMsg( 'badtitletext' ) );
111 wfProfileOut( __METHOD__
);
114 $title = Title
::makeTitleSafe( NS_FILE
, $bits[1] );
116 wfThumbError( 404, wfMsg( 'badtitletext' ) );
117 wfProfileOut( __METHOD__
);
120 $img = RepoGroup
::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
122 $img = wfLocalFile( $fileName );
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__
);
133 $headers[] = 'Cache-Control: private';
134 $headers[] = 'Vary: Cookie';
137 // Check the source file storage path
139 wfThumbError( 404, wfMsg( 'badtitletext' ) );
140 wfProfileOut( __METHOD__
);
143 if ( !$img->exists() ) {
144 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
145 wfProfileOut( __METHOD__
);
148 $sourcePath = $img->getPath();
149 if ( $sourcePath === false ) {
150 wfThumbError( 500, 'The source file is not locally accessible.' );
151 wfProfileOut( __METHOD__
);
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'] ) ) {
159 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
161 wfSuppressWarnings();
162 $imsUnix = strtotime( $imsString );
164 $sourceTsUnix = wfTimestamp( TS_UNIX
, $img->getTimestamp() );
165 if ( $sourceTsUnix <= $imsUnix ) {
166 header( 'HTTP/1.1 304 Not Modified' );
167 wfProfileOut( __METHOD__
);
172 // Stream the file if it exists already...
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 ) )
183 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
184 wfProfileOut( __METHOD__
);
187 $thumbPath = $img->getThumbPath( $thumbName );
188 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
189 $img->getRepo()->streamFile( $thumbPath, $headers );
190 wfProfileOut( __METHOD__
);
194 } catch ( MWException
$e ) {
195 wfThumbError( 500, $e->getHTML() );
196 wfProfileOut( __METHOD__
);
200 // Thumbnail isn't already there, so create the new thumbnail...
202 $thumb = $img->transform( $params, File
::RENDER_NOW
);
203 } catch ( Exception
$ex ) {
204 // Tried to select a page on a non-paged file?
208 // Check for thumbnail generation errors...
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?' );
221 if ( $errorMsg !== false ) {
222 wfThumbError( 500, $errorMsg );
224 // Stream the file if there were no errors
225 $thumb->streamFile( $headers );
228 wfProfileOut( __METHOD__
);
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.
235 * @param $uri String Thumbnail request URI path
236 * @return Array|null associative params array or null
238 function wfExtractThumbParams( $uri ) {
239 $repo = RepoGroup
::singleton()->getLocalRepo();
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'];
250 $zoneUrlRegex = preg_quote( $zoneURI );
252 $hashDirRegex = $subdirRegex = '';
253 for ( $i = 0; $i < $repo->getHashLevels(); $i++
) {
254 $subdirRegex .= '[0-9a-f]';
255 $hashDirRegex .= "$subdirRegex/";
258 $thumbUrlRegex = "!^$zoneUrlRegex/((archive/|temp/)?$hashDirRegex([^/]*)/([^/]*))$!";
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 );
266 $params = array( 'f' => $filename, 'rel404' => $rel );
267 if ( $archOrTemp == 'archive/' ) {
268 $params['archived'] = 1;
269 } elseif ( $archOrTemp == 'temp/' ) {
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;
278 $params['page'] = $pagenum;
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)
287 return null; // not a valid thumbnail URL
291 * Output a thumbnail generation error message
293 * @param $status integer
297 function wfThumbError( $status, $msg ) {
298 global $wgShowHostnames;
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' );
308 header( 'HTTP/1.1 500 Internal server error' );
310 if ( $wgShowHostnames ) {
311 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : '' );
312 $hostname = htmlspecialchars( wfHostname() );
313 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
318 <html><head><title>Error generating thumbnail</title></head>
320 <h1>Error generating thumbnail</h1>