4 * Image authorisation script
8 * Set $wgUploadDirectory to a non-public directory (not web accessible)
9 * Set $wgUploadPath to point to this file
11 * Your server needs to support PATH_INFO; CGI-based configurations
15 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
16 require_once( dirname( __FILE__
) . '/includes/WebStart.php' );
17 wfProfileIn( 'img_auth.php' );
18 require_once( dirname( __FILE__
) . '/includes/StreamFile.php' );
20 // Extract path and image information
21 if( !isset( $_SERVER['PATH_INFO'] ) ) {
22 wfDebugLog( 'img_auth', 'Missing PATH_INFO' );
26 $path = $_SERVER['PATH_INFO'];
27 $filename = realpath( $wgUploadDirectory . $_SERVER['PATH_INFO'] );
28 $realUpload = realpath( $wgUploadDirectory );
29 wfDebugLog( 'img_auth', "\$path is {$path}" );
30 wfDebugLog( 'img_auth', "\$filename is {$filename}" );
32 // Basic directory traversal check
33 if( substr( $filename, 0, strlen( $realUpload ) ) != $realUpload ) {
34 wfDebugLog( 'img_auth', 'Requested path not in upload directory' );
38 // Extract the file name and chop off the size specifier
39 // (e.g. 120px-Foo.png => Foo.png)
40 $name = wfBaseName( $path );
41 if( preg_match( '!\d+px-(.*)!i', $name, $m ) )
43 wfDebugLog( 'img_auth', "\$name is {$name}" );
45 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
46 if( !$title instanceof Title
) {
47 wfDebugLog( 'img_auth', "Unable to construct a valid Title from `{$name}`" );
50 $title = $title->getPrefixedText();
52 // Check the whitelist if needed
53 if( !$wgUser->getId() && ( !is_array( $wgWhitelistRead ) ||
!in_array( $title, $wgWhitelistRead ) ) ) {
54 wfDebugLog( 'img_auth', "Not logged in and `{$title}` not in whitelist." );
58 if( !file_exists( $filename ) ) {
59 wfDebugLog( 'img_auth', "`{$filename}` does not exist" );
62 if( is_dir( $filename ) ) {
63 wfDebugLog( 'img_auth', "`{$filename}` is a directory" );
67 // Stream the requested file
68 wfDebugLog( 'img_auth', "Streaming `{$filename}`" );
69 wfStreamFile( $filename, array( 'Cache-Control: private', 'Vary: Cookie' ) );
73 * Issue a standard HTTP 403 Forbidden header and a basic
74 * error message, then end the script
76 function wfForbidden() {
77 header( 'HTTP/1.0 403 Forbidden' );
78 header( 'Vary: Cookie' );
79 header( 'Content-Type: text/html; charset=utf-8' );
83 <h1>Access Denied</h1>
84 <p>You need to log in to access files on this server.</p>