3 * PHP script to stream out an image thumbnail.
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.
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.
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
24 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
25 if ( isset( $_SERVER['MW_COMPILED'] ) ) {
26 require( 'core/includes/WebStart.php' );
28 require( __DIR__
. '/includes/WebStart.php' );
31 // Don't use fancy mime detection, just check the file extension for jpg/gif/png
32 $wgTrivialMimeDetection = true;
34 if ( defined( 'THUMB_HANDLER' ) ) {
35 // Called from thumb_handler.php via 404; extract params from the URI...
38 // Called directly, use $_REQUEST params
39 wfThumbHandleRequest();
43 //--------------------------------------------------------------------------
46 * Handle a thumbnail request via query parameters
50 function wfThumbHandleRequest() {
51 $params = get_magic_quotes_gpc()
52 ?
array_map( 'stripslashes', $_REQUEST )
55 wfStreamThumb( $params ); // stream the thumbnail
59 * Handle a thumbnail request via thumbnail file URL
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 $uriPath = str_replace( "%2F", "/", urlencode( $_SERVER['REDIRECT_URL'] ) );
70 $uriPath = $_SERVER['REQUEST_URI'];
72 # Just get the URI path (REDIRECT_URL/REQUEST_URI is either a full URL or a path)
73 if ( substr( $uriPath, 0, 1 ) !== '/' ) {
74 $bits = wfParseUrl( $uriPath );
75 if ( $bits && isset( $bits['path'] ) ) {
76 $uriPath = $bits['path'];
78 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
83 $params = wfExtractThumbParams( $uriPath ); // basic wiki URL param extracting
84 if ( $params == null ) {
85 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
89 wfStreamThumb( $params ); // stream the thumbnail
93 * Stream a thumbnail specified by parameters
95 * @param $params Array
98 function wfStreamThumb( array $params ) {
100 wfProfileIn( __METHOD__
);
102 $headers = array(); // HTTP headers to send
104 $fileName = isset( $params['f'] ) ?
$params['f'] : '';
105 unset( $params['f'] );
107 // Backwards compatibility parameters
108 if ( isset( $params['w'] ) ) {
109 $params['width'] = $params['w'];
110 unset( $params['w'] );
112 if ( isset( $params['p'] ) ) {
113 $params['page'] = $params['p'];
115 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
117 // Is this a thumb of an archived file?
118 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
119 unset( $params['archived'] ); // handlers don't care
121 // Is this a thumb of a temp file?
122 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
123 unset( $params['temp'] ); // handlers don't care
125 // Some basic input validation
126 $fileName = strtr( $fileName, '\\/', '__' );
128 // Actually fetch the image. Method depends on whether it is archived or not.
130 // Format is <timestamp>!<name>
131 $bits = explode( '!', $fileName, 2 );
132 if ( count( $bits ) != 2 ) {
133 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
134 wfProfileOut( __METHOD__
);
137 $title = Title
::makeTitleSafe( NS_FILE
, $bits[1] );
139 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
140 wfProfileOut( __METHOD__
);
143 $img = RepoGroup
::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
144 } elseif ( $isTemp ) {
145 $repo = RepoGroup
::singleton()->getLocalRepo()->getTempRepo();
146 // Format is <timestamp>!<name> or just <name>
147 $bits = explode( '!', $fileName, 2 );
148 // Get the name without the timestamp so hash paths are correctly computed
149 $title = Title
::makeTitleSafe( NS_FILE
, isset( $bits[1] ) ?
$bits[1] : $fileName );
151 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
152 wfProfileOut( __METHOD__
);
155 $img = new UnregisteredLocalFile( $title, $repo,
156 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
159 $img = wfLocalFile( $fileName );
162 // Check permissions if there are read restrictions
163 $varyHeader = array();
164 if ( !in_array( 'read', User
::getGroupPermissions( array( '*' ) ), true ) ) {
165 if ( !$img->getTitle() ||
!$img->getTitle()->userCan( 'read' ) ) {
166 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
167 'the source file.' );
168 wfProfileOut( __METHOD__
);
171 $headers[] = 'Cache-Control: private';
172 $varyHeader[] = 'Cookie';
175 // Check the source file storage path
177 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
178 wfProfileOut( __METHOD__
);
181 if ( !$img->exists() ) {
182 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
183 wfProfileOut( __METHOD__
);
186 $sourcePath = $img->getPath();
187 if ( $sourcePath === false ) {
188 wfThumbError( 500, 'The source file is not locally accessible.' );
189 wfProfileOut( __METHOD__
);
193 // Check IMS against the source file
194 // This means that clients can keep a cached copy even after it has been deleted on the server
195 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
197 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
199 wfSuppressWarnings();
200 $imsUnix = strtotime( $imsString );
202 $sourceTsUnix = wfTimestamp( TS_UNIX
, $img->getTimestamp() );
203 if ( $sourceTsUnix <= $imsUnix ) {
204 header( 'HTTP/1.1 304 Not Modified' );
205 wfProfileOut( __METHOD__
);
210 $thumbName = $img->thumbName( $params );
211 if ( !strlen( $thumbName ) ) { // invalid params?
212 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
213 wfProfileOut( __METHOD__
);
217 $disposition = $img->getThumbDisposition( $thumbName );
218 $headers[] = "Content-Disposition: $disposition";
220 // Stream the file if it exists already...
222 $thumbName2 = $img->thumbName( $params, File
::THUMB_FULL_NAME
); // b/c; "long" style
223 // For 404 handled thumbnails, we only use the the base name of the URI
224 // for the thumb params and the parent directory for the source file name.
225 // Check that the zone relative path matches up so squid caches won't pick
226 // up thumbs that would not be purged on source file deletion (bug 34231).
227 if ( isset( $params['rel404'] ) ) { // thumbnail was handled via 404
228 if ( urldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName ) ) {
229 // Request for the canonical thumbnail name
230 } elseif ( urldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName2 ) ) {
231 // Request for the "long" thumbnail name; redirect to canonical name
232 $response = RequestContext
::getMain()->getRequest()->response();
233 $response->header( "HTTP/1.1 301 " . HttpStatus
::getMessage( 301 ) );
234 $response->header( 'Location: ' . wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT
) );
235 $response->header( 'Expires: ' .
236 gmdate( 'D, d M Y H:i:s', time() +
7*86400 ) . ' GMT' );
237 if ( $wgVaryOnXFP ) {
238 $varyHeader[] = 'X-Forwarded-Proto';
240 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
241 wfProfileOut( __METHOD__
);
244 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
245 wfProfileOut( __METHOD__
);
249 $thumbPath = $img->getThumbPath( $thumbName );
250 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
251 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
252 $img->getRepo()->streamFile( $thumbPath, $headers );
253 wfProfileOut( __METHOD__
);
256 } catch ( MWException
$e ) {
257 wfThumbError( 500, $e->getHTML() );
258 wfProfileOut( __METHOD__
);
261 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
263 // Thumbnail isn't already there, so create the new thumbnail...
265 $thumb = $img->transform( $params, File
::RENDER_NOW
);
266 } catch ( Exception
$ex ) {
267 // Tried to select a page on a non-paged file?
271 // Check for thumbnail generation errors...
273 $msg = wfMessage( 'thumbnail_error' );
275 $errorMsg = $msg->rawParams( 'File::transform() returned false' )->escaped();
276 } elseif ( $thumb->isError() ) {
277 $errorMsg = $thumb->getHtmlMsg();
278 } elseif ( !$thumb->hasFile() ) {
279 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
280 } elseif ( $thumb->fileIsSource() ) {
282 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
285 if ( $errorMsg !== false ) {
286 wfThumbError( 500, $errorMsg );
288 // Stream the file if there were no errors
289 $thumb->streamFile( $headers );
292 wfProfileOut( __METHOD__
);
296 * Extract the required params for thumb.php from the thumbnail request URI.
297 * At least 'width' and 'f' should be set if the result is an array.
299 * @param $uriPath String Thumbnail request URI path
300 * @return Array|null associative params array or null
302 function wfExtractThumbParams( $uriPath ) {
303 $repo = RepoGroup
::singleton()->getLocalRepo();
305 $zoneUriPath = $repo->getZoneHandlerUrl( 'thumb' )
306 ?
$repo->getZoneHandlerUrl( 'thumb' ) // custom URL
307 : $repo->getZoneUrl( 'thumb' ); // default to main URL
308 // URL might be relative ("/images") or protocol-relative ("//lang.site/image")
309 $bits = wfParseUrl( wfExpandUrl( $zoneUriPath, PROTO_INTERNAL
) );
310 if ( $bits && isset( $bits['path'] ) ) {
311 $zoneUriPath = $bits['path'];
316 $hashDirRegex = $subdirRegex = '';
317 for ( $i = 0; $i < $repo->getHashLevels(); $i++
) {
318 $subdirRegex .= '[0-9a-f]';
319 $hashDirRegex .= "$subdirRegex/";
322 $thumbPathRegex = "!^" . preg_quote( $zoneUriPath ) .
323 "/((archive/|temp/)?$hashDirRegex([^/]*)/([^/]*))$!";
325 // Check if this is a valid looking thumbnail request...
326 if ( preg_match( $thumbPathRegex, $uriPath, $matches ) ) {
327 list( /* all */, $rel, $archOrTemp, $filename, $thumbname ) = $matches;
328 $filename = urldecode( $filename );
329 $thumbname = urldecode( $thumbname );
331 $params = array( 'f' => $filename, 'rel404' => $rel );
332 if ( $archOrTemp == 'archive/' ) {
333 $params['archived'] = 1;
334 } elseif ( $archOrTemp == 'temp/' ) {
338 // Check if the parameters can be extracted from the thumbnail name...
339 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
340 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
341 $params['width'] = $size;
343 $params['page'] = $pagenum;
345 return $params; // valid thumbnail URL
346 // Hooks return false if they manage to *resolve* the parameters
347 } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
348 return $params; // valid thumbnail URL (via extension or config)
352 return null; // not a valid thumbnail URL
356 * Output a thumbnail generation error message
358 * @param $status integer
362 function wfThumbError( $status, $msg ) {
363 global $wgShowHostnames;
365 header( 'Cache-Control: no-cache' );
366 header( 'Content-Type: text/html; charset=utf-8' );
367 if ( $status == 404 ) {
368 header( 'HTTP/1.1 404 Not found' );
369 } elseif ( $status == 403 ) {
370 header( 'HTTP/1.1 403 Forbidden' );
371 header( 'Vary: Cookie' );
373 header( 'HTTP/1.1 500 Internal server error' );
375 if ( $wgShowHostnames ) {
376 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : '' );
377 $hostname = htmlspecialchars( wfHostname() );
378 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
383 <html><head><title>Error generating thumbnail</title></head>
385 <h1>Error generating thumbnail</h1>