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();
44 //--------------------------------------------------------------------------
47 * Handle a thumbnail request via query parameters
51 function wfThumbHandleRequest() {
52 $params = get_magic_quotes_gpc()
53 ?
array_map( 'stripslashes', $_REQUEST )
56 wfStreamThumb( $params ); // stream the thumbnail
60 * Handle a thumbnail request via thumbnail file URL
64 function wfThumbHandle404() {
65 global $wgArticlePath;
67 # Set action base paths so that WebRequest::getPathInfo()
68 # recognizes the "X" as the 'title' in ../thumb_handler.php/X urls.
69 $wgArticlePath = false; # Don't let a "/*" article path clober our action path
71 $matches = WebRequest
::getPathInfo();
72 if ( !isset( $matches['title'] ) ) {
73 wfThumbError( 404, 'Could not determine the name of the requested thumbnail.' );
77 $params = wfExtractThumbParams( $matches['title'] ); // basic wiki URL param extracting
78 if ( $params == null ) {
79 wfThumbError( 400, 'The specified thumbnail parameters are not recognized.' );
83 wfStreamThumb( $params ); // stream the thumbnail
87 * Stream a thumbnail specified by parameters
89 * @param $params Array
92 function wfStreamThumb( array $params ) {
94 wfProfileIn( __METHOD__
);
96 $headers = array(); // HTTP headers to send
98 $fileName = isset( $params['f'] ) ?
$params['f'] : '';
99 unset( $params['f'] );
101 // Backwards compatibility parameters
102 if ( isset( $params['w'] ) ) {
103 $params['width'] = $params['w'];
104 unset( $params['w'] );
106 if ( isset( $params['p'] ) ) {
107 $params['page'] = $params['p'];
109 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
111 // Is this a thumb of an archived file?
112 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
113 unset( $params['archived'] ); // handlers don't care
115 // Is this a thumb of a temp file?
116 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
117 unset( $params['temp'] ); // handlers don't care
119 // Some basic input validation
120 $fileName = strtr( $fileName, '\\/', '__' );
122 // Actually fetch the image. Method depends on whether it is archived or not.
124 $repo = RepoGroup
::singleton()->getLocalRepo()->getTempRepo();
125 $img = new UnregisteredLocalFile( null, $repo,
126 # Temp files are hashed based on the name without the timestamp.
127 # The thumbnails will be hashed based on the entire name however.
128 # @TODO: fix this convention to actually be reasonable.
129 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
131 } elseif ( $isOld ) {
132 // Format is <timestamp>!<name>
133 $bits = explode( '!', $fileName, 2 );
134 if ( count( $bits ) != 2 ) {
135 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
136 wfProfileOut( __METHOD__
);
139 $title = Title
::makeTitleSafe( NS_FILE
, $bits[1] );
141 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
142 wfProfileOut( __METHOD__
);
145 $img = RepoGroup
::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
147 $img = wfLocalFile( $fileName );
150 // Check the source file title
152 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
153 wfProfileOut( __METHOD__
);
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.' );
163 wfProfileOut( __METHOD__
);
166 $headers[] = 'Cache-Control: private';
167 $varyHeader[] = 'Cookie';
170 // Check the source file storage path
171 if ( !$img->exists() ) {
172 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
173 wfProfileOut( __METHOD__
);
176 $sourcePath = $img->getPath();
177 if ( $sourcePath === false ) {
178 wfThumbError( 500, 'The source file is not locally accessible.' );
179 wfProfileOut( __METHOD__
);
183 // Check IMS against the source file
184 // This means that clients can keep a cached copy even after it has been deleted on the server
185 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
187 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
189 wfSuppressWarnings();
190 $imsUnix = strtotime( $imsString );
192 $sourceTsUnix = wfTimestamp( TS_UNIX
, $img->getTimestamp() );
193 if ( $sourceTsUnix <= $imsUnix ) {
194 header( 'HTTP/1.1 304 Not Modified' );
195 wfProfileOut( __METHOD__
);
200 $thumbName = $img->thumbName( $params );
201 if ( !strlen( $thumbName ) ) { // invalid params?
202 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
203 wfProfileOut( __METHOD__
);
207 $disposition = $img->getThumbDisposition( $thumbName );
208 $headers[] = "Content-Disposition: $disposition";
210 // Stream the file if it exists already...
212 $thumbName2 = $img->thumbName( $params, File
::THUMB_FULL_NAME
); // b/c; "long" style
213 // For 404 handled thumbnails, we only use the the base name of the URI
214 // for the thumb params and the parent directory for the source file name.
215 // Check that the zone relative path matches up so squid caches won't pick
216 // up thumbs that would not be purged on source file deletion (bug 34231).
217 if ( isset( $params['rel404'] ) ) { // thumbnail was handled via 404
218 if ( urldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName ) ) {
219 // Request for the canonical thumbnail name
220 } elseif ( urldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName2 ) ) {
221 // Request for the "long" thumbnail name; redirect to canonical name
222 $response = RequestContext
::getMain()->getRequest()->response();
223 $response->header( "HTTP/1.1 301 " . HttpStatus
::getMessage( 301 ) );
224 $response->header( 'Location: ' . wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT
) );
225 $response->header( 'Expires: ' .
226 gmdate( 'D, d M Y H:i:s', time() +
7*86400 ) . ' GMT' );
227 if ( $wgVaryOnXFP ) {
228 $varyHeader[] = 'X-Forwarded-Proto';
230 if ( count( $varyHeader ) ) {
231 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
233 wfProfileOut( __METHOD__
);
236 wfThumbError( 404, 'The given path of the specified thumbnail is incorrect.' );
237 wfProfileOut( __METHOD__
);
241 $thumbPath = $img->getThumbPath( $thumbName );
242 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
243 if ( count( $varyHeader ) ) {
244 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
246 $img->getRepo()->streamFile( $thumbPath, $headers );
247 wfProfileOut( __METHOD__
);
250 } catch ( MWException
$e ) {
251 wfThumbError( 500, $e->getHTML() );
252 wfProfileOut( __METHOD__
);
256 if ( count( $varyHeader ) ) {
257 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
260 // Thumbnail isn't already there, so create the new thumbnail...
262 $thumb = $img->transform( $params, File
::RENDER_NOW
);
263 } catch ( Exception
$ex ) {
264 // Tried to select a page on a non-paged file?
268 // Check for thumbnail generation errors...
270 $msg = wfMessage( 'thumbnail_error' );
272 $errorMsg = $msg->rawParams( 'File::transform() returned false' )->escaped();
273 } elseif ( $thumb->isError() ) {
274 $errorMsg = $thumb->getHtmlMsg();
275 } elseif ( !$thumb->hasFile() ) {
276 $errorMsg = $msg->rawParams( 'No path supplied in thumbnail object' )->escaped();
277 } elseif ( $thumb->fileIsSource() ) {
279 rawParams( 'Image was not scaled, is the requested width bigger than the source?' )->escaped();
282 if ( $errorMsg !== false ) {
283 wfThumbError( 500, $errorMsg );
285 // Stream the file if there were no errors
286 $thumb->streamFile( $headers );
289 wfProfileOut( __METHOD__
);
293 * Extract the required params for thumb.php from the thumbnail request URI.
294 * At least 'width' and 'f' should be set if the result is an array.
296 * @param $thumbRel String Thumbnail path relative to the thumb zone
297 * @return Array|null associative params array or null
299 function wfExtractThumbParams( $thumbRel ) {
300 $repo = RepoGroup
::singleton()->getLocalRepo();
302 $hashDirReg = $subdirReg = '';
303 for ( $i = 0; $i < $repo->getHashLevels(); $i++
) {
304 $subdirReg .= '[0-9a-f]';
305 $hashDirReg .= "$subdirReg/";
308 // Check if this is a thumbnail of an original in the local file repo
309 if ( preg_match( "!^((archive/)?$hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
310 list( /*all*/, $rel, $archOrTemp, $filename, $thumbname ) = $m;
311 // Check if this is a thumbnail of an temp file in the local file repo
312 } elseif ( preg_match( "!^(temp/)($hashDirReg([^/]*)/([^/]*))$!", $thumbRel, $m ) ) {
313 list( /*all*/, $archOrTemp, $rel, $filename, $thumbname ) = $m;
315 return null; // not a valid looking thumbnail request
318 $params = array( 'f' => $filename, 'rel404' => $rel );
319 if ( $archOrTemp === 'archive/' ) {
320 $params['archived'] = 1;
321 } elseif ( $archOrTemp === 'temp/' ) {
325 // Check hooks if parameters can be extracted
326 // Hooks return false if they manage to *resolve* the parameters
327 if ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
328 return $params; // valid thumbnail URL (via extension or config)
329 // Check if the parameters can be extracted from the thumbnail name...
330 } elseif ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
331 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
332 $params['width'] = $size;
334 $params['page'] = $pagenum;
336 return $params; // valid thumbnail URL
339 return null; // not a valid thumbnail URL
343 * Output a thumbnail generation error message
345 * @param $status integer
349 function wfThumbError( $status, $msg ) {
350 global $wgShowHostnames;
352 header( 'Cache-Control: no-cache' );
353 header( 'Content-Type: text/html; charset=utf-8' );
354 if ( $status == 404 ) {
355 header( 'HTTP/1.1 404 Not found' );
356 } elseif ( $status == 403 ) {
357 header( 'HTTP/1.1 403 Forbidden' );
358 header( 'Vary: Cookie' );
360 header( 'HTTP/1.1 500 Internal server error' );
362 if ( $wgShowHostnames ) {
363 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : '' );
364 $hostname = htmlspecialchars( wfHostname() );
365 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
370 <html><head><title>Error generating thumbnail</title></head>
372 <h1>Error generating thumbnail</h1>