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 $perms = User
::getGroupPermissions( array( '*' ) );
21 if ( in_array( 'read', $perms, true ) ) {
22 wfDebugLog( 'img_auth', 'Public wiki' );
26 // Extract path and image information
27 if( !isset( $_SERVER['PATH_INFO'] ) ) {
28 wfDebugLog( 'img_auth', 'Missing PATH_INFO' );
32 $path = $_SERVER['PATH_INFO'];
33 $filename = realpath( $wgUploadDirectory . $_SERVER['PATH_INFO'] );
34 $realUpload = realpath( $wgUploadDirectory );
35 wfDebugLog( 'img_auth', "\$path is {$path}" );
36 wfDebugLog( 'img_auth', "\$filename is {$filename}" );
38 // Basic directory traversal check
39 if( substr( $filename, 0, strlen( $realUpload ) ) != $realUpload ) {
40 wfDebugLog( 'img_auth', 'Requested path not in upload directory' );
44 // Extract the file name and chop off the size specifier
45 // (e.g. 120px-Foo.png => Foo.png)
46 $name = wfBaseName( $path );
47 if( preg_match( '!\d+px-(.*)!i', $name, $m ) )
49 wfDebugLog( 'img_auth', "\$name is {$name}" );
51 $title = Title
::makeTitleSafe( NS_FILE
, $name );
52 if( !$title instanceof Title
) {
53 wfDebugLog( 'img_auth', "Unable to construct a valid Title from `{$name}`" );
56 $title = $title->getPrefixedText();
58 // Check the whitelist if needed
59 if( !$wgUser->getId() && ( !is_array( $wgWhitelistRead ) ||
!in_array( $title, $wgWhitelistRead ) ) ) {
60 wfDebugLog( 'img_auth', "Not logged in and `{$title}` not in whitelist." );
64 if( !file_exists( $filename ) ) {
65 wfDebugLog( 'img_auth', "`{$filename}` does not exist" );
68 if( is_dir( $filename ) ) {
69 wfDebugLog( 'img_auth', "`{$filename}` is a directory" );
73 // Stream the requested file
74 wfDebugLog( 'img_auth', "Streaming `{$filename}`" );
75 wfStreamFile( $filename, array( 'Cache-Control: private', 'Vary: Cookie' ) );
79 * Issue a standard HTTP 403 Forbidden header and a basic
80 * error message, then end the script
82 function wfForbidden() {
83 header( 'HTTP/1.0 403 Forbidden' );
84 header( 'Vary: Cookie' );
85 header( 'Content-Type: text/html; charset=utf-8' );
89 <h1>Access Denied</h1>
90 <p>You need to log in to access files on this server.</p>
99 * Show a 403 error for use when the wiki is public
101 function wfPublicError() {
102 header( 'HTTP/1.0 403 Forbidden' );
103 header( 'Content-Type: text/html; charset=utf-8' );
107 <h1>Access Denied</h1>
108 <p>The function of img_auth.php is to output files from a private wiki. This wiki
109 is configured as a public wiki. For optimal security, img_auth.php is disabled in
115 wfLogProfilingData();