Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / filebackend / FileBackendGroup.php
blobe65a5945ff9bfc6e654abc52cdf68c3e23392d19
1 <?php
2 /**
3 * File backend registration handling.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup FileBackend
22 * @author Aaron Schulz
24 use \MediaWiki\Logger\LoggerFactory;
25 use MediaWiki\MediaWikiServices;
27 /**
28 * Class to handle file backend registration
30 * @ingroup FileBackend
31 * @since 1.19
33 class FileBackendGroup {
34 /** @var FileBackendGroup */
35 protected static $instance = null;
37 /** @var array (name => ('class' => string, 'config' => array, 'instance' => object)) */
38 protected $backends = [];
40 protected function __construct() {
43 /**
44 * @return FileBackendGroup
46 public static function singleton() {
47 if ( self::$instance == null ) {
48 self::$instance = new self();
49 self::$instance->initFromGlobals();
52 return self::$instance;
55 /**
56 * Destroy the singleton instance
58 public static function destroySingleton() {
59 self::$instance = null;
62 /**
63 * Register file backends from the global variables
65 protected function initFromGlobals() {
66 global $wgLocalFileRepo, $wgForeignFileRepos, $wgFileBackends, $wgDirectoryMode;
68 // Register explicitly defined backends
69 $this->register( $wgFileBackends, wfConfiguredReadOnlyReason() );
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)
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"
103 'fileMode' => isset( $info['fileMode'] ) ? $info['fileMode'] : 0644,
104 'directoryMode' => $wgDirectoryMode,
108 // Register implicitly defined backends
109 $this->register( $autoBackends, wfConfiguredReadOnlyReason() );
113 * Register an array of file backend configurations
115 * @param array $configs
116 * @param string|null $readOnlyReason
117 * @throws InvalidArgumentException
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." );
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." );
130 $class = $config['class'];
132 $config['readOnly'] = !empty( $config['readOnly'] )
133 ? $config['readOnly']
134 : $readOnlyReason;
136 unset( $config['class'] ); // backend won't need this
137 $this->backends[$name] = [
138 'class' => $class,
139 'config' => $config,
140 'instance' => null
146 * Get the backend object with a given name
148 * @param string $name
149 * @return FileBackend
150 * @throws InvalidArgumentException
152 public function get( $name ) {
153 // Lazy-load the actual backend instance
154 if ( !isset( $this->backends[$name]['instance'] ) ) {
155 $config = $this->config( $name );
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'] );
168 $this->backends[$name]['instance'] = new $class( $config );
171 return $this->backends[$name]['instance'];
175 * Get the config array for a backend object with a given name
177 * @param string $name
178 * @return array Parameters to FileBackend::__construct()
179 * @throws InvalidArgumentException
181 public function config( $name ) {
182 if ( !isset( $this->backends[$name] ) ) {
183 throw new InvalidArgumentException( "No backend defined with the name `$name`." );
185 $class = $this->backends[$name]['class'];
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()
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 );
207 return $config;
211 * Get an appropriate backend object from a storage path
213 * @param string $storagePath
214 * @return FileBackend|null Backend or null on failure
216 public function backendFromPath( $storagePath ) {
217 list( $backend, , ) = FileBackend::splitStoragePath( $storagePath );
218 if ( $backend !== null && isset( $this->backends[$backend] ) ) {
219 return $this->get( $backend );
222 return null;
226 * @param string $storagePath
227 * @param string|null $content
228 * @param string|null $fsPath
229 * @return string
230 * @since 1.27
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 );
245 return $type ?: 'unknown/unknown';