Attempt to avoid a warning I got during input:
[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()->userCan( 'read' ) ) {
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 // Check the source file storage path
132 if ( !$img ) {
133 wfThumbError( 404, wfMsg( 'badtitletext' ) );
134 wfProfileOut( __METHOD__ );
135 return;
136 }
137 if ( !$img->exists() ) {
138 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
139 wfProfileOut( __METHOD__ );
140 return;
141 }
142 $sourcePath = $img->getPath();
143 if ( $sourcePath === false ) {
144 wfThumbError( 500, 'The source file is not locally accessible.' );
145 wfProfileOut( __METHOD__ );
146 return;
147 }
148
149 // Check IMS against the source file
150 // This means that clients can keep a cached copy even after it has been deleted on the server
151 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
152 // Fix IE brokenness
153 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
154 // Calculate time
155 wfSuppressWarnings();
156 $imsUnix = strtotime( $imsString );
157 wfRestoreWarnings();
158 $sourceTsUnix = wfTimestamp( TS_UNIX, $img->getTimestamp() );
159 if ( $sourceTsUnix <= $imsUnix ) {
160 header( 'HTTP/1.1 304 Not Modified' );
161 wfProfileOut( __METHOD__ );
162 return;
163 }
164 }
165
166 // Stream the file if it exists already...
167 try {
168 $thumbName = $img->thumbName( $params );
169 if ( strlen( $thumbName ) ) { // valid params?
170 $thumbPath = $img->getThumbPath( $thumbName );
171 if ( $img->getRepo()->fileExists( $thumbPath ) ) {
172 $img->getRepo()->streamFile( $thumbPath, $headers );
173 wfProfileOut( __METHOD__ );
174 return;
175 }
176 }
177 } catch ( MWException $e ) {
178 wfThumbError( 500, $e->getHTML() );
179 wfProfileOut( __METHOD__ );
180 return;
181 }
182
183 // Thumbnail isn't already there, so create the new thumbnail...
184 try {
185 $thumb = $img->transform( $params, File::RENDER_NOW );
186 } catch ( Exception $ex ) {
187 // Tried to select a page on a non-paged file?
188 $thumb = false;
189 }
190
191 // Check for thumbnail generation errors...
192 $errorMsg = false;
193 if ( !$thumb ) {
194 $errorMsg = wfMsgHtml( 'thumbnail_error', 'File::transform() returned false' );
195 } elseif ( $thumb->isError() ) {
196 $errorMsg = $thumb->getHtmlMsg();
197 } elseif ( !$thumb->hasFile() ) {
198 $errorMsg = wfMsgHtml( 'thumbnail_error', 'No path supplied in thumbnail object' );
199 } elseif ( $thumb->fileIsSource() ) {
200 $errorMsg = wfMsgHtml( 'thumbnail_error',
201 'Image was not scaled, is the requested width bigger than the source?' );
202 }
203
204 if ( $errorMsg !== false ) {
205 wfThumbError( 500, $errorMsg );
206 } else {
207 // Stream the file if there were no errors
208 $thumb->streamFile( $headers );
209 }
210
211 wfProfileOut( __METHOD__ );
212 }
213
214 /**
215 * Extract the required params for thumb.php from the thumbnail request URI.
216 * At least 'width' and 'f' should be set if the result is an array.
217 *
218 * @param $uri String Thumbnail request URI
219 * @return Array|null associative params array or null
220 */
221 function wfExtractThumbParams( $uri ) {
222 $repo = RepoGroup::singleton()->getLocalRepo();
223
224 $hashDirRegex = $subdirRegex = '';
225 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
226 $subdirRegex .= '[0-9a-f]';
227 $hashDirRegex .= "$subdirRegex/";
228 }
229 $zoneUrlRegex = preg_quote( $repo->getZoneUrl( 'thumb' ) );
230
231 $thumbUrlRegex = "!^$zoneUrlRegex(/archive|/temp|)/$hashDirRegex([^/]*)/([^/]*)$!";
232
233 // Check if this is a valid looking thumbnail request...
234 if ( preg_match( $thumbUrlRegex, $uri, $matches ) ) {
235 list( /* all */, $archOrTemp, $filename, $thumbname ) = $matches;
236 $filename = urldecode( $filename );
237 $thumbname = urldecode( $thumbname );
238
239 $params = array( 'f' => $filename );
240 if ( $archOrTemp == '/archive' ) {
241 $params['archived'] = 1;
242 } elseif ( $archOrTemp == '/temp' ) {
243 $params['temp'] = 1;
244 }
245
246 // Check if the parameters can be extracted from the thumbnail name...
247 // @TODO: remove 'page' stuff and make ProofreadPage handle it via hook.
248 if ( preg_match( '!^(page(\d*)-)*(\d*)px-[^/]*$!', $thumbname, $matches ) ) {
249 list( /* all */, $pagefull, $pagenum, $size ) = $matches;
250 $params['width'] = $size;
251 if ( $pagenum ) {
252 $params['page'] = $pagenum;
253 }
254 return $params; // valid thumbnail URL
255 // Hooks return false if they manage to *resolve* the parameters
256 } elseif ( !wfRunHooks( 'ExtractThumbParameters', array( $thumbname, &$params ) ) ) {
257 return $params; // valid thumbnail URL (via extension or config)
258 }
259 }
260
261 return null; // not a valid thumbnail URL
262 }
263
264 /**
265 * Output a thumbnail generation error message
266 *
267 * @param $status integer
268 * @param $msg string
269 * @return void
270 */
271 function wfThumbError( $status, $msg ) {
272 global $wgShowHostnames;
273
274 header( 'Cache-Control: no-cache' );
275 header( 'Content-Type: text/html; charset=utf-8' );
276 if ( $status == 404 ) {
277 header( 'HTTP/1.1 404 Not found' );
278 } elseif ( $status == 403 ) {
279 header( 'HTTP/1.1 403 Forbidden' );
280 header( 'Vary: Cookie' );
281 } else {
282 header( 'HTTP/1.1 500 Internal server error' );
283 }
284 if ( $wgShowHostnames ) {
285 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
286 $hostname = htmlspecialchars( wfHostname() );
287 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
288 } else {
289 $debug = "";
290 }
291 echo <<<EOT
292 <html><head><title>Error generating thumbnail</title></head>
293 <body>
294 <h1>Error generating thumbnail</h1>
295 <p>
296 $msg
297 </p>
298 $debug
299 </body>
300 </html>
301
302 EOT;
303 }