Merge "rcfeed: Replace usage of deprecated CommentStore::getStore()"
[lhc/web/wiklou.git] / img_auth.php
1 <?php
2 /**
3 * Image authorisation script
4 *
5 * To use this, see https://www.mediawiki.org/wiki/Manual:Image_Authorization
6 *
7 * - Set $wgUploadDirectory to a non-public directory (not web accessible)
8 * - Set $wgUploadPath to point to this file
9 *
10 * Optional Parameters
11 *
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
15 *
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.
19 *
20 * Your server needs to support REQUEST_URI or PATH_INFO; CGI-based
21 * configurations sometimes don't.
22 *
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.
27 *
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.
32 *
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
37 *
38 * @file
39 */
40
41 define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
42 require __DIR__ . '/includes/WebStart.php';
43
44 # Set action base paths so that WebRequest::getPathInfo()
45 # recognizes the "X" as the 'title' in ../img_auth.php/X urls.
46 $wgArticlePath = false; # Don't let a "/*" article path clober our action path
47 $wgActionPaths = [ "$wgUploadPath/" ];
48
49 wfImageAuthMain();
50
51 $mediawiki = new MediaWiki();
52 $mediawiki->doPostOutputShutdown( 'fast' );
53
54 function wfImageAuthMain() {
55 global $wgImgAuthUrlPathMap;
56
57 $request = RequestContext::getMain()->getRequest();
58 $publicWiki = in_array( 'read', User::getGroupPermissions( [ '*' ] ), true );
59
60 // Get the requested file path (source file or thumbnail)
61 $matches = WebRequest::getPathInfo();
62 if ( !isset( $matches['title'] ) ) {
63 wfForbidden( 'img-auth-accessdenied', 'img-auth-nopathinfo' );
64 return;
65 }
66 $path = $matches['title'];
67 if ( $path && $path[0] !== '/' ) {
68 // Make sure $path has a leading /
69 $path = "/" . $path;
70 }
71
72 // Check for T30235: QUERY_STRING overriding the correct extension
73 $whitelist = [];
74 $extension = FileBackend::extensionFromPath( $path, 'rawcase' );
75 if ( $extension != '' ) {
76 $whitelist[] = $extension;
77 }
78 if ( !$request->checkUrlExtension( $whitelist ) ) {
79 return;
80 }
81
82 // Various extensions may have their own backends that need access.
83 // Check if there is a special backend and storage base path for this file.
84 foreach ( $wgImgAuthUrlPathMap as $prefix => $storageDir ) {
85 $prefix = rtrim( $prefix, '/' ) . '/'; // implicit trailing slash
86 if ( strpos( $path, $prefix ) === 0 ) {
87 $be = FileBackendGroup::singleton()->backendFromPath( $storageDir );
88 $filename = $storageDir . substr( $path, strlen( $prefix ) ); // strip prefix
89 // Check basic user authorization
90 if ( !RequestContext::getMain()->getUser()->isAllowed( 'read' ) ) {
91 wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $path );
92 return;
93 }
94 if ( $be->fileExists( [ 'src' => $filename ] ) ) {
95 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
96 $be->streamFile( [ 'src' => $filename ],
97 [ 'Cache-Control: private', 'Vary: Cookie' ] );
98 } else {
99 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $path );
100 }
101 return;
102 }
103 }
104
105 // Get the local file repository
106 $repo = RepoGroup::singleton()->getRepo( 'local' );
107 $zone = strstr( ltrim( $path, '/' ), '/', true );
108
109 // Get the full file storage path and extract the source file name.
110 // (e.g. 120px-Foo.png => Foo.png or page2-120px-Foo.png => Foo.png).
111 // This only applies to thumbnails/transcoded, and each of them should
112 // be under a folder that has the source file name.
113 if ( $zone === 'thumb' || $zone === 'transcoded' ) {
114 $name = wfBaseName( dirname( $path ) );
115 $filename = $repo->getZonePath( $zone ) . substr( $path, strlen( "/" . $zone ) );
116 // Check to see if the file exists
117 if ( !$repo->fileExists( $filename ) ) {
118 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
119 return;
120 }
121 } else {
122 $name = wfBaseName( $path ); // file is a source file
123 $filename = $repo->getZonePath( 'public' ) . $path;
124 // Check to see if the file exists and is not deleted
125 $bits = explode( '!', $name, 2 );
126 if ( substr( $path, 0, 9 ) === '/archive/' && count( $bits ) == 2 ) {
127 $file = $repo->newFromArchiveName( $bits[1], $name );
128 } else {
129 $file = $repo->newFile( $name );
130 }
131 if ( !$file->exists() || $file->isDeleted( File::DELETED_FILE ) ) {
132 wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
133 return;
134 }
135 }
136
137 $headers = []; // extra HTTP headers to send
138
139 if ( !$publicWiki ) {
140 // For private wikis, run extra auth checks and set cache control headers
141 $headers[] = 'Cache-Control: private';
142 $headers[] = 'Vary: Cookie';
143
144 $title = Title::makeTitleSafe( NS_FILE, $name );
145 if ( !$title instanceof Title ) { // files have valid titles
146 wfForbidden( 'img-auth-accessdenied', 'img-auth-badtitle', $name );
147 return;
148 }
149
150 // Run hook for extension authorization plugins
151 /** @var array $result */
152 $result = null;
153 if ( !Hooks::run( 'ImgAuthBeforeStream', [ &$title, &$path, &$name, &$result ] ) ) {
154 wfForbidden( $result[0], $result[1], array_slice( $result, 2 ) );
155 return;
156 }
157
158 // Check user authorization for this title
159 // Checks Whitelist too
160 if ( !$title->userCan( 'read' ) ) {
161 wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $name );
162 return;
163 }
164 }
165
166 $options = []; // HTTP header options
167 if ( isset( $_SERVER['HTTP_RANGE'] ) ) {
168 $options['range'] = $_SERVER['HTTP_RANGE'];
169 }
170 if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
171 $options['if-modified-since'] = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
172 }
173
174 if ( $request->getCheck( 'download' ) ) {
175 $headers[] = 'Content-Disposition: attachment';
176 }
177
178 // Stream the requested file
179 wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
180 $repo->streamFile( $filename, $headers, $options );
181 }
182
183 /**
184 * Issue a standard HTTP 403 Forbidden header ($msg1-a message index, not a message) and an
185 * error message ($msg2, also a message index), (both required) then end the script
186 * subsequent arguments to $msg2 will be passed as parameters only for replacing in $msg2
187 * @param string $msg1
188 * @param string $msg2
189 * @param mixed ...$args To pass as params to wfMessage() with $msg2. Either variadic, or a single
190 * array argument.
191 */
192 function wfForbidden( $msg1, $msg2, ...$args ) {
193 global $wgImgAuthDetails;
194
195 $args = ( isset( $args[0] ) && is_array( $args[0] ) ) ? $args[0] : $args;
196
197 $msgHdr = wfMessage( $msg1 )->escaped();
198 $detailMsgKey = $wgImgAuthDetails ? $msg2 : 'badaccess-group0';
199 $detailMsg = wfMessage( $detailMsgKey, $args )->escaped();
200
201 wfDebugLog( 'img_auth',
202 "wfForbidden Hdr: " . wfMessage( $msg1 )->inLanguage( 'en' )->text() . " Msg: " .
203 wfMessage( $msg2, $args )->inLanguage( 'en' )->text()
204 );
205
206 HttpStatus::header( 403 );
207 header( 'Cache-Control: no-cache' );
208 header( 'Content-Type: text/html; charset=utf-8' );
209 echo <<<ENDS
210 <!DOCTYPE html>
211 <html>
212 <head>
213 <meta charset="UTF-8" />
214 <title>$msgHdr</title>
215 </head>
216 <body>
217 <h1>$msgHdr</h1>
218 <p>$detailMsg</p>
219 </body>
220 </html>
221 ENDS;
222 }