MediaWiki master
FileBackendGroup.php
Go to the documentation of this file.
1<?php
11
12use InvalidArgumentException;
13use LogicException;
21use Profiler;
26use Wikimedia\Mime\MimeAnalyzer;
29use 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 = [
74 'fallbackWikiId',
75 ];
76
87 public function __construct(
88 ServiceOptions $options,
89 ReadOnlyMode $readOnlyMode,
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 ), $readOnlyMode->getConfiguredReason() );
107
108 $autoBackends = [];
109 // Automatically create b/c backends for file repos...
110 $repos = array_merge(
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 // file deletion is disabled not set
121 $deletedDir = $info['deletedDir'] ?? false;
122 $thumbDir = $info['thumbDir'] ?? "{$directory}/thumb";
123 $transcodedDir = $info['transcodedDir'] ?? "{$directory}/transcoded";
124 $lockManager = $info['lockManager'] ?? 'fsLockManager';
125 // Get the FS backend configuration
126 $autoBackends[] = [
127 'name' => $backendName,
128 'class' => FSFileBackend::class,
129 'lockManager' => $lockManager,
130 'containerPaths' => [
131 "{$repoName}-public" => "{$directory}",
132 "{$repoName}-thumb" => $thumbDir,
133 "{$repoName}-transcoded" => $transcodedDir,
134 "{$repoName}-deleted" => $deletedDir,
135 "{$repoName}-temp" => "{$directory}/temp"
136 ],
137 'fileMode' => $info['fileMode'] ?? 0644,
138 'directoryMode' => $options->get( MainConfigNames::DirectoryMode ),
139 ];
140 }
141
142 // Register implicitly defined backends
143 $this->register( $autoBackends, $readOnlyMode->getConfiguredReason() );
144 }
145
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
183 public function get( $name ) {
184 // Lazy-load the actual backend instance
185 if ( !isset( $this->backends[$name]['instance'] ) ) {
186 $config = $this->config( $name );
187
188 $class = $config['class'];
189 // Checking old alias for compatibility with unchanged config
190 if ( $class === FileBackendMultiWrite::class || $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
213 public function config( $name ) {
214 if ( !isset( $this->backends[$name] ) ) {
215 throw new InvalidArgumentException( "No backend defined with the name '$name'." );
216 }
217
218 $config = $this->backends[$name]['config'];
219
220 return array_merge(
221 // Default backend parameters
222 [
223 'mimeCallback' => $this->guessMimeInternal( ... ),
224 'obResetFunc' => 'wfResetOutputBuffers',
225 'asyncHandler' => DeferredUpdates::addCallableUpdate( ... ),
226 'streamMimeFunc' => StreamFile::contentTypeFromPath( ... ),
227 'tmpFileFactory' => $this->tmpFileFactory,
228 'statusWrapper' => Status::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}
286class_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.
static contentTypeFromPath( $filename, $safe=true)
Determine the file type of a file based on the path.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:44
Profiler base class that defines the interface and some shared functionality.
Definition Profiler.php:22
static instance()
Definition Profiler.php:90
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:73
Multi-datacenter aware caching interface.
Determine whether a site is currently in read-only mode.