MediaWiki  1.29.2
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 = isset( $info['deletedDir'] )
83  ? $info['deletedDir']
84  : false; // deletion disabled
85  $thumbDir = isset( $info['thumbDir'] )
86  ? $info['thumbDir']
87  : "{$directory}/thumb";
88  $transcodedDir = isset( $info['transcodedDir'] )
89  ? $info['transcodedDir']
90  : "{$directory}/transcoded";
91  // Get the FS backend configuration
92  $autoBackends[] = [
93  'name' => $backendName,
94  'class' => 'FSFileBackend',
95  'lockManager' => 'fsLockManager',
96  'containerPaths' => [
97  "{$repoName}-public" => "{$directory}",
98  "{$repoName}-thumb" => $thumbDir,
99  "{$repoName}-transcoded" => $transcodedDir,
100  "{$repoName}-deleted" => $deletedDir,
101  "{$repoName}-temp" => "{$directory}/temp"
102  ],
103  'fileMode' => isset( $info['fileMode'] ) ? $info['fileMode'] : 0644,
104  'directoryMode' => $wgDirectoryMode,
105  ];
106  }
107 
108  // Register implicitly defined backends
109  $this->register( $autoBackends, wfConfiguredReadOnlyReason() );
110  }
111 
119  protected function register( array $configs, $readOnlyReason = null ) {
120  foreach ( $configs as $config ) {
121  if ( !isset( $config['name'] ) ) {
122  throw new InvalidArgumentException( "Cannot register a backend with no name." );
123  }
124  $name = $config['name'];
125  if ( isset( $this->backends[$name] ) ) {
126  throw new LogicException( "Backend with name `{$name}` already registered." );
127  } elseif ( !isset( $config['class'] ) ) {
128  throw new InvalidArgumentException( "Backend with name `{$name}` has no class." );
129  }
130  $class = $config['class'];
131 
132  $config['readOnly'] = !empty( $config['readOnly'] )
133  ? $config['readOnly']
134  : $readOnlyReason;
135 
136  unset( $config['class'] ); // backend won't need this
137  $this->backends[$name] = [
138  'class' => $class,
139  'config' => $config,
140  'instance' => null
141  ];
142  }
143  }
144 
152  public function get( $name ) {
153  // Lazy-load the actual backend instance
154  if ( !isset( $this->backends[$name]['instance'] ) ) {
155  $config = $this->config( $name );
156 
157  $class = $config['class'];
158  if ( $class === 'FileBackendMultiWrite' ) {
159  foreach ( $config['backends'] as $index => $beConfig ) {
160  if ( isset( $beConfig['template'] ) ) {
161  // Config is just a modified version of a registered backend's.
162  // This should only be used when that config is used only by this backend.
163  $config['backends'][$index] += $this->config( $beConfig['template'] );
164  }
165  }
166  }
167 
168  $this->backends[$name]['instance'] = new $class( $config );
169  }
170 
171  return $this->backends[$name]['instance'];
172  }
173 
181  public function config( $name ) {
182  if ( !isset( $this->backends[$name] ) ) {
183  throw new InvalidArgumentException( "No backend defined with the name `$name`." );
184  }
185  $class = $this->backends[$name]['class'];
186 
187  $config = $this->backends[$name]['config'];
188  $config['class'] = $class;
189  $config += [ // set defaults
190  'wikiId' => wfWikiID(), // e.g. "my_wiki-en_"
191  'mimeCallback' => [ $this, 'guessMimeInternal' ],
192  'obResetFunc' => 'wfResetOutputBuffers',
193  'streamMimeFunc' => [ 'StreamFile', 'contentTypeFromPath' ],
194  'tmpDirectory' => wfTempDir(),
195  'statusWrapper' => [ 'Status', 'wrap' ],
196  'wanCache' => MediaWikiServices::getInstance()->getMainWANObjectCache(),
197  'srvCache' => ObjectCache::getLocalServerInstance( 'hash' ),
198  'logger' => LoggerFactory::getInstance( 'FileOperation' ),
199  'profiler' => Profiler::instance()
200  ];
201  $config['lockManager'] =
202  LockManagerGroup::singleton( $config['wikiId'] )->get( $config['lockManager'] );
203  $config['fileJournal'] = isset( $config['fileJournal'] )
204  ? FileJournal::factory( $config['fileJournal'], $name )
205  : FileJournal::factory( [ 'class' => 'NullFileJournal' ], $name );
206 
207  return $config;
208  }
209 
216  public function backendFromPath( $storagePath ) {
217  list( $backend, , ) = FileBackend::splitStoragePath( $storagePath );
218  if ( $backend !== null && isset( $this->backends[$backend] ) ) {
219  return $this->get( $backend );
220  }
221 
222  return null;
223  }
224 
232  public function guessMimeInternal( $storagePath, $content, $fsPath ) {
233  $magic = MimeMagic::singleton();
234  // Trust the extension of the storage path (caller must validate)
235  $ext = FileBackend::extensionFromPath( $storagePath );
236  $type = $magic->guessTypesForExtension( $ext );
237  // For files without a valid extension (or one at all), inspect the contents
238  if ( !$type && $fsPath ) {
239  $type = $magic->guessMimeType( $fsPath, false );
240  } elseif ( !$type && strlen( $content ) ) {
241  $tmpFile = TempFSFile::factory( 'mime_', '', wfTempDir() );
242  file_put_contents( $tmpFile->getPath(), $content );
243  $type = $magic->guessMimeType( $tmpFile->getPath(), false );
244  }
245  return $type ?: 'unknown/unknown';
246  }
247 }
FileBackend\splitStoragePath
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
Definition: FileBackend.php:1448
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
FileBackendGroup
Class to handle file backend registration.
Definition: FileBackendGroup.php:33
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:1301
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:53
FileBackend\extensionFromPath
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
Definition: FileBackend.php:1507
FileBackendGroup\config
config( $name)
Get the config array for a backend object with a given name.
Definition: FileBackendGroup.php:181
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304
$type
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2536
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:232
FileBackendGroup\singleton
static singleton()
Definition: FileBackendGroup.php:46
FileBackendGroup\destroySingleton
static destroySingleton()
Destroy the singleton instance.
Definition: FileBackendGroup.php:58
$content
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition: hooks.txt:1049
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:3011
$wgDirectoryMode
$wgDirectoryMode
Default value for chmoding of new directories.
Definition: DefaultSettings.php:1471
FileBackendGroup\initFromGlobals
initFromGlobals()
Register file backends from the global variables.
Definition: FileBackendGroup.php:65
FileBackendGroup\$backends
array $backends
(name => ('class' => string, 'config' => array, 'instance' => object))
Definition: FileBackendGroup.php:38
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:2061
$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:216
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:35
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:40
FileJournal\factory
static factory(array $config, $backend)
Create an appropriate FileJournal object from config.
Definition: FileJournal.php:63
$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