4 * PHP script to stream out an image thumbnail.
9 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
10 if ( isset( $_SERVER['MW_COMPILED'] ) ) {
11 require( 'phase3/includes/WebStart.php' );
13 require( dirname( __FILE__
) . '/includes/WebStart.php' );
16 // Don't use fancy mime detection, just check the file extension for jpg/gif/png
17 $wgTrivialMimeDetection = true;
19 if ( defined( 'THUMB_HANDLER' ) ) {
20 // Called from thumb_handler.php via 404; extract params from the URI...
23 // Called directly, use $_REQUEST params
24 wfThumbHandleRequest();
28 //--------------------------------------------------------------------------
31 * Handle a thumbnail request via query parameters
33 function wfThumbHandleRequest() {
34 $params = get_magic_quotes_gpc()
35 ?
array_map( 'stripslashes', $_REQUEST )
38 wfStreamThumb( $params ); // stream the thumbnail
42 * Handle a thumbnail request via thumbnail file URL
44 function wfThumbHandle404() {
45 # lighttpd puts the original request in REQUEST_URI, while
46 # sjs sets that to the 404 handler, and puts the original
47 # request in REDIRECT_URL.
48 if ( isset( $_SERVER['REDIRECT_URL'] ) ) {
49 # The URL is un-encoded, so put it back how it was.
50 $uri = str_replace( "%2F", "/", urlencode( $_SERVER['REDIRECT_URL'] ) );
52 $uri = $_SERVER['REQUEST_URI'];
55 $params = wfExtractThumbParams( $uri ); // basic wiki URL param extracting
56 if ( $params == null ) {
57 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
61 wfStreamThumb( $params ); // stream the thumbnail
65 * Stream a thumbnail specified by parameters
67 * @param $params Array
69 function wfStreamThumb( array $params ) {
70 wfProfileIn( __METHOD__
);
72 $headers = array(); // HTTP headers to send
74 $fileName = isset( $params['f'] ) ?
$params['f'] : '';
75 unset( $params['f'] );
77 // Backwards compatibility parameters
78 if ( isset( $params['w'] ) ) {
79 $params['width'] = $params['w'];
80 unset( $params['w'] );
82 if ( isset( $params['p'] ) ) {
83 $params['page'] = $params['p'];
85 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
87 // Is this a thumb of an archived file?
88 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
89 unset( $params['archived'] );
91 // Some basic input validation
92 $fileName = strtr( $fileName, '\\/', '__' );
94 // Actually fetch the image. Method depends on whether it is archived or not.
96 // Format is <timestamp>!<name>
97 $bits = explode( '!', $fileName, 2 );
98 if ( count( $bits ) != 2 ) {
99 wfThumbError( 404, wfMsg( 'badtitletext' ) );
100 wfProfileOut( __METHOD__
);
103 $title = Title
::makeTitleSafe( NS_FILE
, $bits[1] );
105 wfThumbError( 404, wfMsg( 'badtitletext' ) );
106 wfProfileOut( __METHOD__
);
109 $img = RepoGroup
::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
111 $img = wfLocalFile( $fileName );
114 // Check permissions if there are read restrictions
115 if ( !in_array( 'read', User
::getGroupPermissions( array( '*' ) ), true ) ) {
116 if ( !$img->getTitle()->userCan( 'read' ) ) {
117 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
118 'the source file.' );
119 wfProfileOut( __METHOD__
);
122 $headers[] = 'Cache-Control: private';
123 $headers[] = 'Vary: Cookie';
126 // Check the source file storage path
128 wfThumbError( 404, wfMsg( 'badtitletext' ) );
129 wfProfileOut( __METHOD__
);
132 if ( !$img->exists() ) {
133 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
134 wfProfileOut( __METHOD__
);
137 $sourcePath = $img->getPath();
138 if ( $sourcePath === false ) {
139 wfThumbError( 500, 'The source file is not locally accessible.' );
140 wfProfileOut( __METHOD__
);
144 // Check IMS against the source file
145 // This means that clients can keep a cached copy even after it has been deleted on the server
146 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
148 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
150 wfSuppressWarnings();
151 $imsUnix = strtotime( $imsString );
153 $sourceTsUnix = wfTimestamp( TS_UNIX
, $img->getTimestamp() );
154 if ( $sourceTsUnix <= $imsUnix ) {
155 header( 'HTTP/1.1 304 Not Modified' );
156 wfProfileOut( __METHOD__
);
161 // Stream the file if it exists already...
163 $thumbName = $img->thumbName( $params );
164 if ( strlen( $thumbName ) ) { // valid params?
165 $thumbPath = $img->getThumbPath( $thumbName );
166 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
167 $img->getRepo()->streamFile( $thumbPath, $headers );
168 wfProfileOut( __METHOD__
);
172 } catch ( MWException
$e ) {
173 wfThumbError( 500, $e->getHTML() );
174 wfProfileOut( __METHOD__
);
178 // Thumbnail isn't already there, so create the new thumbnail...
180 $thumb = $img->transform( $params, File
::RENDER_NOW
);
181 } catch ( Exception
$ex ) {
182 // Tried to select a page on a non-paged file?
186 // Check for thumbnail generation errors...
189 $errorMsg = wfMsgHtml( 'thumbnail_error', 'File::transform() returned false' );
190 } elseif ( $thumb->isError() ) {
191 $errorMsg = $thumb->getHtmlMsg();
192 } elseif ( !$thumb->hasFile() ) {
193 $errorMsg = wfMsgHtml( 'thumbnail_error', 'No path supplied in thumbnail object' );
194 } elseif ( $thumb->fileIsSource() ) {
195 $errorMsg = wfMsgHtml( 'thumbnail_error',
196 'Image was not scaled, is the requested width bigger than the source?' );
199 if ( $errorMsg !== false ) {
200 wfThumbError( 500, $errorMsg );
202 // Stream the file if there were no errors
203 $thumb->streamFile( $headers );
206 wfProfileOut( __METHOD__
);
210 * Extract the required params for thumb.php from the thumbnail request URI.
211 * At least 'width' and 'f' should be set if the result is an array.
213 * @param $uri String Thumbnail request URI
214 * @return Array|null associative params array or null
216 function wfExtractThumbParams( $uri ) {
217 $repo = RepoGroup
::singleton()->getLocalRepo();
219 $hashDirRegex = $subdirRegex = '';
220 for ( $i = 0; $i < $repo->getHashLevels(); $i++
) {
221 $subdirRegex .= '[0-9a-f]';
222 $hashDirRegex .= "$subdirRegex/";
224 $zoneUrlRegex = preg_quote( $repo->getZoneUrl( 'thumb' ) );
226 $thumbUrlRegex = "!^$zoneUrlRegex(/archive|/temp|)/$hashDirRegex([^/]*)/([^/]*)$!";
228 // Check if this is a valid looking thumbnail request...
229 if ( preg_match( $thumbUrlRegex, $uri, $matches ) ) {
230 list( /* all */, $archOrTemp, $filename, $thumbname ) = $matches;
231 $filename = urldecode( $filename );
232 $thumbname = urldecode( $thumbname );
234 $params = array( 'f' => $filename );
235 if ( $archOrTemp == '/archive' ) {
236 $params['archived'] = 1;
237 } elseif ( $archOrTemp == '/temp' ) {
241 // Check if the parameters can be extracted from the thumbnail name...
242 // @TODO: remove 'page' stuff and make ProofreadPage handle it via hook.
243 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
244 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
245 $params['width'] = $size;
247 $params['page'] = $pagenum;
249 return $params; // valid thumbnail URL
250 // Hooks return false if they manage to *resolve* the parameters
251 } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
252 return $params; // valid thumbnail URL (via extension or config)
256 return null; // not a valid thumbnail URL
260 * Output a thumbnail generation error message
262 * @param $status integer
265 function wfThumbError( $status, $msg ) {
266 global $wgShowHostnames;
268 header( 'Cache-Control: no-cache' );
269 header( 'Content-Type: text/html; charset=utf-8' );
270 if ( $status == 404 ) {
271 header( 'HTTP/1.1 404 Not found' );
272 } elseif ( $status == 403 ) {
273 header( 'HTTP/1.1 403 Forbidden' );
274 header( 'Vary: Cookie' );
276 header( 'HTTP/1.1 500 Internal server error' );
278 if ( $wgShowHostnames ) {
279 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : '' );
280 $hostname = htmlspecialchars( wfHostname() );
281 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
286 <html><head><title>Error generating thumbnail</title></head>
288 <h1>Error generating thumbnail</h1>