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 require __DIR__
. '/includes/WebStart.php';
27 // Don't use fancy mime detection, just check the file extension for jpg/gif/png
28 $wgTrivialMimeDetection = true;
30 if ( defined( 'THUMB_HANDLER' ) ) {
31 // Called from thumb_handler.php via 404; extract params from the URI...
34 // Called directly, use $_GET params
35 wfThumbHandleRequest();
40 //--------------------------------------------------------------------------
43 * Handle a thumbnail request via query parameters
47 function wfThumbHandleRequest() {
48 $params = get_magic_quotes_gpc()
49 ?
array_map( 'stripslashes', $_GET )
52 wfStreamThumb( $params ); // stream the thumbnail
56 * Handle a thumbnail request via thumbnail file URL
60 function wfThumbHandle404() {
61 global $wgArticlePath;
63 # Set action base paths so that WebRequest::getPathInfo()
64 # recognizes the "X" as the 'title' in ../thumb_handler.php/X urls.
65 # Note: If Custom per-extension repo paths are set, this may break.
66 $repo = RepoGroup
::singleton()->getLocalRepo();
67 $oldArticlePath = $wgArticlePath;
68 $wgArticlePath = $repo->getZoneUrl( 'thumb' ) . '/$1';
70 $matches = WebRequest
::getPathInfo();
72 $wgArticlePath = $oldArticlePath;
74 if ( !isset( $matches['title'] ) ) {
75 wfThumbError( 404, 'Could not determine the name of the requested thumbnail.' );
79 $params = wfExtractThumbParams( $matches['title'] ); // basic wiki URL param extracting
80 if ( $params == null ) {
81 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
85 wfStreamThumb( $params ); // stream the thumbnail
89 * Stream a thumbnail specified by parameters
91 * @param $params Array
94 function wfStreamThumb( array $params ) {
97 $section = new ProfileSection( __METHOD__
);
99 $headers = array(); // HTTP headers to send
101 $fileName = isset( $params['f'] ) ?
$params['f'] : '';
102 unset( $params['f'] );
104 // Backwards compatibility parameters
105 if ( isset( $params['w'] ) ) {
106 $params['width'] = $params['w'];
107 unset( $params['w'] );
109 if ( isset( $params['p'] ) ) {
110 $params['page'] = $params['p'];
112 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
114 // Is this a thumb of an archived file?
115 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
116 unset( $params['archived'] ); // handlers don't care
118 // Is this a thumb of a temp file?
119 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
120 unset( $params['temp'] ); // handlers don't care
122 // Some basic input validation
123 $fileName = strtr( $fileName, '\\/', '__' );
125 // Actually fetch the image. Method depends on whether it is archived or not.
127 $repo = RepoGroup
::singleton()->getLocalRepo()->getTempRepo();
128 $img = new UnregisteredLocalFile( null, $repo,
129 # Temp files are hashed based on the name without the timestamp.
130 # The thumbnails will be hashed based on the entire name however.
131 # @todo fix this convention to actually be reasonable.
132 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
134 } elseif ( $isOld ) {
135 // Format is <timestamp>!<name>
136 $bits = explode( '!', $fileName, 2 );
137 if ( count( $bits ) != 2 ) {
138 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
141 $title = Title
::makeTitleSafe( NS_FILE
, $bits[1] );
143 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
146 $img = RepoGroup
::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
148 $img = wfLocalFile( $fileName );
151 // Check the source file title
153 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
157 // Check permissions if there are read restrictions
158 $varyHeader = array();
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.' );
165 $headers[] = 'Cache-Control: private';
166 $varyHeader[] = 'Cookie';
169 // Check the source file storage path
170 if ( !$img->exists() ) {
171 $redirectedLocation = false;
173 // Check for file redirect
175 // Since redirects are associated with pages, not versions of files,
176 // we look for the most current version to see if its a redirect.
177 $possibleRedirFile = RepoGroup
::singleton()->getLocalRepo()->findFile( $img->getName() );
179 $possibleRedirFile = RepoGroup
::singleton()->getLocalRepo()->findFile( $fileName );
181 if ( $possibleRedirFile && !is_null( $possibleRedirFile->getRedirected() ) ) {
182 $redirTarget = $possibleRedirFile->getName();
183 $targetFile = wfLocalFile( Title
::makeTitleSafe( NS_FILE
, $redirTarget ) );
184 if ( $targetFile->exists() ) {
185 $newThumbName = $targetFile->thumbName( $params );
187 $newThumbUrl = $targetFile->getArchiveThumbUrl( $bits[0] . '!' . $targetFile->getName(), $newThumbName );
189 $newThumbUrl = $targetFile->getThumbUrl( $newThumbName );
191 $redirectedLocation = wfExpandUrl( $newThumbUrl, PROTO_CURRENT
);
196 if ( $redirectedLocation ) {
197 // File has been moved. Give redirect.
198 $response = RequestContext
::getMain()->getRequest()->response();
199 $response->header( "HTTP/1.1 302 " . HttpStatus
::getMessage( 302 ) );
200 $response->header( 'Location: ' . $redirectedLocation );
201 $response->header( 'Expires: ' .
202 gmdate( 'D, d M Y H:i:s', time() +
12 * 3600 ) . ' GMT' );
203 if ( $wgVaryOnXFP ) {
204 $varyHeader[] = 'X-Forwarded-Proto';
206 if ( count( $varyHeader ) ) {
207 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
212 // If its not a redirect that has a target as a local file, give 404.
213 wfThumbError( 404, "The source file '$fileName' does not exist." );
215 } elseif ( $img->getPath() === false ) {
216 wfThumbError( 500, "The source file '$fileName' is not locally accessible." );
220 // Check IMS against the source file
221 // This means that clients can keep a cached copy even after it has been deleted on the server
222 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
224 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
226 wfSuppressWarnings();
227 $imsUnix = strtotime( $imsString );
229 if ( wfTimestamp( TS_UNIX
, $img->getTimestamp() ) <= $imsUnix ) {
230 header( 'HTTP/1.1 304 Not Modified' );
235 // Get the normalized thumbnail name from the parameters...
237 $thumbName = $img->thumbName( $params );
238 if ( !strlen( $thumbName ) ) { // invalid params?
239 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
242 $thumbName2 = $img->thumbName( $params, File
::THUMB_FULL_NAME
); // b/c; "long" style
243 } catch ( MWException
$e ) {
244 wfThumbError( 500, $e->getHTML() );
248 // For 404 handled thumbnails, we only use the the base name of the URI
249 // for the thumb params and the parent directory for the source file name.
250 // Check that the zone relative path matches up so squid caches won't pick
251 // up thumbs that would not be purged on source file deletion (bug 34231).
252 if ( isset( $params['rel404'] ) ) { // thumbnail was handled via 404
253 if ( rawurldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName ) ) {
254 // Request for the canonical thumbnail name
255 } elseif ( rawurldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName2 ) ) {
256 // Request for the "long" thumbnail name; redirect to canonical name
257 $response = RequestContext
::getMain()->getRequest()->response();
258 $response->header( "HTTP/1.1 301 " . HttpStatus
::getMessage( 301 ) );
259 $response->header( 'Location: ' .
260 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT
) );
261 $response->header( 'Expires: ' .
262 gmdate( 'D, d M Y H:i:s', time() +
7 * 86400 ) . ' GMT' );
263 if ( $wgVaryOnXFP ) {
264 $varyHeader[] = 'X-Forwarded-Proto';
266 if ( count( $varyHeader ) ) {
267 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
271 wfThumbError( 404, "The given path of the specified thumbnail is incorrect;
272 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
273 rawurldecode( $params['rel404'] ) . "'." );
278 // Suggest a good name for users downloading this thumbnail
279 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName )}";
281 if ( count( $varyHeader ) ) {
282 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
285 // Stream the file if it exists already...
286 $thumbPath = $img->getThumbPath( $thumbName );
287 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
288 $img->getRepo()->streamFile( $thumbPath, $headers );
292 // Thumbnail isn't already there, so create the new thumbnail...
294 $thumb = $img->transform( $params, File
::RENDER_NOW
);
295 } catch ( Exception
$ex ) {
296 // Tried to select a page on a non-paged file?
300 // Check for thumbnail generation errors...
302 $msg = wfMessage( 'thumbnail_error' );
304 $errorMsg = $msg->rawParams( 'File::transform() returned false' )->escaped();
305 } elseif ( $thumb->isError() ) {
306 $errorMsg = $thumb->getHtmlMsg();
307 } elseif ( !$thumb->hasFile() ) {
308 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
309 } elseif ( $thumb->fileIsSource() ) {
311 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
314 if ( $errorMsg !== false ) {
315 wfThumbError( 500, $errorMsg );
317 // Stream the file if there were no errors
318 $thumb->streamFile( $headers );
323 * Extract the required params for thumb.php from the thumbnail request URI.
324 * At least 'width' and 'f' should be set if the result is an array.
326 * @param $thumbRel String Thumbnail path relative to the thumb zone
327 * @return Array|null associative params array or null
329 function wfExtractThumbParams( $thumbRel ) {
330 $repo = RepoGroup
::singleton()->getLocalRepo();
332 $hashDirReg = $subdirReg = '';
333 for ( $i = 0; $i < $repo->getHashLevels(); $i++
) {
334 $subdirReg .= '[0-9a-f]';
335 $hashDirReg .= "$subdirReg/";
338 // Check if this is a thumbnail of an original in the local file repo
339 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
340 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
341 // Check if this is a thumbnail of an temp file in the local file repo
342 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
343 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
345 return null; // not a valid looking thumbnail request
348 $params = array( 'f' => $filename, 'rel404' => $rel );
349 if ( $archOrTemp === 'archive/' ) {
350 $params['archived'] = 1;
351 } elseif ( $archOrTemp === 'temp/' ) {
355 // Check hooks if parameters can be extracted
356 // Hooks return false if they manage to *resolve* the parameters
357 if ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
358 return $params; // valid thumbnail URL (via extension or config)
359 // Check if the parameters can be extracted from the thumbnail name...
360 } elseif ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
361 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
362 $params['width'] = $size;
364 $params['page'] = $pagenum;
366 return $params; // valid thumbnail URL
369 return null; // not a valid thumbnail URL
373 * Output a thumbnail generation error message
375 * @param $status integer
379 function wfThumbError( $status, $msg ) {
380 global $wgShowHostnames;
382 header( 'Cache-Control: no-cache' );
383 header( 'Content-Type: text/html; charset=utf-8' );
384 if ( $status == 404 ) {
385 header( 'HTTP/1.1 404 Not found' );
386 } elseif ( $status == 403 ) {
387 header( 'HTTP/1.1 403 Forbidden' );
388 header( 'Vary: Cookie' );
390 header( 'HTTP/1.1 500 Internal server error' );
392 if ( $wgShowHostnames ) {
393 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : '' );
394 $hostname = htmlspecialchars( wfHostname() );
395 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
400 <html><head><title>Error generating thumbnail</title></head>
402 <h1>Error generating thumbnail</h1>