MediaWiki  1.30.0
FileBackendGroup.php
Go to the documentation of this file.
1 <?php
25 
34  protected static $instance = null;
35 
37  protected $backends = [];
38 
39  protected function __construct() {
40  }
41 
45  public static function singleton() {
46  if ( self::$instance == null ) {
47  self::$instance = new self();
48  self::$instance->initFromGlobals();
49  }
50 
51  return self::$instance;
52  }
53 
57  public static function destroySingleton() {
58  self::$instance = null;
59  }
60 
64  protected function initFromGlobals() {
66 
67  // Register explicitly defined backends
68  $this->register( $wgFileBackends, wfConfiguredReadOnlyReason() );
69 
70  $autoBackends = [];
71  // Automatically create b/c backends for file repos...
72  $repos = array_merge( $wgForeignFileRepos, [ $wgLocalFileRepo ] );
73  foreach ( $repos as $info ) {
74  $backendName = $info['backend'];
75  if ( is_object( $backendName ) || isset( $this->backends[$backendName] ) ) {
76  continue; // already defined (or set to the object for some reason)
77  }
78  $repoName = $info['name'];
79  // Local vars that used to be FSRepo members...
80  $directory = $info['directory'];
81  $deletedDir = isset( $info['deletedDir'] )
82  ? $info['deletedDir']
83  : false; // deletion disabled
84  $thumbDir = isset( $info['thumbDir'] )
85  ? $info['thumbDir']
86  : "{$directory}/thumb";
87  $transcodedDir = isset( $info['transcodedDir'] )
88  ? $info['transcodedDir']
89  : "{$directory}/transcoded";
90  // Get the FS backend configuration
91  $autoBackends[] = [
92  'name' => $backendName,
93  'class' => 'FSFileBackend',
94  'lockManager' => 'fsLockManager',
95  'containerPaths' => [
96  "{$repoName}-public" => "{$directory}",
97  "{$repoName}-thumb" => $thumbDir,
98  "{$repoName}-transcoded" => $transcodedDir,
99  "{$repoName}-deleted" => $deletedDir,
100  "{$repoName}-temp" => "{$directory}/temp"
101  ],
102  'fileMode' => isset( $info['fileMode'] ) ? $info['fileMode'] : 0644,
103  'directoryMode' => $wgDirectoryMode,
104  ];
105  }
106 
107  // Register implicitly defined backends
108  $this->register( $autoBackends, wfConfiguredReadOnlyReason() );
109  }
110 
118  protected function register( array $configs, $readOnlyReason = null ) {
119  foreach ( $configs as $config ) {
120  if ( !isset( $config['name'] ) ) {
121  throw new InvalidArgumentException( "Cannot register a backend with no name." );
122  }
123  $name = $config['name'];
124  if ( isset( $this->backends[$name] ) ) {
125  throw new LogicException( "Backend with name `{$name}` already registered." );
126  } elseif ( !isset( $config['class'] ) ) {
127  throw new InvalidArgumentException( "Backend with name `{$name}` has no class." );
128  }
129  $class = $config['class'];
130 
131  $config['readOnly'] = !empty( $config['readOnly'] )
132  ? $config['readOnly']
133  : $readOnlyReason;
134 
135  unset( $config['class'] ); // backend won't need this
136  $this->backends[$name] = [
137  'class' => $class,
138  'config' => $config,
139  'instance' => null
140  ];
141  }
142  }
143 
151  public function get( $name ) {
152  // Lazy-load the actual backend instance
153  if ( !isset( $this->backends[$name]['instance'] ) ) {
154  $config = $this->config( $name );
155 
156  $class = $config['class'];
157  if ( $class === 'FileBackendMultiWrite' ) {
158  foreach ( $config['backends'] as $index => $beConfig ) {
159  if ( isset( $beConfig['template'] ) ) {
160  // Config is just a modified version of a registered backend's.
161  // This should only be used when that config is used only by this backend.
162  $config['backends'][$index] += $this->config( $beConfig['template'] );
163  }
164  }
165  }
166 
167  $this->backends[$name]['instance'] = new $class( $config );
168  }
169 
170  return $this->backends[$name]['instance'];
171  }
172 
180  public function config( $name ) {
181  if ( !isset( $this->backends[$name] ) ) {
182  throw new InvalidArgumentException( "No backend defined with the name `$name`." );
183  }
184  $class = $this->backends[$name]['class'];
185 
186  $config = $this->backends[$name]['config'];
187  $config['class'] = $class;
188  $config += [ // set defaults
189  'wikiId' => wfWikiID(), // e.g. "my_wiki-en_"
190  'mimeCallback' => [ $this, 'guessMimeInternal' ],
191  'obResetFunc' => 'wfResetOutputBuffers',
192  'streamMimeFunc' => [ 'StreamFile', 'contentTypeFromPath' ],
193  'tmpDirectory' => wfTempDir(),
194  'statusWrapper' => [ 'Status', 'wrap' ],
195  'wanCache' => MediaWikiServices::getInstance()->getMainWANObjectCache(),
196  'srvCache' => ObjectCache::getLocalServerInstance( 'hash' ),
197  'logger' => LoggerFactory::getInstance( 'FileOperation' ),
198  'profiler' => Profiler::instance()
199  ];
200  $config['lockManager'] =
201  LockManagerGroup::singleton( $config['wikiId'] )->get( $config['lockManager'] );
202  $config['fileJournal'] = isset( $config['fileJournal'] )
203  ? FileJournal::factory( $config['fileJournal'], $name )
204  : FileJournal::factory( [ 'class' => 'NullFileJournal' ], $name );
205 
206  return $config;
207  }
208 
215  public function backendFromPath( $storagePath ) {
216  list( $backend, , ) = FileBackend::splitStoragePath( $storagePath );
217  if ( $backend !== null && isset( $this->backends[$backend] ) ) {
218  return $this->get( $backend );
219  }
220 
221  return null;
222  }
223 
231  public function guessMimeInternal( $storagePath, $content, $fsPath ) {
232  $magic = MimeMagic::singleton();
233  // Trust the extension of the storage path (caller must validate)
234  $ext = FileBackend::extensionFromPath( $storagePath );
235  $type = $magic->guessTypesForExtension( $ext );
236  // For files without a valid extension (or one at all), inspect the contents
237  if ( !$type && $fsPath ) {
238  $type = $magic->guessMimeType( $fsPath, false );
239  } elseif ( !$type && strlen( $content ) ) {
240  $tmpFile = TempFSFile::factory( 'mime_', '', wfTempDir() );
241  file_put_contents( $tmpFile->getPath(), $content );
242  $type = $magic->guessMimeType( $tmpFile->getPath(), false );
243  }
244  return $type ?: 'unknown/unknown';
245  }
246 }
FileBackend\splitStoragePath
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
Definition: FileBackend.php:1447
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
FileBackendGroup
Class to handle file backend registration.
Definition: FileBackendGroup.php:32
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:62
$wgLocalFileRepo
$wgLocalFileRepo
File repository structures.
Definition: DefaultSettings.php:517
wfConfiguredReadOnlyReason
wfConfiguredReadOnlyReason()
Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
Definition: GlobalFunctions.php:1348
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
LockManagerGroup\singleton
static singleton( $domain=false)
Definition: LockManagerGroup.php:52
FileBackend\extensionFromPath
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
Definition: FileBackend.php:1506
FileBackendGroup\config
config( $name)
Get the config array for a backend object with a given name.
Definition: FileBackendGroup.php:180
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
php
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
FileBackendGroup\guessMimeInternal
guessMimeInternal( $storagePath, $content, $fsPath)
Definition: FileBackendGroup.php:231
FileBackendGroup\singleton
static singleton()
Definition: FileBackendGroup.php:45
FileBackendGroup\destroySingleton
static destroySingleton()
Destroy the singleton instance.
Definition: FileBackendGroup.php:57
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
$wgFileBackends
$wgFileBackends
File backend structure configuration.
Definition: DefaultSettings.php:640
MimeMagic\singleton
static singleton()
Get an instance of this class.
Definition: MimeMagic.php:33
list
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
TempFSFile\factory
static factory( $prefix, $extension='', $tmpDirectory=null)
Make a new temporary file on the file system.
Definition: TempFSFile.php:55
wfWikiID
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Definition: GlobalFunctions.php:2807
$wgDirectoryMode
$wgDirectoryMode
Default value for chmoding of new directories.
Definition: DefaultSettings.php:1486
FileBackendGroup\initFromGlobals
initFromGlobals()
Register file backends from the global variables.
Definition: FileBackendGroup.php:64
FileBackendGroup\$backends
array $backends
(name => ('class' => string, 'config' => array, 'instance' => object))
Definition: FileBackendGroup.php:37
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:2107
$ext
$ext
Definition: NoLocalSettings.php:25
as
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
FileBackendGroup\backendFromPath
backendFromPath( $storagePath)
Get an appropriate backend object from a storage path.
Definition: FileBackendGroup.php:215
LoggerFactory
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
FileBackendGroup\$instance
static FileBackendGroup $instance
Definition: FileBackendGroup.php:34
MediaWikiServices
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
FileBackendGroup\__construct
__construct()
Definition: FileBackendGroup.php:39
FileJournal\factory
static factory(array $config, $backend)
Create an appropriate FileJournal object from config.
Definition: FileJournal.php:62
$wgForeignFileRepos
$wgForeignFileRepos
Definition: DefaultSettings.php:522
array
the array() calling protocol came about after MediaWiki 1.4rc1.
ObjectCache\getLocalServerInstance
static getLocalServerInstance( $fallback=CACHE_NONE)
Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
Definition: ObjectCache.php:288
$type
$type
Definition: testCompression.php:48