(bug 32984) ar_sha1 might not be set
[lhc/web/wiklou.git] / thumb.php
1 <?php
2
3 /**
4 * PHP script to stream out an image thumbnail.
5 *
6 * @file
7 * @ingroup Media
8 */
9 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
10 if ( isset( $_SERVER['MW_COMPILED'] ) ) {
11 require( 'phase3/includes/WebStart.php' );
12 } else {
13 require( dirname( __FILE__ ) . '/includes/WebStart.php' );
14 }
15
16 // Don't use fancy mime detection, just check the file extension for jpg/gif/png
17 $wgTrivialMimeDetection = true;
18
19 if ( defined( 'THUMB_HANDLER' ) ) {
20 // Called from thumb_handler.php via 404; extract params from the URI...
21 wfThumbHandle404();
22 } else {
23 // Called directly, use $_REQUEST params
24 wfThumbHandleRequest();
25 }
26 wfLogProfilingData();
27
28 //--------------------------------------------------------------------------
29
30 /**
31 * Handle a thumbnail request via query parameters
32 *
33 * @return void
34 */
35 function wfThumbHandleRequest() {
36 $params = get_magic_quotes_gpc()
37 ? array_map( 'stripslashes', $_REQUEST )
38 : $_REQUEST;
39
40 wfStreamThumb( $params ); // stream the thumbnail
41 }
42
43 /**
44 * Handle a thumbnail request via thumbnail file URL
45 *
46 * @return void
47 */
48 function wfThumbHandle404() {
49 # lighttpd puts the original request in REQUEST_URI, while
50 # sjs sets that to the 404 handler, and puts the original
51 # request in REDIRECT_URL.
52 if ( isset( $_SERVER['REDIRECT_URL'] ) ) {
53 # The URL is un-encoded, so put it back how it was.
54 $uri = str_replace( "%2F", "/", urlencode( $_SERVER['REDIRECT_URL'] ) );
55 } else {
56 $uri = $_SERVER['REQUEST_URI'];
57 }
58
59 $params = wfExtractThumbParams( $uri ); // basic wiki URL param extracting
60 if ( $params == null ) {
61 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
62 return;
63 }
64
65 wfStreamThumb( $params ); // stream the thumbnail
66 }
67
68 /**
69 * Stream a thumbnail specified by parameters
70 *
71 * @param $params Array
72 * @return void
73 */
74 function wfStreamThumb( array $params ) {
75 wfProfileIn( __METHOD__ );
76
77 $headers = array(); // HTTP headers to send
78
79 $fileName = isset( $params['f'] ) ? $params['f'] : '';
80 unset( $params['f'] );
81
82 // Backwards compatibility parameters
83 if ( isset( $params['w'] ) ) {
84 $params['width'] = $params['w'];
85 unset( $params['w'] );
86 }
87 if ( isset( $params['p'] ) ) {
88 $params['page'] = $params['p'];
89 }
90 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
91
92 // Is this a thumb of an archived file?
93 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
94 unset( $params['archived'] );
95
96 // Some basic input validation
97 $fileName = strtr( $fileName, '\\/', '__' );
98
99 // Actually fetch the image. Method depends on whether it is archived or not.
100 if ( $isOld ) {
101 // Format is <timestamp>!<name>
102 $bits = explode( '!', $fileName, 2 );
103 if ( count( $bits ) != 2 ) {
104 wfThumbError( 404, wfMsg( 'badtitletext' ) );
105 wfProfileOut( __METHOD__ );
106 return;
107 }
108 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
109 if ( !$title ) {
110 wfThumbError( 404, wfMsg( 'badtitletext' ) );
111 wfProfileOut( __METHOD__ );
112 return;
113 }
114 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
115 } else {
116 $img = wfLocalFile( $fileName );
117 }
118
119 // Check permissions if there are read restrictions
120 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
121 if ( !$img->getTitle()->userCanRead() ) {
122 wfThumbError( 403, 'Access denied. You do not have permission to access ' .
123 'the source file.' );
124 wfProfileOut( __METHOD__ );
125 return;
126 }
127 $headers[] = 'Cache-Control: private';
128 $headers[] = 'Vary: Cookie';
129 }
130
131 if ( !$img ) {
132 wfThumbError( 404, wfMsg( 'badtitletext' ) );
133 wfProfileOut( __METHOD__ );
134 return;
135 }
136 if ( !$img->exists() ) {
137 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
138 wfProfileOut( __METHOD__ );
139 return;
140 }
141 $sourcePath = $img->getPath();
142 if ( $sourcePath === false ) {
143 wfThumbError( 500, 'The source file is not locally accessible.' );
144 wfProfileOut( __METHOD__ );
145 return;
146 }
147
148 // Check IMS against the source file
149 // This means that clients can keep a cached copy even after it has been deleted on the server
150 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
151 // Fix IE brokenness
152 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
153 // Calculate time
154 wfSuppressWarnings();
155 $imsUnix = strtotime( $imsString );
156 $stat = stat( $sourcePath );
157 wfRestoreWarnings();
158 if ( $stat['mtime'] <= $imsUnix ) {
159 header( 'HTTP/1.1 304 Not Modified' );
160 wfProfileOut( __METHOD__ );
161 return;
162 }
163 }
164
165 // Stream the file if it exists already...
166 try {
167 $thumbName = $img->thumbName( $params );
168 if ( $thumbName !== false ) { // valid params?
169 $thumbPath = $img->getThumbPath( $thumbName );
170 if ( is_file( $thumbPath ) ) {
171 StreamFile::stream( $thumbPath, $headers );
172 wfProfileOut( __METHOD__ );
173 return;
174 }
175 }
176 } catch ( MWException $e ) {
177 wfThumbError( 500, $e->getHTML() );
178 wfProfileOut( __METHOD__ );
179 return;
180 }
181
182 // Thumbnail isn't already there, so create the new thumbnail...
183 try {
184 $thumb = $img->transform( $params, File::RENDER_NOW );
185 } catch( Exception $ex ) {
186 // Tried to select a page on a non-paged file?
187 $thumb = false;
188 }
189
190 // Check for thumbnail generation errors...
191 $errorMsg = false;
192 if ( !$thumb ) {
193 $errorMsg = wfMsgHtml( 'thumbnail_error', 'File::transform() returned false' );
194 } elseif ( $thumb->isError() ) {
195 $errorMsg = $thumb->getHtmlMsg();
196 } elseif ( !$thumb->getPath() ) {
197 $errorMsg = wfMsgHtml( 'thumbnail_error', 'No path supplied in thumbnail object' );
198 } elseif ( $thumb->getPath() == $img->getPath() ) {
199 $errorMsg = wfMsgHtml( 'thumbnail_error', 'Image was not scaled, ' .
200 'is the requested width bigger than the source?' );
201 }
202
203 if ( $errorMsg !== false ) {
204 wfThumbError( 500, $errorMsg );
205 } else {
206 // Stream the file if there were no errors
207 StreamFile::stream( $thumb->getPath(), $headers );
208 }
209
210 wfProfileOut( __METHOD__ );
211 }
212
213 /**
214 * Extract the required params for thumb.php from the thumbnail request URI.
215 * At least 'width' and 'f' should be set if the result is an array.
216 *
217 * @param $uri String Thumbnail request URI
218 * @return Array|null associative params array or null
219 */
220 function wfExtractThumbParams( $uri ) {
221 $repo = RepoGroup::singleton()->getLocalRepo();
222
223 $hashDirRegex = $subdirRegex = '';
224 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
225 $subdirRegex .= '[0-9a-f]';
226 $hashDirRegex .= "$subdirRegex/";
227 }
228 $zoneUrlRegex = preg_quote( $repo->getZoneUrl( 'thumb' ) );
229
230 $thumbUrlRegex = "!^$zoneUrlRegex(/archive|/temp|)/$hashDirRegex([^/]*)/([^/]*)$!";
231
232 // Check if this is a valid looking thumbnail request...
233 if ( preg_match( $thumbUrlRegex, $uri, $matches ) ) {
234 list( /* all */, $archOrTemp, $filename, $thumbname ) = $matches;
235
236 $params = array( 'f' => $filename );
237 if ( $archOrTemp == '/archive' ) {
238 $params['archived'] = 1;
239 } elseif ( $archOrTemp == '/temp' ) {
240 $params['temp'] = 1;
241 }
242
243 // Check if the parameters can be extracted from the thumbnail name...
244 // @TODO: remove 'page' stuff and make ProofreadPage handle it via hook.
245 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
246 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
247 $params['width'] = $size;
248 if ( $pagenum ) {
249 $params['page'] = $pagenum;
250 }
251 return $params; // valid thumbnail URL
252 // Hooks return false if they manage to *resolve* the parameters
253 } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
254 return $params; // valid thumbnail URL (via extension or config)
255 }
256 }
257
258 return null; // not a valid thumbnail URL
259 }
260
261 /**
262 * Output a thumbnail generation error message
263 *
264 * @param $status integer
265 * @param $msg string
266 * @return void
267 */
268 function wfThumbError( $status, $msg ) {
269 global $wgShowHostnames;
270
271 header( 'Cache-Control: no-cache' );
272 header( 'Content-Type: text/html; charset=utf-8' );
273 if ( $status == 404 ) {
274 header( 'HTTP/1.1 404 Not found' );
275 } elseif ( $status == 403 ) {
276 header( 'HTTP/1.1 403 Forbidden' );
277 header( 'Vary: Cookie' );
278 } else {
279 header( 'HTTP/1.1 500 Internal server error' );
280 }
281 if ( $wgShowHostnames ) {
282 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
283 $hostname = htmlspecialchars( wfHostname() );
284 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
285 } else {
286 $debug = "";
287 }
288 echo <<<EOT
289 <html><head><title>Error generating thumbnail</title></head>
290 <body>
291 <h1>Error generating thumbnail</h1>
292 <p>
293 $msg
294 </p>
295 $debug
296 </body>
297 </html>
298
299 EOT;
300 }
301