StatusValue: Add a getter for MessageSpecifier list
[mediawiki.git] / img_auth.php
blobedc27c7ce1e6c596ea23bf0a5e6d79a21114f864
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\Context\RequestContext;
43 use MediaWiki\HookContainer\HookRunner;
44 use MediaWiki\Html\TemplateParser;
45 use MediaWiki\Request\WebRequest;
46 use MediaWiki\Title\Title;
48 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
49 define( 'MW_ENTRY_POINT', 'img_auth' );
50 require __DIR__ . '/includes/WebStart.php';
52 wfImageAuthMain();
54 $mediawiki = new MediaWiki();
55 $mediawiki->doPostOutputShutdown();
57 function wfImageAuthMain() {
58 global $wgImgAuthUrlPathMap, $wgScriptPath, $wgImgAuthPath;
60 $services = \MediaWiki\MediaWikiServices::getInstance();
61 $permissionManager = $services->getPermissionManager();
63 $request = RequestContext::getMain()->getRequest();
64 $publicWiki = $services->getGroupPermissionsLookup()->groupHasPermission( '*', 'read' );
66 // Find the path assuming the request URL is relative to the local public zone URL
67 $baseUrl = $services->getRepoGroup()->getLocalRepo()->getZoneUrl( 'public' );
68 if ( $baseUrl[0] === '/' ) {
69 $basePath = $baseUrl;
70 } else {
71 $basePath = parse_url( $baseUrl, PHP_URL_PATH );
73 $path = WebRequest::getRequestPathSuffix( $basePath );
75 if ( $path === false ) {
76 // Try instead assuming img_auth.php is the base path
77 $basePath = $wgImgAuthPath ?: "$wgScriptPath/img_auth.php";
78 $path = WebRequest::getRequestPathSuffix( $basePath );
81 if ( $path === false ) {
82 wfForbidden( 'img-auth-accessdenied', 'img-auth-notindir' );
83 return;
86 if ( $path === '' || $path[0] !== '/' ) {
87 // Make sure $path has a leading /
88 $path = "/" . $path;
91 $user = RequestContext::getMain()->getUser();
93 // Various extensions may have their own backends that need access.
94 // Check if there is a special backend and storage base path for this file.
95 foreach ( $wgImgAuthUrlPathMap as $prefix => $storageDir ) {
96 $prefix = rtrim( $prefix, '/' ) . '/'; // implicit trailing slash
97 if ( strpos( $path, $prefix ) === 0 ) {
98 $be = $services->getFileBackendGroup()->backendFromPath( $storageDir );
99 $filename = $storageDir . substr( $path, strlen( $prefix ) ); // strip prefix
100 // Check basic user authorization
101 $isAllowedUser = $permissionManager->userHasRight( $user, 'read' );
102 if ( !$isAllowedUser ) {
103 wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $path );
104 return;
106 if ( $be->fileExists( [ 'src' => $filename ] ) ) {
107 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
108 $be->streamFile( [
109 'src' => $filename,
110 'headers' => [ 'Cache-Control: private', 'Vary: Cookie' ]
111 ] );
112 } else {
113 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $path );
115 return;
119 // Get the local file repository
120 $repo = $services->getRepoGroup()->getRepo( 'local' );
121 $zone = strstr( ltrim( $path, '/' ), '/', true );
123 // Get the full file storage path and extract the source file name.
124 // (e.g. 120px-Foo.png => Foo.png or page2-120px-Foo.png => Foo.png).
125 // This only applies to thumbnails/transcoded, and each of them should
126 // be under a folder that has the source file name.
127 if ( $zone === 'thumb' || $zone === 'transcoded' ) {
128 $name = wfBaseName( dirname( $path ) );
129 $filename = $repo->getZonePath( $zone ) . substr( $path, strlen( "/" . $zone ) );
130 // Check to see if the file exists
131 if ( !$repo->fileExists( $filename ) ) {
132 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
133 return;
135 } else {
136 $name = wfBaseName( $path ); // file is a source file
137 $filename = $repo->getZonePath( 'public' ) . $path;
138 // Check to see if the file exists and is not deleted
139 $bits = explode( '!', $name, 2 );
140 if ( str_starts_with( $path, '/archive/' ) && count( $bits ) == 2 ) {
141 $file = $repo->newFromArchiveName( $bits[1], $name );
142 } else {
143 $file = $repo->newFile( $name );
145 if ( !$file->exists() || $file->isDeleted( File::DELETED_FILE ) ) {
146 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
147 return;
151 $headers = []; // extra HTTP headers to send
153 $title = Title::makeTitleSafe( NS_FILE, $name );
155 $hookRunner = new HookRunner( $services->getHookContainer() );
156 if ( !$publicWiki ) {
157 // For private wikis, run extra auth checks and set cache control headers
158 $headers['Cache-Control'] = 'private';
159 $headers['Vary'] = 'Cookie';
161 if ( !$title instanceof Title ) { // files have valid titles
162 wfForbidden( 'img-auth-accessdenied', 'img-auth-badtitle', $name );
163 return;
166 // Run hook for extension authorization plugins
167 /** @var array $result */
168 $result = null;
169 if ( !$hookRunner->onImgAuthBeforeStream( $title, $path, $name, $result ) ) {
170 wfForbidden( $result[0], $result[1], array_slice( $result, 2 ) );
171 return;
174 // Check user authorization for this title
175 // Checks Whitelist too
177 if ( !$permissionManager->userCan( 'read', $user, $title ) ) {
178 wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $name );
179 return;
183 if ( isset( $_SERVER['HTTP_RANGE'] ) ) {
184 $headers['Range'] = $_SERVER['HTTP_RANGE'];
186 if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
187 $headers['If-Modified-Since'] = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
190 if ( $request->getCheck( 'download' ) ) {
191 $headers['Content-Disposition'] = 'attachment';
194 // Allow modification of headers before streaming a file
195 $hookRunner->onImgAuthModifyHeaders( $title->getTitleValue(), $headers );
197 // Stream the requested file
198 [ $headers, $options ] = HTTPFileStreamer::preprocessHeaders( $headers );
199 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
200 $repo->streamFileWithStatus( $filename, $headers, $options );
204 * Issue a standard HTTP 403 Forbidden header ($msg1-a message index, not a message) and an
205 * error message ($msg2, also a message index), (both required) then end the script
206 * subsequent arguments to $msg2 will be passed as parameters only for replacing in $msg2
207 * @param string $msg1
208 * @param string $msg2
209 * @param mixed ...$args To pass as params to wfMessage() with $msg2. Either variadic, or a single
210 * array argument.
212 function wfForbidden( $msg1, $msg2, ...$args ) {
213 global $wgImgAuthDetails;
215 $args = ( isset( $args[0] ) && is_array( $args[0] ) ) ? $args[0] : $args;
217 $msgHdr = wfMessage( $msg1 )->text();
218 $detailMsgKey = $wgImgAuthDetails ? $msg2 : 'badaccess-group0';
219 $detailMsg = wfMessage( $detailMsgKey, $args )->text();
221 wfDebugLog( 'img_auth',
222 "wfForbidden Hdr: " . wfMessage( $msg1 )->inLanguage( 'en' )->text() . " Msg: " .
223 wfMessage( $msg2, $args )->inLanguage( 'en' )->text()
226 HttpStatus::header( 403 );
227 header( 'Cache-Control: no-cache' );
228 header( 'Content-Type: text/html; charset=utf-8' );
229 $templateParser = new TemplateParser();
230 echo $templateParser->processTemplate( 'ImageAuthForbidden', [
231 'msgHdr' => $msgHdr,
232 'detailMsg' => $detailMsg,
233 ] );