MediaWiki master
AuthenticatedFileEntryPoint.php
Go to the documentation of this file.
1<?php
27
28use File;
35
37
41 public function execute() {
42 $services = $this->getServiceContainer();
43 $permissionManager = $services->getPermissionManager();
44
45 $request = $this->getRequest();
46 $publicWiki = $services->getGroupPermissionsLookup()->groupHasPermission( '*', 'read' );
47
48 // Find the path assuming the request URL is relative to the local public zone URL
49 $baseUrl = $services->getRepoGroup()->getLocalRepo()->getZoneUrl( 'public' );
50 if ( $baseUrl[0] === '/' ) {
51 $basePath = $baseUrl;
52 } else {
53 $basePath = parse_url( $baseUrl, PHP_URL_PATH );
54 }
55 $path = $this->getRequestPathSuffix( "$basePath" );
56
57 if ( $path === false ) {
58 // Try instead assuming img_auth.php is the base path
59 $basePath = $this->getConfig( MainConfigNames::ImgAuthPath )
60 ?: $this->getConfig( MainConfigNames::ScriptPath ) . '/img_auth.php';
61 $path = $this->getRequestPathSuffix( $basePath );
62 }
63
64 if ( $path === false ) {
65 $this->forbidden( 'img-auth-accessdenied', 'img-auth-notindir' );
66 return;
67 }
68
69 if ( $path === '' || $path[0] !== '/' ) {
70 // Make sure $path has a leading /
71 $path = "/" . $path;
72 }
73
74 $user = $this->getContext()->getUser();
75
76 // Various extensions may have their own backends that need access.
77 // Check if there is a special backend and storage base path for this file.
79 foreach ( $pathMap as $prefix => $storageDir ) {
80 $prefix = rtrim( $prefix, '/' ) . '/'; // implicit trailing slash
81 if ( strpos( $path, $prefix ) === 0 ) {
82 $be = $services->getFileBackendGroup()->backendFromPath( $storageDir );
83 $filename = $storageDir . substr( $path, strlen( $prefix ) ); // strip prefix
84 // Check basic user authorization
85 $isAllowedUser = $permissionManager->userHasRight( $user, 'read' );
86 if ( !$isAllowedUser ) {
87 $this->forbidden( 'img-auth-accessdenied', 'img-auth-noread', $path );
88 return;
89 }
90 if ( $be && $be->fileExists( [ 'src' => $filename ] ) ) {
91 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
92 $be->streamFile( [
93 'src' => $filename,
94 'headers' => [ 'Cache-Control: private', 'Vary: Cookie' ]
95 ] );
96 } else {
97 $this->forbidden( 'img-auth-accessdenied', 'img-auth-nofile', $path );
98 }
99
100 return;
101 }
102 }
103
104 // Get the local file repository
105 $repo = $services->getRepoGroup()->getLocalRepo();
106 $zone = strstr( ltrim( $path, '/' ), '/', true );
107
108 // Get the full file storage path and extract the source file name.
109 // (e.g. 120px-Foo.png => Foo.png or page2-120px-Foo.png => Foo.png).
110 // This only applies to thumbnails/transcoded, and each of them should
111 // be under a folder that has the source file name.
112 if ( $zone === 'thumb' || $zone === 'transcoded' ) {
113 $name = wfBaseName( dirname( $path ) );
114 $filename = $repo->getZonePath( $zone ) . substr( $path, strlen( "/" . $zone ) );
115 // Check to see if the file exists
116 if ( !$repo->fileExists( $filename ) ) {
117 $this->forbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
118 return;
119 }
120 } else {
121 $name = wfBaseName( $path ); // file is a source file
122 $filename = $repo->getZonePath( 'public' ) . $path;
123 // Check to see if the file exists and is not deleted
124 $bits = explode( '!', $name, 2 );
125 if ( str_starts_with( $path, '/archive/' ) && count( $bits ) == 2 ) {
126 $file = $repo->newFromArchiveName( $bits[1], $name );
127 } else {
128 $file = $repo->newFile( $name );
129 }
130 if ( !$file || !$file->exists() || $file->isDeleted( File::DELETED_FILE ) ) {
131 $this->forbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
132 return;
133 }
134 }
135
136 $headers = []; // extra HTTP headers to send
137
138 $title = Title::makeTitleSafe( NS_FILE, $name );
139
140 $hookRunner = new HookRunner( $services->getHookContainer() );
141 if ( !$publicWiki ) {
142 // For private wikis, run extra auth checks and set cache control headers
143 $headers['Cache-Control'] = 'private';
144 $headers['Vary'] = 'Cookie';
145
146 if ( !$title instanceof Title ) { // files have valid titles
147 $this->forbidden( 'img-auth-accessdenied', 'img-auth-badtitle', $name );
148 return;
149 }
150
151 // Run hook for extension authorization plugins
152 $authResult = [];
153 if ( !$hookRunner->onImgAuthBeforeStream( $title, $path, $name, $authResult ) ) {
154 $this->forbidden( $authResult[0], $authResult[1], array_slice( $authResult, 2 ) );
155 return;
156 }
157
158 // Check user authorization for this title
159 // Checks Whitelist too
160
161 if ( !$permissionManager->userCan( 'read', $user, $title ) ) {
162 $this->forbidden( 'img-auth-accessdenied', 'img-auth-noread', $name );
163 return;
164 }
165 }
166
167 $range = $this->environment->getServerInfo( 'HTTP_RANGE' );
168 $ims = $this->environment->getServerInfo( 'HTTP_IF_MODIFIED_SINCE' );
169
170 if ( $range !== null ) {
171 $headers['Range'] = $range;
172 }
173 if ( $ims !== null ) {
174 $headers['If-Modified-Since'] = $ims;
175 }
176
177 if ( $request->getCheck( 'download' ) ) {
178 $headers['Content-Disposition'] = 'attachment';
179 }
180
181 // Allow modification of headers before streaming a file
182 $hookRunner->onImgAuthModifyHeaders( $title->getTitleValue(), $headers );
183
184 // Stream the requested file
185 $this->prepareForOutput();
186
187 [ $headers, $options ] = HTTPFileStreamer::preprocessHeaders( $headers );
188 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
189 $repo->streamFileWithStatus( $filename, $headers, $options );
190
191 $this->enterPostSendMode();
192 }
193
204 private function forbidden( $msg1, $msg2, ...$args ) {
205 $args = ( isset( $args[0] ) && is_array( $args[0] ) ) ? $args[0] : $args;
206 $context = $this->getContext();
207
208 $msgHdr = $context->msg( $msg1 )->text();
209 $detailMsgKey = $this->getConfig( MainConfigNames::ImgAuthDetails )
210 ? $msg2 : 'badaccess-group0';
211
212 $detailMsg = $context->msg(
213 $detailMsgKey,
214 $args
215 )->text();
216
218 'img_auth',
219 "wfForbidden Hdr: " . $context->msg( $msg1 )->inLanguage( 'en' )->text()
220 . " Msg: " . $context->msg( $msg2, $args )->inLanguage( 'en' )->text()
221 );
222
223 $this->status( 403 );
224 $this->header( 'Cache-Control: no-cache' );
225 $this->header( 'Content-Type: text/html; charset=utf-8' );
227 $this->print(
228 $templateParser->processTemplate( 'ImageAuthForbidden', [
229 'msgHdr' => $msgHdr,
230 'detailMsg' => $detailMsg,
231 ] )
232 );
233 }
234}
const NS_FILE
Definition Defines.php:71
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:74
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...
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
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...
Represents a title within MediaWiki.
Definition Title.php:79