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 $_GET 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', $_GET )
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 ) {
95 wfProfileIn( __METHOD__
);
97 $headers = array(); // HTTP headers to send
99 $fileName = isset( $params['f'] ) ?
$params['f'] : '';
100 unset( $params['f'] );
102 // Backwards compatibility parameters
103 if ( isset( $params['w'] ) ) {
104 $params['width'] = $params['w'];
105 unset( $params['w'] );
107 if ( isset( $params['p'] ) ) {
108 $params['page'] = $params['p'];
110 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
112 // Is this a thumb of an archived file?
113 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
114 unset( $params['archived'] ); // handlers don't care
116 // Is this a thumb of a temp file?
117 $isTemp = ( isset( $params['temp'] ) && $params['temp'] );
118 unset( $params['temp'] ); // handlers don't care
120 // Some basic input validation
121 $fileName = strtr( $fileName, '\\/', '__' );
123 // Actually fetch the image. Method depends on whether it is archived or not.
125 $repo = RepoGroup
::singleton()->getLocalRepo()->getTempRepo();
126 $img = new UnregisteredLocalFile( null, $repo,
127 # Temp files are hashed based on the name without the timestamp.
128 # The thumbnails will be hashed based on the entire name however.
129 # @TODO: fix this convention to actually be reasonable.
130 $repo->getZonePath( 'public' ) . '/' . $repo->getTempHashPath( $fileName ) . $fileName
132 } elseif ( $isOld ) {
133 // Format is <timestamp>!<name>
134 $bits = explode( '!', $fileName, 2 );
135 if ( count( $bits ) != 2 ) {
136 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
137 wfProfileOut( __METHOD__
);
140 $title = Title
::makeTitleSafe( NS_FILE
, $bits[1] );
142 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
143 wfProfileOut( __METHOD__
);
146 $img = RepoGroup
::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
148 $img = wfLocalFile( $fileName );
151 // Check the source file title
153 wfThumbError( 404, wfMessage( 'badtitletext' )->text() );
154 wfProfileOut( __METHOD__
);
158 // Check permissions if there are read restrictions
159 $varyHeader = array();
160 if ( !in_array( 'read', User
::getGroupPermissions( array( '*' ) ), true ) ) {
161 if ( !$img->getTitle() ||
!$img->getTitle()->userCan( 'read' ) ) {
162 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
163 'the source file.' );
164 wfProfileOut( __METHOD__
);
167 $headers[] = 'Cache-Control: private';
168 $varyHeader[] = 'Cookie';
171 // Check the source file storage path
172 if ( !$img->exists() ) {
173 wfThumbError( 404, "The source file '$fileName' does not exist." );
174 wfProfileOut( __METHOD__
);
176 } elseif ( $img->getPath() === false ) {
177 wfThumbError( 500, "The source file '$fileName' is not locally accessible." );
178 wfProfileOut( __METHOD__
);
182 // Check IMS against the source file
183 // This means that clients can keep a cached copy even after it has been deleted on the server
184 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
186 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
188 wfSuppressWarnings();
189 $imsUnix = strtotime( $imsString );
191 if ( wfTimestamp( TS_UNIX
, $img->getTimestamp() ) <= $imsUnix ) {
192 header( 'HTTP/1.1 304 Not Modified' );
193 wfProfileOut( __METHOD__
);
198 // Get the normalized thumbnail name from the parameters...
200 $thumbName = $img->thumbName( $params );
201 if ( !strlen( $thumbName ) ) { // invalid params?
202 wfThumbError( 400, 'The specified thumbnail parameters are not valid.' );
203 wfProfileOut( __METHOD__
);
206 $thumbName2 = $img->thumbName( $params, File
::THUMB_FULL_NAME
); // b/c; "long" style
207 } catch ( MWException
$e ) {
208 wfThumbError( 500, $e->getHTML() );
209 wfProfileOut( __METHOD__
);
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 ( rawurldecode( $params['rel404'] ) === $img->getThumbRel( $thumbName ) ) {
219 // Request for the canonical thumbnail name
220 } elseif ( rawurldecode( $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: ' .
225 wfExpandUrl( $img->getThumbUrl( $thumbName ), PROTO_CURRENT
) );
226 $response->header( 'Expires: ' .
227 gmdate( 'D, d M Y H:i:s', time() +
7 * 86400 ) . ' GMT' );
228 if ( $wgVaryOnXFP ) {
229 $varyHeader[] = 'X-Forwarded-Proto';
231 if ( count( $varyHeader ) ) {
232 $response->header( 'Vary: ' . implode( ', ', $varyHeader ) );
234 wfProfileOut( __METHOD__
);
237 wfThumbError( 404, "The given path of the specified thumbnail is incorrect;
238 expected '" . $img->getThumbRel( $thumbName ) . "' but got '" .
239 rawurldecode( $params['rel404'] ) . "'." );
240 wfProfileOut( __METHOD__
);
245 // Suggest a good name for users downloading this thumbnail
246 $headers[] = "Content-Disposition: {$img->getThumbDisposition( $thumbName )}";
248 if ( count( $varyHeader ) ) {
249 $headers[] = 'Vary: ' . implode( ', ', $varyHeader );
252 // Stream the file if it exists already...
253 $thumbPath = $img->getThumbPath( $thumbName );
254 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
255 $img->getRepo()->streamFile( $thumbPath, $headers );
256 wfProfileOut( __METHOD__
);
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>