FileBackendGroup.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. <?php
  2. /**
  3. * File backend registration handling.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @ingroup FileBackend
  22. */
  23. use MediaWiki\Logger\LoggerFactory;
  24. use MediaWiki\MediaWikiServices;
  25. /**
  26. * Class to handle file backend registration
  27. *
  28. * @ingroup FileBackend
  29. * @since 1.19
  30. */
  31. class FileBackendGroup {
  32. /** @var FileBackendGroup */
  33. protected static $instance = null;
  34. /** @var array (name => ('class' => string, 'config' => array, 'instance' => object)) */
  35. protected $backends = [];
  36. protected function __construct() {
  37. }
  38. /**
  39. * @return FileBackendGroup
  40. */
  41. public static function singleton() {
  42. if ( self::$instance == null ) {
  43. self::$instance = new self();
  44. self::$instance->initFromGlobals();
  45. }
  46. return self::$instance;
  47. }
  48. /**
  49. * Destroy the singleton instance
  50. */
  51. public static function destroySingleton() {
  52. self::$instance = null;
  53. }
  54. /**
  55. * Register file backends from the global variables
  56. */
  57. protected function initFromGlobals() {
  58. global $wgLocalFileRepo, $wgForeignFileRepos, $wgFileBackends, $wgDirectoryMode;
  59. // Register explicitly defined backends
  60. $this->register( $wgFileBackends, wfConfiguredReadOnlyReason() );
  61. $autoBackends = [];
  62. // Automatically create b/c backends for file repos...
  63. $repos = array_merge( $wgForeignFileRepos, [ $wgLocalFileRepo ] );
  64. foreach ( $repos as $info ) {
  65. $backendName = $info['backend'];
  66. if ( is_object( $backendName ) || isset( $this->backends[$backendName] ) ) {
  67. continue; // already defined (or set to the object for some reason)
  68. }
  69. $repoName = $info['name'];
  70. // Local vars that used to be FSRepo members...
  71. $directory = $info['directory'];
  72. $deletedDir = $info['deletedDir'] ?? false; // deletion disabled
  73. $thumbDir = $info['thumbDir'] ?? "{$directory}/thumb";
  74. $transcodedDir = $info['transcodedDir'] ?? "{$directory}/transcoded";
  75. // Get the FS backend configuration
  76. $autoBackends[] = [
  77. 'name' => $backendName,
  78. 'class' => FSFileBackend::class,
  79. 'lockManager' => 'fsLockManager',
  80. 'containerPaths' => [
  81. "{$repoName}-public" => "{$directory}",
  82. "{$repoName}-thumb" => $thumbDir,
  83. "{$repoName}-transcoded" => $transcodedDir,
  84. "{$repoName}-deleted" => $deletedDir,
  85. "{$repoName}-temp" => "{$directory}/temp"
  86. ],
  87. 'fileMode' => $info['fileMode'] ?? 0644,
  88. 'directoryMode' => $wgDirectoryMode,
  89. ];
  90. }
  91. // Register implicitly defined backends
  92. $this->register( $autoBackends, wfConfiguredReadOnlyReason() );
  93. }
  94. /**
  95. * Register an array of file backend configurations
  96. *
  97. * @param array[] $configs
  98. * @param string|null $readOnlyReason
  99. * @throws InvalidArgumentException
  100. */
  101. protected function register( array $configs, $readOnlyReason = null ) {
  102. foreach ( $configs as $config ) {
  103. if ( !isset( $config['name'] ) ) {
  104. throw new InvalidArgumentException( "Cannot register a backend with no name." );
  105. }
  106. $name = $config['name'];
  107. if ( isset( $this->backends[$name] ) ) {
  108. throw new LogicException( "Backend with name `{$name}` already registered." );
  109. } elseif ( !isset( $config['class'] ) ) {
  110. throw new InvalidArgumentException( "Backend with name `{$name}` has no class." );
  111. }
  112. $class = $config['class'];
  113. $config['readOnly'] = $config['readOnly'] ?? $readOnlyReason;
  114. unset( $config['class'] ); // backend won't need this
  115. $this->backends[$name] = [
  116. 'class' => $class,
  117. 'config' => $config,
  118. 'instance' => null
  119. ];
  120. }
  121. }
  122. /**
  123. * Get the backend object with a given name
  124. *
  125. * @param string $name
  126. * @return FileBackend
  127. * @throws InvalidArgumentException
  128. */
  129. public function get( $name ) {
  130. // Lazy-load the actual backend instance
  131. if ( !isset( $this->backends[$name]['instance'] ) ) {
  132. $config = $this->config( $name );
  133. $class = $config['class'];
  134. if ( $class === FileBackendMultiWrite::class ) {
  135. foreach ( $config['backends'] as $index => $beConfig ) {
  136. if ( isset( $beConfig['template'] ) ) {
  137. // Config is just a modified version of a registered backend's.
  138. // This should only be used when that config is used only by this backend.
  139. $config['backends'][$index] += $this->config( $beConfig['template'] );
  140. }
  141. }
  142. }
  143. $this->backends[$name]['instance'] = new $class( $config );
  144. }
  145. return $this->backends[$name]['instance'];
  146. }
  147. /**
  148. * Get the config array for a backend object with a given name
  149. *
  150. * @param string $name
  151. * @return array Parameters to FileBackend::__construct()
  152. * @throws InvalidArgumentException
  153. */
  154. public function config( $name ) {
  155. if ( !isset( $this->backends[$name] ) ) {
  156. throw new InvalidArgumentException( "No backend defined with the name `$name`." );
  157. }
  158. $class = $this->backends[$name]['class'];
  159. $config = $this->backends[$name]['config'];
  160. $config['class'] = $class;
  161. $config += [ // set defaults
  162. 'wikiId' => wfWikiID(), // e.g. "my_wiki-en_"
  163. 'mimeCallback' => [ $this, 'guessMimeInternal' ],
  164. 'obResetFunc' => 'wfResetOutputBuffers',
  165. 'streamMimeFunc' => [ StreamFile::class, 'contentTypeFromPath' ],
  166. 'tmpDirectory' => wfTempDir(),
  167. 'statusWrapper' => [ Status::class, 'wrap' ],
  168. 'wanCache' => MediaWikiServices::getInstance()->getMainWANObjectCache(),
  169. 'srvCache' => ObjectCache::getLocalServerInstance( 'hash' ),
  170. 'logger' => LoggerFactory::getInstance( 'FileOperation' ),
  171. 'profiler' => Profiler::instance()
  172. ];
  173. $config['lockManager'] =
  174. LockManagerGroup::singleton( $config['wikiId'] )->get( $config['lockManager'] );
  175. $config['fileJournal'] = isset( $config['fileJournal'] )
  176. ? FileJournal::factory( $config['fileJournal'], $name )
  177. : FileJournal::factory( [ 'class' => NullFileJournal::class ], $name );
  178. return $config;
  179. }
  180. /**
  181. * Get an appropriate backend object from a storage path
  182. *
  183. * @param string $storagePath
  184. * @return FileBackend|null Backend or null on failure
  185. */
  186. public function backendFromPath( $storagePath ) {
  187. list( $backend, , ) = FileBackend::splitStoragePath( $storagePath );
  188. if ( $backend !== null && isset( $this->backends[$backend] ) ) {
  189. return $this->get( $backend );
  190. }
  191. return null;
  192. }
  193. /**
  194. * @param string $storagePath
  195. * @param string|null $content
  196. * @param string|null $fsPath
  197. * @return string
  198. * @since 1.27
  199. */
  200. public function guessMimeInternal( $storagePath, $content, $fsPath ) {
  201. $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
  202. // Trust the extension of the storage path (caller must validate)
  203. $ext = FileBackend::extensionFromPath( $storagePath );
  204. $type = $magic->guessTypesForExtension( $ext );
  205. // For files without a valid extension (or one at all), inspect the contents
  206. if ( !$type && $fsPath ) {
  207. $type = $magic->guessMimeType( $fsPath, false );
  208. } elseif ( !$type && strlen( $content ) ) {
  209. $tmpFile = TempFSFile::factory( 'mime_', '', wfTempDir() );
  210. file_put_contents( $tmpFile->getPath(), $content );
  211. $type = $magic->guessMimeType( $tmpFile->getPath(), false );
  212. }
  213. return $type ?: 'unknown/unknown';
  214. }
  215. }