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( dirname( __FILE__
) . '/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 $uri = str_replace( "%2F", "/", urlencode( $_SERVER['REDIRECT_URL'] ) );
69 # Just get the URI path (REDIRECT_URL is either a full URL or a path)
70 if ( $uri[0] !== '/' ) {
71 $bits = wfParseUrl( $uri );
72 if ( $bits && isset( $bits['path'] ) ) {
77 $uri = $_SERVER['REQUEST_URI'];
80 $params = wfExtractThumbParams( $uri ); // basic wiki URL param extracting
81 if ( $params == null ) {
82 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
86 wfStreamThumb( $params ); // stream the thumbnail
90 * Stream a thumbnail specified by parameters
92 * @param $params Array
95 function wfStreamThumb( array $params ) {
96 wfProfileIn( __METHOD__
);
98 $headers = array(); // HTTP headers to send
100 $fileName = isset( $params['f'] ) ?
$params['f'] : '';
101 unset( $params['f'] );
103 // Backwards compatibility parameters
104 if ( isset( $params['w'] ) ) {
105 $params['width'] = $params['w'];
106 unset( $params['w'] );
108 if ( isset( $params['p'] ) ) {
109 $params['page'] = $params['p'];
111 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
113 // Is this a thumb of an archived file?
114 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
115 unset( $params['archived'] ); // handlers don't care
117 // Is this a thumb of a temp file?
118 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
119 unset( $params['temp'] ); // handlers don't care
121 // Some basic input validation
122 $fileName = strtr( $fileName, '\\/', '__' );
124 // Actually fetch the image. Method depends on whether it is archived or not.
126 // Format is <timestamp>!<name>
127 $bits = explode( '!', $fileName, 2 );
128 if ( count( $bits ) != 2 ) {
129 wfThumbError( 404, wfMsg( 'badtitletext' ) );
130 wfProfileOut( __METHOD__
);
133 $title = Title
::makeTitleSafe( NS_FILE
, $bits[1] );
135 wfThumbError( 404, wfMsg( 'badtitletext' ) );
136 wfProfileOut( __METHOD__
);
139 $img = RepoGroup
::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
140 } elseif ( $isTemp ) {
141 $repo = RepoGroup
::singleton()->getLocalRepo()->getTempRepo();
142 // Format is <timestamp>!<name> or just <name>
143 $bits = explode( '!', $fileName, 2 );
144 // Get the name without the timestamp so hash paths are correctly computed
145 $title = Title
::makeTitleSafe( NS_FILE
, isset( $bits[1] ) ?
$bits[1] : $fileName );
147 wfThumbError( 404, wfMsg( 'badtitletext' ) );
148 wfProfileOut( __METHOD__
);
151 $img = new UnregisteredLocalFile( $title, $repo,
152 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
155 $img = wfLocalFile( $fileName );
158 // Check permissions if there are read restrictions
159 if ( !in_array( 'read', User
::getGroupPermissions( array( '*' ) ), true ) ) {
160 if ( !$img->getTitle() ||
!$img->getTitle()->userCan( 'read' ) ) {
161 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
162 'the source file.' );
163 wfProfileOut( __METHOD__
);
166 $headers[] = 'Cache-Control: private';
167 $headers[] = 'Vary: Cookie';
170 // Check the source file storage path
172 wfThumbError( 404, wfMsg( 'badtitletext' ) );
173 wfProfileOut( __METHOD__
);
176 if ( !$img->exists() ) {
177 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
178 wfProfileOut( __METHOD__
);
181 $sourcePath = $img->getPath();
182 if ( $sourcePath === false ) {
183 wfThumbError( 500, 'The source file is not locally accessible.' );
184 wfProfileOut( __METHOD__
);
188 // Check IMS against the source file
189 // This means that clients can keep a cached copy even after it has been deleted on the server
190 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
192 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
194 wfSuppressWarnings();
195 $imsUnix = strtotime( $imsString );
197 $sourceTsUnix = wfTimestamp( TS_UNIX
, $img->getTimestamp() );
198 if ( $sourceTsUnix <= $imsUnix ) {
199 header( 'HTTP/1.1 304 Not Modified' );
200 wfProfileOut( __METHOD__
);
205 // Stream the file if it exists already...
207 $thumbName = $img->thumbName( $params );
208 if ( strlen( $thumbName ) ) { // valid params?
209 // For 404 handled thumbnails, we only use the the base name of the URI
210 // for the thumb params and the parent directory for the source file name.
211 // Check that the zone relative path matches up so squid caches won't pick
212 // up thumbs that would not be purged on source file deletion (bug 34231).
213 if ( isset( $params['rel404'] ) // thumbnail was handled via 404
214 && urldecode( $params['rel404'] ) !== $img->getThumbRel( $thumbName ) )
216 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
217 wfProfileOut( __METHOD__
);
220 $thumbPath = $img->getThumbPath( $thumbName );
221 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
222 $img->getRepo()->streamFile( $thumbPath, $headers );
223 wfProfileOut( __METHOD__
);
227 } catch ( MWException
$e ) {
228 wfThumbError( 500, $e->getHTML() );
229 wfProfileOut( __METHOD__
);
233 // Thumbnail isn't already there, so create the new thumbnail...
235 $thumb = $img->transform( $params, File
::RENDER_NOW
);
236 } catch ( Exception
$ex ) {
237 // Tried to select a page on a non-paged file?
241 // Check for thumbnail generation errors...
244 $errorMsg = wfMsgHtml( 'thumbnail_error', 'File::transform() returned false' );
245 } elseif ( $thumb->isError() ) {
246 $errorMsg = $thumb->getHtmlMsg();
247 } elseif ( !$thumb->hasFile() ) {
248 $errorMsg = wfMsgHtml( 'thumbnail_error', 'No path supplied in thumbnail object' );
249 } elseif ( $thumb->fileIsSource() ) {
250 $errorMsg = wfMsgHtml( 'thumbnail_error',
251 'Image was not scaled, is the requested width bigger than the source?' );
254 if ( $errorMsg !== false ) {
255 wfThumbError( 500, $errorMsg );
257 // Stream the file if there were no errors
258 $thumb->streamFile( $headers );
261 wfProfileOut( __METHOD__
);
265 * Extract the required params for thumb.php from the thumbnail request URI.
266 * At least 'width' and 'f' should be set if the result is an array.
268 * @param $uri String Thumbnail request URI path
269 * @return Array|null associative params array or null
271 function wfExtractThumbParams( $uri ) {
272 $repo = RepoGroup
::singleton()->getLocalRepo();
274 $zoneURI = $repo->getZoneUrl( 'thumb' );
275 if ( substr( $zoneURI, 0, 1 ) !== '/' ) {
276 $bits = wfParseUrl( $zoneURI );
277 if ( $bits && isset( $bits['path'] ) ) {
278 $zoneURI = $bits['path'];
283 $zoneUrlRegex = preg_quote( $zoneURI );
285 $hashDirRegex = $subdirRegex = '';
286 for ( $i = 0; $i < $repo->getHashLevels(); $i++
) {
287 $subdirRegex .= '[0-9a-f]';
288 $hashDirRegex .= "$subdirRegex/";
291 $thumbUrlRegex = "!^$zoneUrlRegex/((archive/|temp/)?$hashDirRegex([^/]*)/([^/]*))$!";
293 // Check if this is a valid looking thumbnail request...
294 if ( preg_match( $thumbUrlRegex, $uri, $matches ) ) {
295 list( /* all */, $rel, $archOrTemp, $filename, $thumbname ) = $matches;
296 $filename = urldecode( $filename );
297 $thumbname = urldecode( $thumbname );
299 $params = array( 'f' => $filename, 'rel404' => $rel );
300 if ( $archOrTemp == 'archive/' ) {
301 $params['archived'] = 1;
302 } elseif ( $archOrTemp == 'temp/' ) {
306 // Check if the parameters can be extracted from the thumbnail name...
307 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
308 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
309 $params['width'] = $size;
311 $params['page'] = $pagenum;
313 return $params; // valid thumbnail URL
314 // Hooks return false if they manage to *resolve* the parameters
315 } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
316 return $params; // valid thumbnail URL (via extension or config)
320 return null; // not a valid thumbnail URL
324 * Output a thumbnail generation error message
326 * @param $status integer
330 function wfThumbError( $status, $msg ) {
331 global $wgShowHostnames;
333 header( 'Cache-Control: no-cache' );
334 header( 'Content-Type: text/html; charset=utf-8' );
335 if ( $status == 404 ) {
336 header( 'HTTP/1.1 404 Not found' );
337 } elseif ( $status == 403 ) {
338 header( 'HTTP/1.1 403 Forbidden' );
339 header( 'Vary: Cookie' );
341 header( 'HTTP/1.1 500 Internal server error' );
343 if ( $wgShowHostnames ) {
344 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : '' );
345 $hostname = htmlspecialchars( wfHostname() );
346 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
351 <html><head><title>Error generating thumbnail</title></head>
353 <h1>Error generating thumbnail</h1>