MediaWiki master
FileBackendGroup.php
Go to the documentation of this file.
1<?php
25
26use InvalidArgumentException;
27use LogicException;
35use Profiler;
39use Wikimedia\Mime\MimeAnalyzer;
42use Wikimedia\ObjectFactory\ObjectFactory;
44
56 protected $backends = [];
57
59 private $options;
60
62 private $srvCache;
63
65 private $wanCache;
66
68 private $mimeAnalyzer;
69
71 private $lmgFactory;
72
74 private $tmpFileFactory;
75
77 private $objectFactory;
78
82 public const CONSTRUCTOR_OPTIONS = [
87 'fallbackWikiId',
88 ];
89
100 public function __construct(
101 ServiceOptions $options,
102 ReadOnlyMode $readOnlyMode,
103 BagOStuff $srvCache,
104 WANObjectCache $wanCache,
105 MimeAnalyzer $mimeAnalyzer,
106 LockManagerGroupFactory $lmgFactory,
107 TempFSFileFactory $tmpFileFactory,
108 ObjectFactory $objectFactory
109 ) {
110 $this->options = $options;
111 $this->srvCache = $srvCache;
112 $this->wanCache = $wanCache;
113 $this->mimeAnalyzer = $mimeAnalyzer;
114 $this->lmgFactory = $lmgFactory;
115 $this->tmpFileFactory = $tmpFileFactory;
116 $this->objectFactory = $objectFactory;
117
118 // Register explicitly defined backends
119 $this->register( $options->get( MainConfigNames::FileBackends ), $readOnlyMode->getConfiguredReason() );
120
121 $autoBackends = [];
122 // Automatically create b/c backends for file repos...
123 $repos = array_merge(
125 foreach ( $repos as $info ) {
126 $backendName = $info['backend'];
127 if ( is_object( $backendName ) || isset( $this->backends[$backendName] ) ) {
128 continue; // already defined (or set to the object for some reason)
129 }
130 $repoName = $info['name'];
131 // Local vars that used to be FSRepo members...
132 $directory = $info['directory'];
133 $deletedDir = $info['deletedDir'] ?? false; // deletion disabled
134 $thumbDir = $info['thumbDir'] ?? "{$directory}/thumb";
135 $transcodedDir = $info['transcodedDir'] ?? "{$directory}/transcoded";
136 $lockManager = $info['lockManager'] ?? 'fsLockManager';
137 // Get the FS backend configuration
138 $autoBackends[] = [
139 'name' => $backendName,
140 'class' => FSFileBackend::class,
141 'lockManager' => $lockManager,
142 'containerPaths' => [
143 "{$repoName}-public" => "{$directory}",
144 "{$repoName}-thumb" => $thumbDir,
145 "{$repoName}-transcoded" => $transcodedDir,
146 "{$repoName}-deleted" => $deletedDir,
147 "{$repoName}-temp" => "{$directory}/temp"
148 ],
149 'fileMode' => $info['fileMode'] ?? 0644,
150 'directoryMode' => $options->get( MainConfigNames::DirectoryMode ),
151 ];
152 }
153
154 // Register implicitly defined backends
155 $this->register( $autoBackends, $readOnlyMode->getConfiguredReason() );
156 }
157
164 protected function register( array $configs, $readOnlyReason = null ) {
165 foreach ( $configs as $config ) {
166 if ( !isset( $config['name'] ) ) {
167 throw new InvalidArgumentException( "Cannot register a backend with no name." );
168 }
169 $name = $config['name'];
170 if ( isset( $this->backends[$name] ) ) {
171 throw new LogicException( "Backend with name '$name' already registered." );
172 } elseif ( !isset( $config['class'] ) ) {
173 throw new InvalidArgumentException( "Backend with name '$name' has no class." );
174 }
175 $class = $config['class'];
176
177 $config['domainId'] ??= $config['wikiId'] ?? $this->options->get( 'fallbackWikiId' );
178 $config['readOnly'] ??= $readOnlyReason;
179
180 unset( $config['class'] ); // backend won't need this
181 $this->backends[$name] = [
182 'class' => $class,
183 'config' => $config,
184 'instance' => null
185 ];
186 }
187 }
188
195 public function get( $name ) {
196 // Lazy-load the actual backend instance
197 if ( !isset( $this->backends[$name]['instance'] ) ) {
198 $config = $this->config( $name );
199
200 $class = $config['class'];
201 // Checking old alias for compatibility with unchanged config
202 if ( $class === FileBackendMultiWrite::class || $class === \FileBackendMultiWrite::class ) {
203 // @todo How can we test this? What's the intended use-case?
204 foreach ( $config['backends'] as $index => $beConfig ) {
205 if ( isset( $beConfig['template'] ) ) {
206 // Config is just a modified version of a registered backend's.
207 // This should only be used when that config is used only by this backend.
208 $config['backends'][$index] += $this->config( $beConfig['template'] );
209 }
210 }
211 }
212
213 $this->backends[$name]['instance'] = new $class( $config );
214 }
215
216 return $this->backends[$name]['instance'];
217 }
218
225 public function config( $name ) {
226 if ( !isset( $this->backends[$name] ) ) {
227 throw new InvalidArgumentException( "No backend defined with the name '$name'." );
228 }
229
230 $config = $this->backends[$name]['config'];
231
232 return array_merge(
233 // Default backend parameters
234 [
235 'mimeCallback' => [ $this, 'guessMimeInternal' ],
236 'obResetFunc' => 'wfResetOutputBuffers',
237 'streamMimeFunc' => [ StreamFile::class, 'contentTypeFromPath' ],
238 'tmpFileFactory' => $this->tmpFileFactory,
239 'statusWrapper' => [ Status::class, 'wrap' ],
240 'wanCache' => $this->wanCache,
241 'srvCache' => $this->srvCache,
242 'logger' => LoggerFactory::getInstance( 'FileOperation' ),
243 'profiler' => static function ( $section ) {
244 return Profiler::instance()->scopedProfileIn( $section );
245 }
246 ],
247 // Configured backend parameters
248 $config,
249 // Resolved backend parameters
250 [
251 'class' => $this->backends[$name]['class'],
252 'lockManager' =>
253 $this->lmgFactory->getLockManagerGroup( $config['domainId'] )
254 ->get( $config['lockManager'] ),
255 ]
256 );
257 }
258
265 public function backendFromPath( $storagePath ) {
266 [ $backend, , ] = FileBackend::splitStoragePath( $storagePath );
267 if ( $backend !== null && isset( $this->backends[$backend] ) ) {
268 return $this->get( $backend );
269 }
270
271 return null;
272 }
273
281 public function guessMimeInternal( $storagePath, $content, $fsPath ) {
282 // Trust the extension of the storage path (caller must validate)
283 $ext = FileBackend::extensionFromPath( $storagePath );
284 $type = $this->mimeAnalyzer->getMimeTypeFromExtensionOrNull( $ext );
285 // For files without a valid extension (or one at all), inspect the contents
286 if ( !$type && $fsPath ) {
287 $type = $this->mimeAnalyzer->guessMimeType( $fsPath, false );
288 } elseif ( !$type && $content !== null && $content !== '' ) {
289 $tmpFile = $this->tmpFileFactory->newTempFSFile( 'mime_', '' );
290 file_put_contents( $tmpFile->getPath(), $content );
291 $type = $this->mimeAnalyzer->guessMimeType( $tmpFile->getPath(), false );
292 }
293 return $type ?: 'unknown/unknown';
294 }
295}
297class_alias( FileBackendGroup::class, 'FileBackendGroup' );
A class for passing options to services.
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:89
Multi-datacenter aware caching interface.
Determine whether a site is currently in read-only mode.