MediaWiki  master
FileBackendGroup.php
Go to the documentation of this file.
1 <?php
29 use Wikimedia\ObjectFactory\ObjectFactory;
31 
43  protected $backends = [];
44 
46  private $options;
47 
49  private $srvCache;
50 
52  private $wanCache;
53 
55  private $mimeAnalyzer;
56 
58  private $lmgFactory;
59 
61  private $tmpFileFactory;
62 
64  private $objectFactory;
65 
69  public const CONSTRUCTOR_OPTIONS = [
70  MainConfigNames::DirectoryMode,
71  MainConfigNames::FileBackends,
72  MainConfigNames::ForeignFileRepos,
73  MainConfigNames::LocalFileRepo,
74  'fallbackWikiId',
75  ];
76 
87  public function __construct(
88  ServiceOptions $options,
89  ConfiguredReadOnlyMode $configuredReadOnlyMode,
90  BagOStuff $srvCache,
91  WANObjectCache $wanCache,
92  MimeAnalyzer $mimeAnalyzer,
93  LockManagerGroupFactory $lmgFactory,
94  TempFSFileFactory $tmpFileFactory,
95  ObjectFactory $objectFactory
96  ) {
97  $this->options = $options;
98  $this->srvCache = $srvCache;
99  $this->wanCache = $wanCache;
100  $this->mimeAnalyzer = $mimeAnalyzer;
101  $this->lmgFactory = $lmgFactory;
102  $this->tmpFileFactory = $tmpFileFactory;
103  $this->objectFactory = $objectFactory;
104 
105  // Register explicitly defined backends
106  $this->register( $options->get( MainConfigNames::FileBackends ), $configuredReadOnlyMode->getReason() );
107 
108  $autoBackends = [];
109  // Automatically create b/c backends for file repos...
110  $repos = array_merge(
111  $options->get( MainConfigNames::ForeignFileRepos ), [ $options->get( MainConfigNames::LocalFileRepo ) ] );
112  foreach ( $repos as $info ) {
113  $backendName = $info['backend'];
114  if ( is_object( $backendName ) || isset( $this->backends[$backendName] ) ) {
115  continue; // already defined (or set to the object for some reason)
116  }
117  $repoName = $info['name'];
118  // Local vars that used to be FSRepo members...
119  $directory = $info['directory'];
120  $deletedDir = $info['deletedDir'] ?? false; // deletion disabled
121  $thumbDir = $info['thumbDir'] ?? "{$directory}/thumb";
122  $transcodedDir = $info['transcodedDir'] ?? "{$directory}/transcoded";
123  $lockManager = $info['lockManager'] ?? 'fsLockManager';
124  // Get the FS backend configuration
125  $autoBackends[] = [
126  'name' => $backendName,
127  'class' => FSFileBackend::class,
128  'lockManager' => $lockManager,
129  'containerPaths' => [
130  "{$repoName}-public" => "{$directory}",
131  "{$repoName}-thumb" => $thumbDir,
132  "{$repoName}-transcoded" => $transcodedDir,
133  "{$repoName}-deleted" => $deletedDir,
134  "{$repoName}-temp" => "{$directory}/temp"
135  ],
136  'fileMode' => $info['fileMode'] ?? 0644,
137  'directoryMode' => $options->get( MainConfigNames::DirectoryMode ),
138  ];
139  }
140 
141  // Register implicitly defined backends
142  $this->register( $autoBackends, $configuredReadOnlyMode->getReason() );
143  }
144 
152  protected function register( array $configs, $readOnlyReason = null ) {
153  foreach ( $configs as $config ) {
154  if ( !isset( $config['name'] ) ) {
155  throw new InvalidArgumentException( "Cannot register a backend with no name." );
156  }
157  $name = $config['name'];
158  if ( isset( $this->backends[$name] ) ) {
159  throw new LogicException( "Backend with name '$name' already registered." );
160  } elseif ( !isset( $config['class'] ) ) {
161  throw new InvalidArgumentException( "Backend with name '$name' has no class." );
162  }
163  $class = $config['class'];
164 
165  $config['domainId'] ??= $config['wikiId'] ?? $this->options->get( 'fallbackWikiId' );
166  $config['readOnly'] ??= $readOnlyReason;
167 
168  unset( $config['class'] ); // backend won't need this
169  $this->backends[$name] = [
170  'class' => $class,
171  'config' => $config,
172  'instance' => null
173  ];
174  }
175  }
176 
184  public function get( $name ) {
185  // Lazy-load the actual backend instance
186  if ( !isset( $this->backends[$name]['instance'] ) ) {
187  $config = $this->config( $name );
188 
189  $class = $config['class'];
190  if ( $class === FileBackendMultiWrite::class ) {
191  // @todo How can we test this? What's the intended use-case?
192  foreach ( $config['backends'] as $index => $beConfig ) {
193  if ( isset( $beConfig['template'] ) ) {
194  // Config is just a modified version of a registered backend's.
195  // This should only be used when that config is used only by this backend.
196  $config['backends'][$index] += $this->config( $beConfig['template'] );
197  }
198  }
199  }
200 
201  $this->backends[$name]['instance'] = new $class( $config );
202  }
203 
204  return $this->backends[$name]['instance'];
205  }
206 
214  public function config( $name ) {
215  if ( !isset( $this->backends[$name] ) ) {
216  throw new InvalidArgumentException( "No backend defined with the name '$name'." );
217  }
218 
219  $config = $this->backends[$name]['config'];
220 
221  return array_merge(
222  // Default backend parameters
223  [
224  'mimeCallback' => [ $this, 'guessMimeInternal' ],
225  'obResetFunc' => 'wfResetOutputBuffers',
226  'streamMimeFunc' => [ StreamFile::class, 'contentTypeFromPath' ],
227  'tmpFileFactory' => $this->tmpFileFactory,
228  'statusWrapper' => [ Status::class, 'wrap' ],
229  'wanCache' => $this->wanCache,
230  'srvCache' => $this->srvCache,
231  'logger' => LoggerFactory::getInstance( 'FileOperation' ),
232  'profiler' => static function ( $section ) {
233  return Profiler::instance()->scopedProfileIn( $section );
234  }
235  ],
236  // Configured backend parameters
237  $config,
238  // Resolved backend parameters
239  [
240  'class' => $this->backends[$name]['class'],
241  'lockManager' =>
242  $this->lmgFactory->getLockManagerGroup( $config['domainId'] )
243  ->get( $config['lockManager'] ),
244  ]
245  );
246  }
247 
254  public function backendFromPath( $storagePath ) {
255  [ $backend, , ] = FileBackend::splitStoragePath( $storagePath );
256  if ( $backend !== null && isset( $this->backends[$backend] ) ) {
257  return $this->get( $backend );
258  }
259 
260  return null;
261  }
262 
270  public function guessMimeInternal( $storagePath, $content, $fsPath ) {
271  // Trust the extension of the storage path (caller must validate)
272  $ext = FileBackend::extensionFromPath( $storagePath );
273  $type = $this->mimeAnalyzer->getMimeTypeFromExtensionOrNull( $ext );
274  // For files without a valid extension (or one at all), inspect the contents
275  if ( !$type && $fsPath ) {
276  $type = $this->mimeAnalyzer->guessMimeType( $fsPath, false );
277  } elseif ( !$type && $content !== null && $content !== '' ) {
278  $tmpFile = $this->tmpFileFactory->newTempFSFile( 'mime_', '' );
279  file_put_contents( $tmpFile->getPath(), $content );
280  $type = $this->mimeAnalyzer->guessMimeType( $tmpFile->getPath(), false );
281  }
282  return $type ?: 'unknown/unknown';
283  }
284 }
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:85
Class to handle file backend registration.
config( $name)
Get the config array for a backend object with a given name.
guessMimeInternal( $storagePath, $content, $fsPath)
__construct(ServiceOptions $options, ConfiguredReadOnlyMode $configuredReadOnlyMode, BagOStuff $srvCache, WANObjectCache $wanCache, MimeAnalyzer $mimeAnalyzer, LockManagerGroupFactory $lmgFactory, TempFSFileFactory $tmpFileFactory, ObjectFactory $objectFactory)
backendFromPath( $storagePath)
Get an appropriate backend object from a storage path.
array[] $backends
(name => ('class' => string, 'config' => array, 'instance' => object))
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
A class for passing options to services.
PSR-3 logger instance factory.
A class containing constants representing the names of configuration variables.
Implements functions related to MIME types such as detection and mapping to file extension.
static instance()
Singleton.
Definition: Profiler.php:108
Multi-datacenter aware caching interface.
Determine whether a site is statically configured as read-only.
$content
Definition: router.php:76
if(!is_readable( $file)) $ext
Definition: router.php:48