-if( !file_exists( $filename ) ) {
- wfDebugLog( 'img_auth', "requested file does not exist: $filename" );
- wfForbidden();
-}
-if( is_dir( $filename ) ) {
- wfDebugLog( 'img_auth', "requested file is a directory: $filename" );
- wfForbidden();
-}
+$filename = realpath( $wgUploadDirectory . $path );
+$realUpload = realpath( $wgUploadDirectory );
+
+// Basic directory traversal check
+if( substr( $filename, 0, strlen( $realUpload ) ) != $realUpload )
+ wfForbidden('img-auth-accessdenied','img-auth-notindir');
+
+// Extract the file name and chop off the size specifier
+// (e.g. 120px-Foo.png => Foo.png)
+$name = wfBaseName( $path );
+if( preg_match( '!\d+px-(.*)!i', $name, $m ) )
+ $name = $m[1];
+
+// Check to see if the file exists
+if( !file_exists( $filename ) )
+ wfForbidden('img-auth-accessdenied','img-auth-nofile',$filename);
+
+// Check to see if tried to access a directory
+if( is_dir( $filename ) )
+ wfForbidden('img-auth-accessdenied','img-auth-isdir',$filename);
+
+
+$title = Title::makeTitleSafe( NS_FILE, $name );