img_auth.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. <?php
  2. /**
  3. * The web entry point for serving non-public images to logged-in users.
  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. * @ingroup entrypoint
  40. */
  41. use MediaWiki\Context\RequestContext;
  42. use MediaWiki\HookContainer\HookRunner;
  43. use MediaWiki\Html\TemplateParser;
  44. use MediaWiki\Request\WebRequest;
  45. use MediaWiki\Title\Title;
  46. define( 'MW_NO_OUTPUT_COMPRESSION', 1 );
  47. define( 'MW_ENTRY_POINT', 'img_auth' );
  48. require __DIR__ . '/includes/WebStart.php';
  49. wfImageAuthMain();
  50. $mediawiki = new MediaWiki();
  51. $mediawiki->doPostOutputShutdown();
  52. function wfImageAuthMain() {
  53. global $wgImgAuthUrlPathMap, $wgScriptPath, $wgImgAuthPath;
  54. $services = \MediaWiki\MediaWikiServices::getInstance();
  55. $permissionManager = $services->getPermissionManager();
  56. $request = RequestContext::getMain()->getRequest();
  57. $publicWiki = $services->getGroupPermissionsLookup()->groupHasPermission( '*', 'read' );
  58. // Find the path assuming the request URL is relative to the local public zone URL
  59. $baseUrl = $services->getRepoGroup()->getLocalRepo()->getZoneUrl( 'public' );
  60. if ( $baseUrl[0] === '/' ) {
  61. $basePath = $baseUrl;
  62. } else {
  63. $basePath = parse_url( $baseUrl, PHP_URL_PATH );
  64. }
  65. $path = WebRequest::getRequestPathSuffix( $basePath );
  66. if ( $path === false ) {
  67. // Try instead assuming img_auth.php is the base path
  68. $basePath = $wgImgAuthPath ?: "$wgScriptPath/img_auth.php";
  69. $path = WebRequest::getRequestPathSuffix( $basePath );
  70. }
  71. if ( $path === false ) {
  72. wfForbidden( 'img-auth-accessdenied', 'img-auth-notindir' );
  73. return;
  74. }
  75. if ( $path === '' || $path[0] !== '/' ) {
  76. // Make sure $path has a leading /
  77. $path = "/" . $path;
  78. }
  79. $user = RequestContext::getMain()->getUser();
  80. // Various extensions may have their own backends that need access.
  81. // Check if there is a special backend and storage base path for this file.
  82. foreach ( $wgImgAuthUrlPathMap as $prefix => $storageDir ) {
  83. $prefix = rtrim( $prefix, '/' ) . '/'; // implicit trailing slash
  84. if ( strpos( $path, $prefix ) === 0 ) {
  85. $be = $services->getFileBackendGroup()->backendFromPath( $storageDir );
  86. $filename = $storageDir . substr( $path, strlen( $prefix ) ); // strip prefix
  87. // Check basic user authorization
  88. $isAllowedUser = $permissionManager->userHasRight( $user, 'read' );
  89. if ( !$isAllowedUser ) {
  90. wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $path );
  91. return;
  92. }
  93. if ( $be->fileExists( [ 'src' => $filename ] ) ) {
  94. wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
  95. $be->streamFile( [
  96. 'src' => $filename,
  97. 'headers' => [ 'Cache-Control: private', 'Vary: Cookie' ]
  98. ] );
  99. } else {
  100. wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $path );
  101. }
  102. return;
  103. }
  104. }
  105. // Get the local file repository
  106. $repo = $services->getRepoGroup()->getRepo( 'local' );
  107. $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;
  119. }
  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 ( str_starts_with( $path, '/archive/' ) && count( $bits ) == 2 ) {
  126. $file = $repo->newFromArchiveName( $bits[1], $name );
  127. } else {
  128. $file = $repo->newFile( $name );
  129. }
  130. if ( !$file->exists() || $file->isDeleted( File::DELETED_FILE ) ) {
  131. wfForbidden( 'img-auth-accessdenied', 'img-auth-nofile', $filename );
  132. return;
  133. }
  134. }
  135. $headers = []; // extra HTTP headers to send
  136. $title = Title::makeTitleSafe( NS_FILE, $name );
  137. $hookRunner = new HookRunner( $services->getHookContainer() );
  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';
  142. if ( !$title instanceof Title ) { // files have valid titles
  143. wfForbidden( 'img-auth-accessdenied', 'img-auth-badtitle', $name );
  144. return;
  145. }
  146. // Run hook for extension authorization plugins
  147. /** @var array $result */
  148. $result = null;
  149. if ( !$hookRunner->onImgAuthBeforeStream( $title, $path, $name, $result ) ) {
  150. wfForbidden( $result[0], $result[1], array_slice( $result, 2 ) );
  151. return;
  152. }
  153. // Check user authorization for this title
  154. // Checks Whitelist too
  155. if ( !$permissionManager->userCan( 'read', $user, $title ) ) {
  156. wfForbidden( 'img-auth-accessdenied', 'img-auth-noread', $name );
  157. return;
  158. }
  159. }
  160. if ( isset( $_SERVER['HTTP_RANGE'] ) ) {
  161. $headers['Range'] = $_SERVER['HTTP_RANGE'];
  162. }
  163. if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
  164. $headers['If-Modified-Since'] = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
  165. }
  166. if ( $request->getCheck( 'download' ) ) {
  167. $headers['Content-Disposition'] = 'attachment';
  168. }
  169. // Allow modification of headers before streaming a file
  170. $hookRunner->onImgAuthModifyHeaders( $title->getTitleValue(), $headers );
  171. // Stream the requested file
  172. [ $headers, $options ] = HTTPFileStreamer::preprocessHeaders( $headers );
  173. wfDebugLog( 'img_auth', "Streaming `" . $filename . "`." );
  174. $repo->streamFileWithStatus( $filename, $headers, $options );
  175. }
  176. /**
  177. * Issue a standard HTTP 403 Forbidden header ($msg1-a message index, not a message) and an
  178. * error message ($msg2, also a message index), (both required) then end the script
  179. * subsequent arguments to $msg2 will be passed as parameters only for replacing in $msg2
  180. * @param string $msg1
  181. * @param string $msg2
  182. * @param mixed ...$args To pass as params to wfMessage() with $msg2. Either variadic, or a single
  183. * array argument.
  184. */
  185. function wfForbidden( $msg1, $msg2, ...$args ) {
  186. global $wgImgAuthDetails;
  187. $args = ( isset( $args[0] ) && is_array( $args[0] ) ) ? $args[0] : $args;
  188. $msgHdr = wfMessage( $msg1 )->text();
  189. $detailMsgKey = $wgImgAuthDetails ? $msg2 : 'badaccess-group0';
  190. $detailMsg = wfMessage( $detailMsgKey, $args )->text();
  191. wfDebugLog( 'img_auth',
  192. "wfForbidden Hdr: " . wfMessage( $msg1 )->inLanguage( 'en' )->text() . " Msg: " .
  193. wfMessage( $msg2, $args )->inLanguage( 'en' )->text()
  194. );
  195. HttpStatus::header( 403 );
  196. header( 'Cache-Control: no-cache' );
  197. header( 'Content-Type: text/html; charset=utf-8' );
  198. $templateParser = new TemplateParser();
  199. echo $templateParser->processTemplate( 'ImageAuthForbidden', [
  200. 'msgHdr' => $msgHdr,
  201. 'detailMsg' => $detailMsg,
  202. ] );
  203. }