Unpersist the session on logout
[mediawiki.git] / img_auth.php
blobd63618817a19ec4da0dc043aac146dff9fb7f2e1
1 <?php
2 /**
3 * Image authorisation script
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 PATH_INFO; CGI-based configurations usually don't.
22 * This program is free software; you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as published by
24 * the Free Software Foundation; either version 2 of the License, or
25 * (at your option) any later version.
27 * This program is distributed in the hope that it will be useful,
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 * GNU General Public License for more details.
32 * You should have received a copy of the GNU General Public License along
33 * with this program; if not, write to the Free Software Foundation, Inc.,
34 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
35 * http://www.gnu.org/copyleft/gpl.html
37 * @file
40 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
41 require __DIR__ . '/includes/WebStart.php';
43 # Set action base paths so that WebRequest::getPathInfo()
44 # recognizes the "X" as the 'title' in ../img_auth.php/X urls.
45 $wgArticlePath = false; # Don't let a "/*" article path clober our action path
46 $wgActionPaths = [ "$wgUploadPath/" ];
48 wfImageAuthMain();
50 $mediawiki = new MediaWiki();
51 $mediawiki->doPostOutputShutdown( 'fast' );
53 function wfImageAuthMain() {
54 global $wgImgAuthUrlPathMap;
56 $request = RequestContext::getMain()->getRequest();
57 $publicWiki = in_array( 'read', User::getGroupPermissions( [ '*' ] ), true );
59 // Get the requested file path (source file or thumbnail)
60 $matches = WebRequest::getPathInfo();
61 if ( !isset( $matches['title'] ) ) {
62 wfForbidden( 'img-auth-accessdenied', 'img-auth-nopathinfo' );
63 return;
65 $path = $matches['title'];
66 if ( $path && $path[0] !== '/' ) {
67 // Make sure $path has a leading /
68 $path = "/" . $path;
71 // Check for bug 28235: QUERY_STRING overriding the correct extension
72 $whitelist = [];
73 $extension = FileBackend::extensionFromPath( $path, 'rawcase' );
74 if ( $extension != '' ) {
75 $whitelist[] = $extension;
77 if ( !$request->checkUrlExtension( $whitelist ) ) {
78 return;
81 // Various extensions may have their own backends that need access.
82 // Check if there is a special backend and storage base path for this file.
83 foreach ( $wgImgAuthUrlPathMap as $prefix => $storageDir ) {
84 $prefix = rtrim( $prefix, '/' ) . '/'; // implicit trailing slash
85 if ( strpos( $path, $prefix ) === 0 ) {
86 $be = FileBackendGroup::singleton()->backendFromPath( $storageDir );
87 $filename = $storageDir . substr( $path, strlen( $prefix ) ); // strip prefix
88 // Check basic user authorization
89 if ( !RequestContext::getMain()->getUser()->isAllowed( 'read' ) ) {
90 wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $path );
91 return;
93 if ( $be->fileExists( [ 'src' => $filename ] ) ) {
94 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
95 $be->streamFile( [ 'src' => $filename ],
96 [ 'Cache-Control: private', 'Vary: Cookie' ] );
97 } else {
98 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $path );
100 return;
104 // Get the local file repository
105 $repo = RepoGroup::singleton()->getRepo( 'local' );
106 $zone = strstr( ltrim( $path, '/' ), '/', true );
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 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
118 return;
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 ( substr( $path, 0, 9 ) === '/archive/' && count( $bits ) == 2 ) {
126 $file = $repo->newFromArchiveName( $bits[1], $name );
127 } else {
128 $file = $repo->newFile( $name );
130 if ( !$file->exists() || $file->isDeleted( File::DELETED_FILE ) ) {
131 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
132 return;
136 $headers = []; // extra HTTP headers to send
138 if ( !$publicWiki ) {
139 // For private wikis, run extra auth checks and set cache control headers
140 $headers[] = 'Cache-Control: private';
141 $headers[] = 'Vary: Cookie';
143 $title = Title::makeTitleSafe( NS_FILE, $name );
144 if ( !$title instanceof Title ) { // files have valid titles
145 wfForbidden( 'img-auth-accessdenied', 'img-auth-badtitle', $name );
146 return;
149 // Run hook for extension authorization plugins
150 /** @var $result array */
151 $result = null;
152 if ( !Hooks::run( 'ImgAuthBeforeStream', [ &$title, &$path, &$name, &$result ] ) ) {
153 wfForbidden( $result[0], $result[1], array_slice( $result, 2 ) );
154 return;
157 // Check user authorization for this title
158 // Checks Whitelist too
159 if ( !$title->userCan( 'read' ) ) {
160 wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $name );
161 return;
165 if ( $request->getCheck( 'download' ) ) {
166 $headers[] = 'Content-Disposition: attachment';
169 // Stream the requested file
170 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
171 $repo->streamFile( $filename, $headers );
175 * Issue a standard HTTP 403 Forbidden header ($msg1-a message index, not a message) and an
176 * error message ($msg2, also a message index), (both required) then end the script
177 * subsequent arguments to $msg2 will be passed as parameters only for replacing in $msg2
178 * @param string $msg1
179 * @param string $msg2
181 function wfForbidden( $msg1, $msg2 ) {
182 global $wgImgAuthDetails;
184 $args = func_get_args();
185 array_shift( $args );
186 array_shift( $args );
187 $args = ( isset( $args[0] ) && is_array( $args[0] ) ) ? $args[0] : $args;
189 $msgHdr = wfMessage( $msg1 )->escaped();
190 $detailMsgKey = $wgImgAuthDetails ? $msg2 : 'badaccess-group0';
191 $detailMsg = wfMessage( $detailMsgKey, $args )->escaped();
193 wfDebugLog( 'img_auth',
194 "wfForbidden Hdr: " . wfMessage( $msg1 )->inLanguage( 'en' )->text() . " Msg: " .
195 wfMessage( $msg2, $args )->inLanguage( 'en' )->text()
198 HttpStatus::header( 403 );
199 header( 'Cache-Control: no-cache' );
200 header( 'Content-Type: text/html; charset=utf-8' );
201 echo <<<ENDS
202 <!DOCTYPE html>
203 <html>
204 <head>
205 <meta charset="UTF-8" />
206 <title>$msgHdr</title>
207 </head>
208 <body>
209 <h1>$msgHdr</h1>
210 <p>$detailMsg</p>
211 </body>
212 </html>
213 ENDS;