Kill "* @return void"
[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 function wfThumbHandleRequest() {
34 $params = get_magic_quotes_gpc()
35 ? array_map( 'stripslashes', $_REQUEST )
36 : $_REQUEST;
37
38 wfStreamThumb( $params ); // stream the thumbnail
39 }
40
41 /**
42 * Handle a thumbnail request via thumbnail file URL
43 */
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'] ) );
51 } else {
52 $uri = $_SERVER['REQUEST_URI'];
53 }
54
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.' );
58 return;
59 }
60
61 wfStreamThumb( $params ); // stream the thumbnail
62 }
63
64 /**
65 * Stream a thumbnail specified by parameters
66 *
67 * @param $params Array
68 */
69 function wfStreamThumb( array $params ) {
70 wfProfileIn( __METHOD__ );
71
72 $headers = array(); // HTTP headers to send
73
74 $fileName = isset( $params['f'] ) ? $params['f'] : '';
75 unset( $params['f'] );
76
77 // Backwards compatibility parameters
78 if ( isset( $params['w'] ) ) {
79 $params['width'] = $params['w'];
80 unset( $params['w'] );
81 }
82 if ( isset( $params['p'] ) ) {
83 $params['page'] = $params['p'];
84 }
85 unset( $params['r'] ); // ignore 'r' because we unconditionally pass File::RENDER
86
87 // Is this a thumb of an archived file?
88 $isOld = ( isset( $params['archived'] ) && $params['archived'] );
89 unset( $params['archived'] );
90
91 // Some basic input validation
92 $fileName = strtr( $fileName, '\\/', '__' );
93
94 // Actually fetch the image. Method depends on whether it is archived or not.
95 if ( $isOld ) {
96 // Format is <timestamp>!<name>
97 $bits = explode( '!', $fileName, 2 );
98 if ( count( $bits ) != 2 ) {
99 wfThumbError( 404, wfMsg( 'badtitletext' ) );
100 wfProfileOut( __METHOD__ );
101 return;
102 }
103 $title = Title::makeTitleSafe( NS_FILE, $bits[1] );
104 if ( !$title ) {
105 wfThumbError( 404, wfMsg( 'badtitletext' ) );
106 wfProfileOut( __METHOD__ );
107 return;
108 }
109 $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName( $title, $fileName );
110 } else {
111 $img = wfLocalFile( $fileName );
112 }
113
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__ );
120 return;
121 }
122 $headers[] = 'Cache-Control: private';
123 $headers[] = 'Vary: Cookie';
124 }
125
126 // Check the source file storage path
127 if ( !$img ) {
128 wfThumbError( 404, wfMsg( 'badtitletext' ) );
129 wfProfileOut( __METHOD__ );
130 return;
131 }
132 if ( !$img->exists() ) {
133 wfThumbError( 404, 'The source file for the specified thumbnail does not exist.' );
134 wfProfileOut( __METHOD__ );
135 return;
136 }
137 $sourcePath = $img->getPath();
138 if ( $sourcePath === false ) {
139 wfThumbError( 500, 'The source file is not locally accessible.' );
140 wfProfileOut( __METHOD__ );
141 return;
142 }
143
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'] ) ) {
147 // Fix IE brokenness
148 $imsString = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
149 // Calculate time
150 wfSuppressWarnings();
151 $imsUnix = strtotime( $imsString );
152 wfRestoreWarnings();
153 $sourceTsUnix = wfTimestamp( TS_UNIX, $img->getTimestamp() );
154 if ( $sourceTsUnix <= $imsUnix ) {
155 header( 'HTTP/1.1 304 Not Modified' );
156 wfProfileOut( __METHOD__ );
157 return;
158 }
159 }
160
161 // Stream the file if it exists already...
162 try {
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__ );
169 return;
170 }
171 }
172 } catch ( MWException $e ) {
173 wfThumbError( 500, $e->getHTML() );
174 wfProfileOut( __METHOD__ );
175 return;
176 }
177
178 // Thumbnail isn't already there, so create the new thumbnail...
179 try {
180 $thumb = $img->transform( $params, File::RENDER_NOW );
181 } catch ( Exception $ex ) {
182 // Tried to select a page on a non-paged file?
183 $thumb = false;
184 }
185
186 // Check for thumbnail generation errors...
187 $errorMsg = false;
188 if ( !$thumb ) {
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?' );
197 }
198
199 if ( $errorMsg !== false ) {
200 wfThumbError( 500, $errorMsg );
201 } else {
202 // Stream the file if there were no errors
203 $thumb->streamFile( $headers );
204 }
205
206 wfProfileOut( __METHOD__ );
207 }
208
209 /**
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.
212 *
213 * @param $uri String Thumbnail request URI
214 * @return Array|null associative params array or null
215 */
216 function wfExtractThumbParams( $uri ) {
217 $repo = RepoGroup::singleton()->getLocalRepo();
218
219 $hashDirRegex = $subdirRegex = '';
220 for ( $i = 0; $i < $repo->getHashLevels(); $i++ ) {
221 $subdirRegex .= '[0-9a-f]';
222 $hashDirRegex .= "$subdirRegex/";
223 }
224 $zoneUrlRegex = preg_quote( $repo->getZoneUrl( 'thumb' ) );
225
226 $thumbUrlRegex = "!^$zoneUrlRegex(/archive|/temp|)/$hashDirRegex([^/]*)/([^/]*)$!";
227
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 );
233
234 $params = array( 'f' => $filename );
235 if ( $archOrTemp == '/archive' ) {
236 $params['archived'] = 1;
237 } elseif ( $archOrTemp == '/temp' ) {
238 $params['temp'] = 1;
239 }
240
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;
246 if ( $pagenum ) {
247 $params['page'] = $pagenum;
248 }
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)
253 }
254 }
255
256 return null; // not a valid thumbnail URL
257 }
258
259 /**
260 * Output a thumbnail generation error message
261 *
262 * @param $status integer
263 * @param $msg string
264 */
265 function wfThumbError( $status, $msg ) {
266 global $wgShowHostnames;
267
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' );
275 } else {
276 header( 'HTTP/1.1 500 Internal server error' );
277 }
278 if ( $wgShowHostnames ) {
279 $url = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '' );
280 $hostname = htmlspecialchars( wfHostname() );
281 $debug = "<!-- $url -->\n<!-- $hostname -->\n";
282 } else {
283 $debug = "";
284 }
285 echo <<<EOT
286 <html><head><title>Error generating thumbnail</title></head>
287 <body>
288 <h1>Error generating thumbnail</h1>
289 <p>
290 $msg
291 </p>
292 $debug
293 </body>
294 </html>
295
296 EOT;
297 }