MediaWiki  master
FileBackendGroup.php
Go to the documentation of this file.
1 <?php
26 
35  protected static $instance = null;
36 
38  protected $backends = [];
39 
40  protected function __construct() {
41  }
42 
46  public static function singleton() {
47  if ( self::$instance == null ) {
48  self::$instance = new self();
49  self::$instance->initFromGlobals();
50  }
51 
52  return self::$instance;
53  }
54 
58  public static function destroySingleton() {
59  self::$instance = null;
60  }
61 
65  protected function initFromGlobals() {
67 
68  // Register explicitly defined backends
69  $this->register( $wgFileBackends, wfConfiguredReadOnlyReason() );
70 
71  $autoBackends = [];
72  // Automatically create b/c backends for file repos...
73  $repos = array_merge( $wgForeignFileRepos, [ $wgLocalFileRepo ] );
74  foreach ( $repos as $info ) {
75  $backendName = $info['backend'];
76  if ( is_object( $backendName ) || isset( $this->backends[$backendName] ) ) {
77  continue; // already defined (or set to the object for some reason)
78  }
79  $repoName = $info['name'];
80  // Local vars that used to be FSRepo members...
81  $directory = $info['directory'];
82  $deletedDir = $info['deletedDir'] ?? false; // deletion disabled
83  $thumbDir = $info['thumbDir'] ?? "{$directory}/thumb";
84  $transcodedDir = $info['transcodedDir'] ?? "{$directory}/transcoded";
85  // Get the FS backend configuration
86  $autoBackends[] = [
87  'name' => $backendName,
88  'class' => FSFileBackend::class,
89  'lockManager' => 'fsLockManager',
90  'containerPaths' => [
91  "{$repoName}-public" => "{$directory}",
92  "{$repoName}-thumb" => $thumbDir,
93  "{$repoName}-transcoded" => $transcodedDir,
94  "{$repoName}-deleted" => $deletedDir,
95  "{$repoName}-temp" => "{$directory}/temp"
96  ],
97  'fileMode' => $info['fileMode'] ?? 0644,
98  'directoryMode' => $wgDirectoryMode,
99  ];
100  }
101 
102  // Register implicitly defined backends
103  $this->register( $autoBackends, wfConfiguredReadOnlyReason() );
104  }
105 
113  protected function register( array $configs, $readOnlyReason = null ) {
114  foreach ( $configs as $config ) {
115  if ( !isset( $config['name'] ) ) {
116  throw new InvalidArgumentException( "Cannot register a backend with no name." );
117  }
118  $name = $config['name'];
119  if ( isset( $this->backends[$name] ) ) {
120  throw new LogicException( "Backend with name '$name' already registered." );
121  } elseif ( !isset( $config['class'] ) ) {
122  throw new InvalidArgumentException( "Backend with name '$name' has no class." );
123  }
124  $class = $config['class'];
125 
126  // @FIXME: ideally this would default to the DB domain (which includes the schema)
127  $config['domainId'] = $config['domainId'] ?? ( $config['wikiId'] ?? wfWikiID() );
128  $config['readOnly'] = $config['readOnly'] ?? $readOnlyReason;
129 
130  unset( $config['class'] ); // backend won't need this
131  $this->backends[$name] = [
132  'class' => $class,
133  'config' => $config,
134  'instance' => null
135  ];
136  }
137  }
138 
146  public function get( $name ) {
147  // Lazy-load the actual backend instance
148  if ( !isset( $this->backends[$name]['instance'] ) ) {
149  $config = $this->config( $name );
150 
151  $class = $config['class'];
152  if ( $class === FileBackendMultiWrite::class ) {
153  foreach ( $config['backends'] as $index => $beConfig ) {
154  if ( isset( $beConfig['template'] ) ) {
155  // Config is just a modified version of a registered backend's.
156  // This should only be used when that config is used only by this backend.
157  $config['backends'][$index] += $this->config( $beConfig['template'] );
158  }
159  }
160  }
161 
162  $this->backends[$name]['instance'] = new $class( $config );
163  }
164 
165  return $this->backends[$name]['instance'];
166  }
167 
175  public function config( $name ) {
176  if ( !isset( $this->backends[$name] ) ) {
177  throw new InvalidArgumentException( "No backend defined with the name '$name'." );
178  }
179 
180  $config = $this->backends[$name]['config'];
181  $services = MediaWikiServices::getInstance();
182 
183  return array_merge(
184  // Default backend parameters
185  [
186  'mimeCallback' => [ $this, 'guessMimeInternal' ],
187  'obResetFunc' => 'wfResetOutputBuffers',
188  'streamMimeFunc' => [ StreamFile::class, 'contentTypeFromPath' ],
189  'tmpDirectory' => wfTempDir(),
190  'statusWrapper' => [ Status::class, 'wrap' ],
191  'wanCache' => $services->getMainWANObjectCache(),
192  'srvCache' => ObjectCache::getLocalServerInstance( 'hash' ),
193  'logger' => LoggerFactory::getInstance( 'FileOperation' ),
194  'profiler' => function ( $section ) {
195  return Profiler::instance()->scopedProfileIn( $section );
196  }
197  ],
198  // Configured backend parameters
199  $config,
200  // Resolved backend parameters
201  [
202  'class' => $this->backends[$name]['class'],
203  'lockManager' =>
204  LockManagerGroup::singleton( $config['domainId'] )
205  ->get( $config['lockManager'] ),
206  'fileJournal' => isset( $config['fileJournal'] )
207  ? FileJournal::factory( $config['fileJournal'], $name )
208  : FileJournal::factory( [ 'class' => NullFileJournal::class ], $name )
209  ]
210  );
211  }
212 
219  public function backendFromPath( $storagePath ) {
220  list( $backend, , ) = FileBackend::splitStoragePath( $storagePath );
221  if ( $backend !== null && isset( $this->backends[$backend] ) ) {
222  return $this->get( $backend );
223  }
224 
225  return null;
226  }
227 
235  public function guessMimeInternal( $storagePath, $content, $fsPath ) {
236  $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
237  // Trust the extension of the storage path (caller must validate)
238  $ext = FileBackend::extensionFromPath( $storagePath );
239  $type = $magic->guessTypesForExtension( $ext );
240  // For files without a valid extension (or one at all), inspect the contents
241  if ( !$type && $fsPath ) {
242  $type = $magic->guessMimeType( $fsPath, false );
243  } elseif ( !$type && strlen( $content ) ) {
244  $tmpFile = TempFSFile::factory( 'mime_', '', wfTempDir() );
245  file_put_contents( $tmpFile->getPath(), $content );
246  $type = $magic->guessMimeType( $tmpFile->getPath(), false );
247  }
248  return $type ?: 'unknown/unknown';
249  }
250 }
$wgForeignFileRepos
Enable the use of files from one or more other wikis.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static instance()
Singleton.
Definition: Profiler.php:62
$wgFileBackends
File backend structure configuration.
$wgLocalFileRepo
File repository structures.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
static destroySingleton()
Destroy the singleton instance.
guessMimeInternal( $storagePath, $content, $fsPath)
static getInstance()
Returns the global default instance of the top level service locator.
config( $name)
Get the config array for a backend object with a given name.
wfConfiguredReadOnlyReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
wfTempDir()
Tries to get the system directory for temporary files.
static factory( $prefix, $extension='', $tmpDirectory=null)
Make a new temporary file on the file system.
Definition: TempFSFile.php:55
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2205
initFromGlobals()
Register file backends from the global variables.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition: hooks.txt:3039
Class to handle file backend registration.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static singleton( $domain=false)
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
array $backends
(name => (&#39;class&#39; => string, &#39;config&#39; => array, &#39;instance&#39; => object))
backendFromPath( $storagePath)
Get an appropriate backend object from a storage path.
static FileBackendGroup $instance
if(!is_readable( $file)) $ext
Definition: router.php:48
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
static getLocalServerInstance( $fallback=CACHE_NONE)
Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
$content
Definition: pageupdater.txt:72
$wgDirectoryMode
Default value for chmoding of new directories.
static factory(array $config, $backend)
Create an appropriate FileJournal object from config.
Definition: FileJournal.php:63