img_auth.php 7.5 KB

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