Update git submodules
[mediawiki.git] / img_auth.php
blobe0d25c0806e1d6e90aa15537f7b9fd4b52438e93
1 <?php
2 /**
3 * The web entry point for serving non-public images to logged-in users.
5 * To use this, see https://www.mediawiki.org/wiki/Manual:Image_authorization
7 * - Set $wgUploadDirectory to a non-public directory (not web accessible)
8 * - Set $wgUploadPath to point to this file
10 * Optional Parameters
12 * - Set $wgImgAuthDetails = true if you want the reason the access was denied messages to
13 * be displayed instead of just the 403 error (doesn't work on IE anyway),
14 * otherwise it will only appear in error logs
16 * For security reasons, you usually don't want your user to know *why* access was denied,
17 * just that it was. If you want to change this, you can set $wgImgAuthDetails to 'true'
18 * in localsettings.php and it will give the user the reason why access was denied.
20 * Your server needs to support REQUEST_URI or PATH_INFO; CGI-based
21 * configurations sometimes don't.
23 * This program is free software; you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation; either version 2 of the License, or
26 * (at your option) any later version.
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
33 * You should have received a copy of the GNU General Public License along
34 * with this program; if not, write to the Free Software Foundation, Inc.,
35 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
36 * http://www.gnu.org/copyleft/gpl.html
38 * @file
39 * @ingroup entrypoint
42 use MediaWiki\HookContainer\HookRunner;
43 use MediaWiki\Html\TemplateParser;
44 use MediaWiki\Request\WebRequest;
45 use MediaWiki\Title\Title;
47 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
48 define( 'MW_ENTRY_POINT', 'img_auth' );
49 require __DIR__ . '/includes/WebStart.php';
51 wfImageAuthMain();
53 $mediawiki = new MediaWiki();
54 $mediawiki->doPostOutputShutdown();
56 function wfImageAuthMain() {
57 global $wgImgAuthUrlPathMap, $wgScriptPath, $wgImgAuthPath;
59 $services = \MediaWiki\MediaWikiServices::getInstance();
60 $permissionManager = $services->getPermissionManager();
62 $request = RequestContext::getMain()->getRequest();
63 $publicWiki = $services->getGroupPermissionsLookup()->groupHasPermission( '*', 'read' );
65 // Find the path assuming the request URL is relative to the local public zone URL
66 $baseUrl = $services->getRepoGroup()->getLocalRepo()->getZoneUrl( 'public' );
67 if ( $baseUrl[0] === '/' ) {
68 $basePath = $baseUrl;
69 } else {
70 $basePath = parse_url( $baseUrl, PHP_URL_PATH );
72 $path = WebRequest::getRequestPathSuffix( $basePath );
74 if ( $path === false ) {
75 // Try instead assuming img_auth.php is the base path
76 $basePath = $wgImgAuthPath ?: "$wgScriptPath/img_auth.php";
77 $path = WebRequest::getRequestPathSuffix( $basePath );
80 if ( $path === false ) {
81 wfForbidden( 'img-auth-accessdenied', 'img-auth-notindir' );
82 return;
85 if ( $path === '' || $path[0] !== '/' ) {
86 // Make sure $path has a leading /
87 $path = "/" . $path;
90 $user = RequestContext::getMain()->getUser();
92 // Various extensions may have their own backends that need access.
93 // Check if there is a special backend and storage base path for this file.
94 foreach ( $wgImgAuthUrlPathMap as $prefix => $storageDir ) {
95 $prefix = rtrim( $prefix, '/' ) . '/'; // implicit trailing slash
96 if ( strpos( $path, $prefix ) === 0 ) {
97 $be = $services->getFileBackendGroup()->backendFromPath( $storageDir );
98 $filename = $storageDir . substr( $path, strlen( $prefix ) ); // strip prefix
99 // Check basic user authorization
100 $isAllowedUser = $permissionManager->userHasRight( $user, 'read' );
101 if ( !$isAllowedUser ) {
102 wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $path );
103 return;
105 if ( $be->fileExists( [ 'src' => $filename ] ) ) {
106 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
107 $be->streamFile( [
108 'src' => $filename,
109 'headers' => [ 'Cache-Control: private', 'Vary: Cookie' ]
110 ] );
111 } else {
112 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $path );
114 return;
118 // Get the local file repository
119 $repo = $services->getRepoGroup()->getRepo( 'local' );
120 $zone = strstr( ltrim( $path, '/' ), '/', true );
122 // Get the full file storage path and extract the source file name.
123 // (e.g. 120px-Foo.png => Foo.png or page2-120px-Foo.png => Foo.png).
124 // This only applies to thumbnails/transcoded, and each of them should
125 // be under a folder that has the source file name.
126 if ( $zone === 'thumb' || $zone === 'transcoded' ) {
127 $name = wfBaseName( dirname( $path ) );
128 $filename = $repo->getZonePath( $zone ) . substr( $path, strlen( "/" . $zone ) );
129 // Check to see if the file exists
130 if ( !$repo->fileExists( $filename ) ) {
131 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
132 return;
134 } else {
135 $name = wfBaseName( $path ); // file is a source file
136 $filename = $repo->getZonePath( 'public' ) . $path;
137 // Check to see if the file exists and is not deleted
138 $bits = explode( '!', $name, 2 );
139 if ( str_starts_with( $path, '/archive/' ) && count( $bits ) == 2 ) {
140 $file = $repo->newFromArchiveName( $bits[1], $name );
141 } else {
142 $file = $repo->newFile( $name );
144 if ( !$file->exists() || $file->isDeleted( File::DELETED_FILE ) ) {
145 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
146 return;
150 $headers = []; // extra HTTP headers to send
152 $title = Title::makeTitleSafe( NS_FILE, $name );
154 $hookRunner = new HookRunner( $services->getHookContainer() );
155 if ( !$publicWiki ) {
156 // For private wikis, run extra auth checks and set cache control headers
157 $headers['Cache-Control'] = 'private';
158 $headers['Vary'] = 'Cookie';
160 if ( !$title instanceof Title ) { // files have valid titles
161 wfForbidden( 'img-auth-accessdenied', 'img-auth-badtitle', $name );
162 return;
165 // Run hook for extension authorization plugins
166 /** @var array $result */
167 $result = null;
168 if ( !$hookRunner->onImgAuthBeforeStream( $title, $path, $name, $result ) ) {
169 wfForbidden( $result[0], $result[1], array_slice( $result, 2 ) );
170 return;
173 // Check user authorization for this title
174 // Checks Whitelist too
176 if ( !$permissionManager->userCan( 'read', $user, $title ) ) {
177 wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $name );
178 return;
182 if ( isset( $_SERVER['HTTP_RANGE'] ) ) {
183 $headers['Range'] = $_SERVER['HTTP_RANGE'];
185 if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
186 $headers['If-Modified-Since'] = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
189 if ( $request->getCheck( 'download' ) ) {
190 $headers['Content-Disposition'] = 'attachment';
193 // Allow modification of headers before streaming a file
194 $hookRunner->onImgAuthModifyHeaders( $title->getTitleValue(), $headers );
196 // Stream the requested file
197 [ $headers, $options ] = HTTPFileStreamer::preprocessHeaders( $headers );
198 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
199 $repo->streamFileWithStatus( $filename, $headers, $options );
203 * Issue a standard HTTP 403 Forbidden header ($msg1-a message index, not a message) and an
204 * error message ($msg2, also a message index), (both required) then end the script
205 * subsequent arguments to $msg2 will be passed as parameters only for replacing in $msg2
206 * @param string $msg1
207 * @param string $msg2
208 * @param mixed ...$args To pass as params to wfMessage() with $msg2. Either variadic, or a single
209 * array argument.
211 function wfForbidden( $msg1, $msg2, ...$args ) {
212 global $wgImgAuthDetails;
214 $args = ( isset( $args[0] ) && is_array( $args[0] ) ) ? $args[0] : $args;
216 $msgHdr = wfMessage( $msg1 )->text();
217 $detailMsgKey = $wgImgAuthDetails ? $msg2 : 'badaccess-group0';
218 $detailMsg = wfMessage( $detailMsgKey, $args )->text();
220 wfDebugLog( 'img_auth',
221 "wfForbidden Hdr: " . wfMessage( $msg1 )->inLanguage( 'en' )->text() . " Msg: " .
222 wfMessage( $msg2, $args )->inLanguage( 'en' )->text()
225 HttpStatus::header( 403 );
226 header( 'Cache-Control: no-cache' );
227 header( 'Content-Type: text/html; charset=utf-8' );
228 $templateParser = new TemplateParser();
229 echo $templateParser->processTemplate( 'ImageAuthForbidden', [
230 'msgHdr' => $msgHdr,
231 'detailMsg' => $detailMsg,
232 ] );