Add setCaller to BatchRowIterator
[mediawiki.git] / img_auth.php
blobcc44c5fda273eb9e65dc06933abeeed15c3f5b48
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 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
43 define( 'MW_ENTRY_POINT', 'img_auth' );
44 require __DIR__ . '/includes/WebStart.php';
46 wfImageAuthMain();
48 $mediawiki = new MediaWiki();
49 $mediawiki->doPostOutputShutdown();
51 function wfImageAuthMain() {
52 global $wgImgAuthUrlPathMap, $wgScriptPath, $wgImgAuthPath;
54 $services = \MediaWiki\MediaWikiServices::getInstance();
55 $permissionManager = $services->getPermissionManager();
57 $request = RequestContext::getMain()->getRequest();
58 $publicWiki = in_array( 'read', $permissionManager->getGroupPermissions( [ '*' ] ), true );
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 );
67 $path = WebRequest::getRequestPathSuffix( $basePath );
69 if ( $path === false ) {
70 // Try instead assuming img_auth.php is the base path
71 $basePath = $wgImgAuthPath ?: "$wgScriptPath/img_auth.php";
72 $path = WebRequest::getRequestPathSuffix( $basePath );
75 if ( $path === false ) {
76 wfForbidden( 'img-auth-accessdenied', 'img-auth-notindir' );
77 return;
80 if ( $path === '' || $path[0] !== '/' ) {
81 // Make sure $path has a leading /
82 $path = "/" . $path;
85 $user = RequestContext::getMain()->getUser();
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;
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 );
109 return;
113 // Get the local file repository
114 $repo = $services->getRepoGroup()->getRepo( 'local' );
115 $zone = strstr( ltrim( $path, '/' ), '/', true );
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;
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 );
139 if ( !$file->exists() || $file->isDeleted( File::DELETED_FILE ) ) {
140 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
141 return;
145 $headers = []; // extra HTTP headers to send
147 $title = Title::makeTitleSafe( NS_FILE, $name );
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';
154 if ( !$title instanceof Title ) { // files have valid titles
155 wfForbidden( 'img-auth-accessdenied', 'img-auth-badtitle', $name );
156 return;
159 // Run hook for extension authorization plugins
160 /** @var array $result */
161 $result = null;
162 if ( !Hooks::runner()->onImgAuthBeforeStream( $title, $path, $name, $result ) ) {
163 wfForbidden( $result[0], $result[1], array_slice( $result, 2 ) );
164 return;
167 // Check user authorization for this title
168 // Checks Whitelist too
170 if ( !$permissionManager->userCan( 'read', $user, $title ) ) {
171 wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $name );
172 return;
176 if ( isset( $_SERVER['HTTP_RANGE'] ) ) {
177 $headers['Range'] = $_SERVER['HTTP_RANGE'];
179 if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
180 $headers['If-Modified-Since'] = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
183 if ( $request->getCheck( 'download' ) ) {
184 $headers['Content-Disposition'] = 'attachment';
187 // Allow modification of headers before streaming a file
188 Hooks::runner()->onImgAuthModifyHeaders( $title->getTitleValue(), $headers );
190 // Stream the requested file
191 list( $headers, $options ) = HTTPFileStreamer::preprocessHeaders( $headers );
192 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
193 $repo->streamFileWithStatus( $filename, $headers, $options );
197 * Issue a standard HTTP 403 Forbidden header ($msg1-a message index, not a message) and an
198 * error message ($msg2, also a message index), (both required) then end the script
199 * subsequent arguments to $msg2 will be passed as parameters only for replacing in $msg2
200 * @param string $msg1
201 * @param string $msg2
202 * @param mixed ...$args To pass as params to wfMessage() with $msg2. Either variadic, or a single
203 * array argument.
205 function wfForbidden( $msg1, $msg2, ...$args ) {
206 global $wgImgAuthDetails;
208 $args = ( isset( $args[0] ) && is_array( $args[0] ) ) ? $args[0] : $args;
210 $msgHdr = wfMessage( $msg1 )->text();
211 $detailMsgKey = $wgImgAuthDetails ? $msg2 : 'badaccess-group0';
212 $detailMsg = wfMessage( $detailMsgKey, $args )->text();
214 wfDebugLog( 'img_auth',
215 "wfForbidden Hdr: " . wfMessage( $msg1 )->inLanguage( 'en' )->text() . " Msg: " .
216 wfMessage( $msg2, $args )->inLanguage( 'en' )->text()
219 HttpStatus::header( 403 );
220 header( 'Cache-Control: no-cache' );
221 header( 'Content-Type: text/html; charset=utf-8' );
222 $templateParser = new TemplateParser();
223 echo $templateParser->processTemplate( 'ImageAuthForbidden', [
224 'msgHdr' => $msgHdr,
225 'detailMsg' => $detailMsg,
226 ] );