MediaWiki  master
img_auth.php
Go to the documentation of this file.
1 <?php
42 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
43 define( 'MW_ENTRY_POINT', 'img_auth' );
44 require __DIR__ . '/includes/WebStart.php';
45 
47 
49 $mediawiki->doPostOutputShutdown();
50 
51 function wfImageAuthMain() {
53 
54  $services = \MediaWiki\MediaWikiServices::getInstance();
55  $permissionManager = $services->getPermissionManager();
56 
57  $request = RequestContext::getMain()->getRequest();
58  $publicWiki = in_array( 'read', $permissionManager->getGroupPermissions( [ '*' ] ), true );
59 
60  // Find the path assuming the request URL is relative to the local public zone URL
61  $baseUrl = $services->getRepoGroup()->getLocalRepo()->getZoneUrl( 'public' );
62  if ( $baseUrl[0] === '/' ) {
63  $basePath = $baseUrl;
64  } else {
65  $basePath = parse_url( $baseUrl, PHP_URL_PATH );
66  }
68 
69  if ( $path === false ) {
70  // Try instead assuming img_auth.php is the base path
71  $basePath = $wgImgAuthPath ?: "$wgScriptPath/img_auth.php";
73  }
74 
75  if ( $path === false ) {
76  wfForbidden( 'img-auth-accessdenied', 'img-auth-notindir' );
77  return;
78  }
79 
80  if ( $path === '' || $path[0] !== '/' ) {
81  // Make sure $path has a leading /
82  $path = "/" . $path;
83  }
84 
85  $user = RequestContext::getMain()->getUser();
86 
87  // Various extensions may have their own backends that need access.
88  // Check if there is a special backend and storage base path for this file.
89  foreach ( $wgImgAuthUrlPathMap as $prefix => $storageDir ) {
90  $prefix = rtrim( $prefix, '/' ) . '/'; // implicit trailing slash
91  if ( strpos( $path, $prefix ) === 0 ) {
92  $be = $services->getFileBackendGroup()->backendFromPath( $storageDir );
93  $filename = $storageDir . substr( $path, strlen( $prefix ) ); // strip prefix
94  // Check basic user authorization
95  $isAllowedUser = $permissionManager->userHasRight( $user, 'read' );
96  if ( !$isAllowedUser ) {
97  wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $path );
98  return;
99  }
100  if ( $be->fileExists( [ 'src' => $filename ] ) ) {
101  wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
102  $be->streamFile( [
103  'src' => $filename,
104  'headers' => [ 'Cache-Control: private', 'Vary: Cookie' ]
105  ] );
106  } else {
107  wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $path );
108  }
109  return;
110  }
111  }
112 
113  // Get the local file repository
114  $repo = $services->getRepoGroup()->getRepo( 'local' );
115  $zone = strstr( ltrim( $path, '/' ), '/', true );
116 
117  // Get the full file storage path and extract the source file name.
118  // (e.g. 120px-Foo.png => Foo.png or page2-120px-Foo.png => Foo.png).
119  // This only applies to thumbnails/transcoded, and each of them should
120  // be under a folder that has the source file name.
121  if ( $zone === 'thumb' || $zone === 'transcoded' ) {
122  $name = wfBaseName( dirname( $path ) );
123  $filename = $repo->getZonePath( $zone ) . substr( $path, strlen( "/" . $zone ) );
124  // Check to see if the file exists
125  if ( !$repo->fileExists( $filename ) ) {
126  wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
127  return;
128  }
129  } else {
130  $name = wfBaseName( $path ); // file is a source file
131  $filename = $repo->getZonePath( 'public' ) . $path;
132  // Check to see if the file exists and is not deleted
133  $bits = explode( '!', $name, 2 );
134  if ( substr( $path, 0, 9 ) === '/archive/' && count( $bits ) == 2 ) {
135  $file = $repo->newFromArchiveName( $bits[1], $name );
136  } else {
137  $file = $repo->newFile( $name );
138  }
139  if ( !$file->exists() || $file->isDeleted( File::DELETED_FILE ) ) {
140  wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
141  return;
142  }
143  }
144 
145  $headers = []; // extra HTTP headers to send
146 
147  $title = Title::makeTitleSafe( NS_FILE, $name );
148 
149  if ( !$publicWiki ) {
150  // For private wikis, run extra auth checks and set cache control headers
151  $headers['Cache-Control'] = 'private';
152  $headers['Vary'] = 'Cookie';
153 
154  if ( !$title instanceof Title ) { // files have valid titles
155  wfForbidden( 'img-auth-accessdenied', 'img-auth-badtitle', $name );
156  return;
157  }
158 
159  // Run hook for extension authorization plugins
161  $result = null;
162  if ( !Hooks::runner()->onImgAuthBeforeStream( $title, $path, $name, $result ) ) {
163  wfForbidden( $result[0], $result[1], array_slice( $result, 2 ) );
164  return;
165  }
166 
167  // Check user authorization for this title
168  // Checks Whitelist too
169 
170  if ( !$permissionManager->userCan( 'read', $user, $title ) ) {
171  wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $name );
172  return;
173  }
174  }
175 
176  if ( isset( $_SERVER['HTTP_RANGE'] ) ) {
177  $headers['Range'] = $_SERVER['HTTP_RANGE'];
178  }
179  if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
180  $headers['If-Modified-Since'] = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
181  }
182 
183  if ( $request->getCheck( 'download' ) ) {
184  $headers['Content-Disposition'] = 'attachment';
185  }
186 
187  // Allow modification of headers before streaming a file
188  Hooks::runner()->onImgAuthModifyHeaders( $title->getTitleValue(), $headers );
189 
190  // Stream the requested file
191  list( $headers, $options ) = HTTPFileStreamer::preprocessHeaders( $headers );
192  wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
193  $repo->streamFileWithStatus( $filename, $headers, $options );
194 }
195 
205 function wfForbidden( $msg1, $msg2, ...$args ) {
206  global $wgImgAuthDetails;
207 
208  $args = ( isset( $args[0] ) && is_array( $args[0] ) ) ? $args[0] : $args;
209 
210  $msgHdr = wfMessage( $msg1 )->text();
211  $detailMsgKey = $wgImgAuthDetails ? $msg2 : 'badaccess-group0';
212  $detailMsg = wfMessage( $detailMsgKey, $args )->text();
213 
214  wfDebugLog( 'img_auth',
215  "wfForbidden Hdr: " . wfMessage( $msg1 )->inLanguage( 'en' )->text() . " Msg: " .
216  wfMessage( $msg2, $args )->inLanguage( 'en' )->text()
217  );
218 
219  HttpStatus::header( 403 );
220  header( 'Cache-Control: no-cache' );
221  header( 'Content-Type: text/html; charset=utf-8' );
223  echo $templateParser->processTemplate( 'ImageAuthForbidden', [
224  'msgHdr' => $msgHdr,
225  'detailMsg' => $detailMsg,
226  ] );
227 }
WebRequest\getRequestPathSuffix
static getRequestPathSuffix( $basePath)
If the request URL matches a given base path, extract the path part of the request URL after that bas...
Definition: WebRequest.php:231
wfBaseName
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
Definition: GlobalFunctions.php:2313
NS_FILE
const NS_FILE
Definition: Defines.php:75
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1219
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:988
HTTPFileStreamer\preprocessHeaders
static preprocessHeaders( $headers)
Takes HTTP headers in a name => value format and converts them to the weird format expected by stream...
Definition: HTTPFileStreamer.php:51
MediaWiki
A helper class for throttling authentication attempts.
$args
if( $line===false) $args
Definition: mcc.php:124
$wgImgAuthDetails
$wgImgAuthDetails
Set this to true if you use img_auth and want the user to see details on why access failed.
Definition: DefaultSettings.php:508
$title
$title
Definition: testCompression.php:38
$wgImgAuthPath
$wgImgAuthPath
The base path for img_auth.php.
Definition: DefaultSettings.php:287
$wgImgAuthUrlPathMap
$wgImgAuthUrlPathMap
Map of relative URL directories to match to internal mwstore:// base storage paths.
Definition: DefaultSettings.php:524
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:618
$templateParser
$templateParser
Definition: NoLocalSettings.php:47
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:172
$mediawiki
$mediawiki
Definition: img_auth.php:48
wfImageAuthMain
wfImageAuthMain()
Definition: img_auth.php:51
wfForbidden
wfForbidden( $msg1, $msg2,... $args)
Issue a standard HTTP 403 Forbidden header ($msg1-a message index, not a message) and an error messag...
Definition: img_auth.php:205
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:453
Title
Represents a title within MediaWiki.
Definition: Title.php:42
HttpStatus\header
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
$path
$path
Definition: NoLocalSettings.php:25
$basePath
$basePath
Definition: addSite.php:5
File\DELETED_FILE
const DELETED_FILE
Definition: File.php:67
$wgScriptPath
$wgScriptPath
The path we should point to.
Definition: DefaultSettings.php:179
TemplateParser
Definition: TemplateParser.php:27