MediaWiki master
AuthenticatedFileEntryPoint.php
Go to the documentation of this file.
1<?php
13
24
26
30 public function execute() {
31 $services = $this->getServiceContainer();
32 $permissionManager = $services->getPermissionManager();
33
34 $request = $this->getRequest();
35 $publicWiki = $services->getGroupPermissionsLookup()->groupHasPermission( '*', 'read' );
36
37 // Find the path assuming the request URL is relative to the local public zone URL
38 $baseUrl = $services->getRepoGroup()->getLocalRepo()->getZoneUrl( 'public' );
39 if ( $baseUrl[0] === '/' ) {
40 $basePath = $baseUrl;
41 } else {
42 $basePath = parse_url( $baseUrl, PHP_URL_PATH );
43 }
44 $path = $this->getRequestPathSuffix( "$basePath" );
45
46 if ( $path === false ) {
47 // Try instead assuming img_auth.php is the base path
48 $basePath = $this->getConfig( MainConfigNames::ImgAuthPath )
49 ?: $this->getConfig( MainConfigNames::ScriptPath ) . '/img_auth.php';
50 $path = $this->getRequestPathSuffix( $basePath );
51 }
52
53 if ( $path === false ) {
54 $this->forbidden( 'img-auth-accessdenied', 'img-auth-notindir' );
55 return;
56 }
57
58 if ( $path === '' || $path[0] !== '/' ) {
59 // Make sure $path has a leading /
60 $path = "/" . $path;
61 }
62
63 $user = $this->getContext()->getUser();
64
65 // Various extensions may have their own backends that need access.
66 // Check if there is a special backend and storage base path for this file.
68 foreach ( $pathMap as $prefix => $storageDir ) {
69 $prefix = rtrim( $prefix, '/' ) . '/'; // implicit trailing slash
70 if ( str_starts_with( $path, $prefix ) ) {
71 $be = $services->getFileBackendGroup()->backendFromPath( $storageDir );
72 $filename = $storageDir . substr( $path, strlen( $prefix ) ); // strip prefix
73 // Check basic user authorization
74 $isAllowedUser = $permissionManager->userHasRight( $user, 'read' );
75 if ( !$isAllowedUser ) {
76 $this->forbidden( 'img-auth-accessdenied', 'img-auth-noread', $path );
77 return;
78 }
79 if ( $be && $be->fileExists( [ 'src' => $filename ] ) ) {
80 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
81 $be->streamFile( [
82 'src' => $filename,
83 'headers' => [ 'Cache-Control: private', 'Vary: Cookie' ]
84 ] );
85 } else {
86 $this->forbidden( 'img-auth-accessdenied', 'img-auth-nofile', $path );
87 }
88
89 return;
90 }
91 }
92
93 // Get the local file repository
94 $repo = $services->getRepoGroup()->getLocalRepo();
95 $zone = strstr( ltrim( $path, '/' ), '/', true );
96
97 // Get the full file storage path and extract the source file name.
98 // (e.g. 120px-Foo.png => Foo.png or page2-120px-Foo.png => Foo.png).
99 // This only applies to thumbnails/transcoded, and each of them should
100 // be under a folder that has the source file name.
101 if ( $zone === 'thumb' || $zone === 'transcoded' ) {
102 $name = wfBaseName( dirname( $path ) );
103 $filename = $repo->getZonePath( $zone ) . substr( $path, strlen( "/" . $zone ) );
104 // Check to see if the file exists
105 if ( !$repo->fileExists( $filename ) ) {
106 $this->forbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
107 return;
108 }
109 } else {
110 $name = wfBaseName( $path ); // file is a source file
111 $filename = $repo->getZonePath( 'public' ) . $path;
112 // Check to see if the file exists and is not deleted
113 $bits = explode( '!', $name, 2 );
114 if ( str_starts_with( $path, '/archive/' ) && count( $bits ) == 2 ) {
115 $file = $repo->newFromArchiveName( $bits[1], $name );
116 } else {
117 $file = $repo->newFile( $name );
118 }
119 if ( !$file || !$file->exists() || $file->isDeleted( File::DELETED_FILE ) ) {
120 $this->forbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
121 return;
122 }
123 }
124
125 $headers = []; // extra HTTP headers to send
126
127 $title = Title::makeTitleSafe( NS_FILE, $name );
128
129 $hookRunner = new HookRunner( $services->getHookContainer() );
130 if ( !$publicWiki ) {
131 // For private wikis, run extra auth checks and set cache control headers
132 $headers['Cache-Control'] = 'private';
133 $headers['Vary'] = 'Cookie';
134
135 if ( !$title instanceof Title ) { // files have valid titles
136 $this->forbidden( 'img-auth-accessdenied', 'img-auth-badtitle', $name );
137 return;
138 }
139
140 // Run hook for extension authorization plugins
141 $authResult = [];
142 if ( !$hookRunner->onImgAuthBeforeStream( $title, $path, $name, $authResult ) ) {
143 $this->forbidden( $authResult[0], $authResult[1], array_slice( $authResult, 2 ) );
144 return;
145 }
146
147 if ( !$permissionManager->userCan( 'read', $user, $title ) ) {
148 $this->forbidden( 'img-auth-accessdenied', 'img-auth-noread', $name );
149 return;
150 }
151 }
152
153 $range = $this->environment->getServerInfo( 'HTTP_RANGE' );
154 $ims = $this->environment->getServerInfo( 'HTTP_IF_MODIFIED_SINCE' );
155
156 if ( $range !== null ) {
157 $headers['Range'] = $range;
158 }
159 if ( $ims !== null ) {
160 $headers['If-Modified-Since'] = $ims;
161 }
162
163 if ( $request->getCheck( 'download' ) ) {
164 $headers['Content-Disposition'] = 'attachment';
165 }
166
167 $cspHeader = ContentSecurityPolicy::getMediaHeader( $filename );
168 if ( $cspHeader ) {
169 $headers['Content-Security-Policy'] = $cspHeader;
170 }
171
172 // Allow modification of headers before streaming a file
173 $hookRunner->onImgAuthModifyHeaders( $title->getTitleValue(), $headers );
174
175 // Stream the requested file
176 $this->prepareForOutput();
177
178 [ $headers, $options ] = HTTPFileStreamer::preprocessHeaders( $headers );
179 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
180 $repo->streamFileWithStatus( $filename, $headers, $options );
181
182 $this->enterPostSendMode();
183 }
184
196 private function forbidden( $msg1, $msg2, ...$args ) {
197 $args = ( isset( $args[0] ) && is_array( $args[0] ) ) ? $args[0] : $args;
198 $context = $this->getContext();
199
200 $msgHdr = $context->msg( $msg1 )->text();
201 $detailMsg = $this->getConfig( MainConfigNames::ImgAuthDetails )
202 ? $context->msg( $msg2, $args )->text()
203 : $context->msg( 'badaccess-group0' )->text();
204
206 'img_auth',
207 "wfForbidden Hdr: " . $context->msg( $msg1 )->inLanguage( 'en' )->text()
208 . " Msg: " . $context->msg( $msg2, $args )->inLanguage( 'en' )->text()
209 );
210
211 $this->status( 403 );
212 $this->header( 'Cache-Control: no-cache' );
213 $this->header( 'Content-Type: text/html; charset=utf-8' );
214 $language = $context->getLanguage();
215 $lang = $language->getHtmlCode();
216 $this->header( "Content-Language: $lang" );
218 $this->print(
219 $templateParser->processTemplate( 'ImageAuthForbidden', [
220 'dir' => $language->getDir(),
221 'lang' => $lang,
222 'msgHdr' => $msgHdr,
223 'detailMsg' => $detailMsg,
224 ] )
225 );
226 }
227}
const NS_FILE
Definition Defines.php:57
wfBaseName( $path, $suffix='')
Return the final portion of a pathname.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
$templateParser
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:79
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Handles compiling Mustache templates into PHP rendering functions.
A class containing constants representing the names of configuration variables.
const ImgAuthDetails
Name constant for the ImgAuthDetails setting, for use with Config::get()
const ImgAuthUrlPathMap
Name constant for the ImgAuthUrlPathMap setting, for use with Config::get()
const ImgAuthPath
Name constant for the ImgAuthPath setting, for use with Config::get()
const ScriptPath
Name constant for the ScriptPath setting, for use with Config::get()
Base class for entry point handlers.
enterPostSendMode()
Disables all output to the client.
getServiceContainer()
Returns the main service container.
prepareForOutput()
Prepare for sending the output.
header(string $header, bool $replace=true, int $status=0)
getRequestPathSuffix( $basePath)
If the request URL matches a given base path, extract the path part of the request URL after that bas...
Handle sending Content-Security-Policy headers.
Represents a title within MediaWiki.
Definition Title.php:70
Functions related to the output of file content.
static preprocessHeaders( $headers)
Takes HTTP headers in a name => value format and converts them to the weird format expected by stream...
Value object representing a message parameter that consists of a list of values.