MediaWiki master
FileBackendGroup.php
Go to the documentation of this file.
1<?php
25
26use InvalidArgumentException;
27use LogicException;
35use Profiler;
40use Wikimedia\Mime\MimeAnalyzer;
43use Wikimedia\ObjectFactory\ObjectFactory;
45
57 protected $backends = [];
58
60 private $options;
61
63 private $srvCache;
64
66 private $wanCache;
67
69 private $mimeAnalyzer;
70
72 private $lmgFactory;
73
75 private $tmpFileFactory;
76
78 private $objectFactory;
79
83 public const CONSTRUCTOR_OPTIONS = [
88 'fallbackWikiId',
89 ];
90
101 public function __construct(
102 ServiceOptions $options,
103 ReadOnlyMode $readOnlyMode,
104 BagOStuff $srvCache,
105 WANObjectCache $wanCache,
106 MimeAnalyzer $mimeAnalyzer,
107 LockManagerGroupFactory $lmgFactory,
108 TempFSFileFactory $tmpFileFactory,
109 ObjectFactory $objectFactory
110 ) {
111 $this->options = $options;
112 $this->srvCache = $srvCache;
113 $this->wanCache = $wanCache;
114 $this->mimeAnalyzer = $mimeAnalyzer;
115 $this->lmgFactory = $lmgFactory;
116 $this->tmpFileFactory = $tmpFileFactory;
117 $this->objectFactory = $objectFactory;
118
119 // Register explicitly defined backends
120 $this->register( $options->get( MainConfigNames::FileBackends ), $readOnlyMode->getConfiguredReason() );
121
122 $autoBackends = [];
123 // Automatically create b/c backends for file repos...
124 $repos = array_merge(
126 foreach ( $repos as $info ) {
127 $backendName = $info['backend'];
128 if ( is_object( $backendName ) || isset( $this->backends[$backendName] ) ) {
129 continue; // already defined (or set to the object for some reason)
130 }
131 $repoName = $info['name'];
132 // Local vars that used to be FSRepo members...
133 $directory = $info['directory'];
134 $deletedDir = $info['deletedDir'] ?? false; // deletion disabled
135 $thumbDir = $info['thumbDir'] ?? "{$directory}/thumb";
136 $transcodedDir = $info['transcodedDir'] ?? "{$directory}/transcoded";
137 $lockManager = $info['lockManager'] ?? 'fsLockManager';
138 // Get the FS backend configuration
139 $autoBackends[] = [
140 'name' => $backendName,
141 'class' => FSFileBackend::class,
142 'lockManager' => $lockManager,
143 'containerPaths' => [
144 "{$repoName}-public" => "{$directory}",
145 "{$repoName}-thumb" => $thumbDir,
146 "{$repoName}-transcoded" => $transcodedDir,
147 "{$repoName}-deleted" => $deletedDir,
148 "{$repoName}-temp" => "{$directory}/temp"
149 ],
150 'fileMode' => $info['fileMode'] ?? 0644,
151 'directoryMode' => $options->get( MainConfigNames::DirectoryMode ),
152 ];
153 }
154
155 // Register implicitly defined backends
156 $this->register( $autoBackends, $readOnlyMode->getConfiguredReason() );
157 }
158
165 protected function register( array $configs, $readOnlyReason = null ) {
166 foreach ( $configs as $config ) {
167 if ( !isset( $config['name'] ) ) {
168 throw new InvalidArgumentException( "Cannot register a backend with no name." );
169 }
170 $name = $config['name'];
171 if ( isset( $this->backends[$name] ) ) {
172 throw new LogicException( "Backend with name '$name' already registered." );
173 } elseif ( !isset( $config['class'] ) ) {
174 throw new InvalidArgumentException( "Backend with name '$name' has no class." );
175 }
176 $class = $config['class'];
177
178 $config['domainId'] ??= $config['wikiId'] ?? $this->options->get( 'fallbackWikiId' );
179 $config['readOnly'] ??= $readOnlyReason;
180
181 unset( $config['class'] ); // backend won't need this
182 $this->backends[$name] = [
183 'class' => $class,
184 'config' => $config,
185 'instance' => null
186 ];
187 }
188 }
189
196 public function get( $name ) {
197 // Lazy-load the actual backend instance
198 if ( !isset( $this->backends[$name]['instance'] ) ) {
199 $config = $this->config( $name );
200
201 $class = $config['class'];
202 // Checking old alias for compatibility with unchanged config
203 if ( $class === FileBackendMultiWrite::class || $class === \FileBackendMultiWrite::class ) {
204 // @todo How can we test this? What's the intended use-case?
205 foreach ( $config['backends'] as $index => $beConfig ) {
206 if ( isset( $beConfig['template'] ) ) {
207 // Config is just a modified version of a registered backend's.
208 // This should only be used when that config is used only by this backend.
209 $config['backends'][$index] += $this->config( $beConfig['template'] );
210 }
211 }
212 }
213
214 $this->backends[$name]['instance'] = new $class( $config );
215 }
216
217 return $this->backends[$name]['instance'];
218 }
219
226 public function config( $name ) {
227 if ( !isset( $this->backends[$name] ) ) {
228 throw new InvalidArgumentException( "No backend defined with the name '$name'." );
229 }
230
231 $config = $this->backends[$name]['config'];
232
233 return array_merge(
234 // Default backend parameters
235 [
236 'mimeCallback' => [ $this, 'guessMimeInternal' ],
237 'obResetFunc' => 'wfResetOutputBuffers',
238 'asyncHandler' => [ DeferredUpdates::class, 'addCallableUpdate' ],
239 'streamMimeFunc' => [ StreamFile::class, 'contentTypeFromPath' ],
240 'tmpFileFactory' => $this->tmpFileFactory,
241 'statusWrapper' => [ Status::class, 'wrap' ],
242 'wanCache' => $this->wanCache,
243 'srvCache' => $this->srvCache,
244 'logger' => LoggerFactory::getInstance( 'FileOperation' ),
245 'profiler' => static function ( $section ) {
246 return Profiler::instance()->scopedProfileIn( $section );
247 }
248 ],
249 // Configured backend parameters
250 $config,
251 // Resolved backend parameters
252 [
253 'class' => $this->backends[$name]['class'],
254 'lockManager' =>
255 $this->lmgFactory->getLockManagerGroup( $config['domainId'] )
256 ->get( $config['lockManager'] ),
257 ]
258 );
259 }
260
267 public function backendFromPath( $storagePath ) {
268 [ $backend, , ] = FileBackend::splitStoragePath( $storagePath );
269 if ( $backend !== null && isset( $this->backends[$backend] ) ) {
270 return $this->get( $backend );
271 }
272
273 return null;
274 }
275
283 public function guessMimeInternal( $storagePath, $content, $fsPath ) {
284 // Trust the extension of the storage path (caller must validate)
285 $ext = FileBackend::extensionFromPath( $storagePath );
286 $type = $this->mimeAnalyzer->getMimeTypeFromExtensionOrNull( $ext );
287 // For files without a valid extension (or one at all), inspect the contents
288 if ( !$type && $fsPath ) {
289 $type = $this->mimeAnalyzer->guessMimeType( $fsPath, false );
290 } elseif ( !$type && $content !== null && $content !== '' ) {
291 $tmpFile = $this->tmpFileFactory->newTempFSFile( 'mime_', '' );
292 file_put_contents( $tmpFile->getPath(), $content );
293 $type = $this->mimeAnalyzer->guessMimeType( $tmpFile->getPath(), false );
294 }
295 return $type ?: 'unknown/unknown';
296 }
297}
299class_alias( FileBackendGroup::class, 'FileBackendGroup' );
A class for passing options to services.
Defer callable updates to run later in the PHP process.
Class to handle file backend registration.
backendFromPath( $storagePath)
Get an appropriate backend object from a storage path.
config( $name)
Get the config array for a backend object with a given name.
__construct(ServiceOptions $options, ReadOnlyMode $readOnlyMode, BagOStuff $srvCache, WANObjectCache $wanCache, MimeAnalyzer $mimeAnalyzer, LockManagerGroupFactory $lmgFactory, TempFSFileFactory $tmpFileFactory, ObjectFactory $objectFactory)
array[] $backends
(name => ('class' => string, 'config' => array, 'instance' => object))
guessMimeInternal( $storagePath, $content, $fsPath)
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
const FileBackends
Name constant for the FileBackends setting, for use with Config::get()
const LocalFileRepo
Name constant for the LocalFileRepo setting, for use with Config::get()
const ForeignFileRepos
Name constant for the ForeignFileRepos setting, for use with Config::get()
const DirectoryMode
Name constant for the DirectoryMode setting, for use with Config::get()
Functions related to the output of file content.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:54
Profiler base class that defines the interface and some shared functionality.
Definition Profiler.php:37
static instance()
Definition Profiler.php:105
Class for a file system (FS) based file backend.
Proxy backend that mirrors writes to several internal backends.
Base class for all file backend classes (including multi-write backends).
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
Abstract class for any ephemeral data store.
Definition BagOStuff.php:88
Multi-datacenter aware caching interface.
Determine whether a site is currently in read-only mode.