d9e5a540e2154eefc65158f0c4068e8a61a56e4b
[lhc/web/wiklou.git] / includes / filebackend / FileBackendGroup.php
1 <?php
2 /**
3 * File backend registration handling.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup FileBackend
22 * @author Aaron Schulz
23 */
24 use \MediaWiki\Logger\LoggerFactory;
25
26 /**
27 * Class to handle file backend registration
28 *
29 * @ingroup FileBackend
30 * @since 1.19
31 */
32 class FileBackendGroup {
33 /** @var FileBackendGroup */
34 protected static $instance = null;
35
36 /** @var array (name => ('class' => string, 'config' => array, 'instance' => object)) */
37 protected $backends = [];
38
39 protected function __construct() {
40 }
41
42 /**
43 * @return FileBackendGroup
44 */
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
54 /**
55 * Destroy the singleton instance
56 */
57 public static function destroySingleton() {
58 self::$instance = null;
59 }
60
61 /**
62 * Register file backends from the global variables
63 */
64 protected function initFromGlobals() {
65 global $wgLocalFileRepo, $wgForeignFileRepos, $wgFileBackends;
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 $fileMode = isset( $info['fileMode'] )
91 ? $info['fileMode']
92 : 0644;
93 // Get the FS backend configuration
94 $autoBackends[] = [
95 'name' => $backendName,
96 'class' => 'FSFileBackend',
97 'lockManager' => 'fsLockManager',
98 'containerPaths' => [
99 "{$repoName}-public" => "{$directory}",
100 "{$repoName}-thumb" => $thumbDir,
101 "{$repoName}-transcoded" => $transcodedDir,
102 "{$repoName}-deleted" => $deletedDir,
103 "{$repoName}-temp" => "{$directory}/temp"
104 ],
105 'fileMode' => $fileMode,
106 ];
107 }
108
109 // Register implicitly defined backends
110 $this->register( $autoBackends, wfConfiguredReadOnlyReason() );
111 }
112
113 /**
114 * Register an array of file backend configurations
115 *
116 * @param array $configs
117 * @param string|null $readOnlyReason
118 * @throws InvalidArgumentException
119 */
120 protected function register( array $configs, $readOnlyReason = null ) {
121 foreach ( $configs as $config ) {
122 if ( !isset( $config['name'] ) ) {
123 throw new InvalidArgumentException( "Cannot register a backend with no name." );
124 }
125 $name = $config['name'];
126 if ( isset( $this->backends[$name] ) ) {
127 throw new LogicException( "Backend with name `{$name}` already registered." );
128 } elseif ( !isset( $config['class'] ) ) {
129 throw new InvalidArgumentException( "Backend with name `{$name}` has no class." );
130 }
131 $class = $config['class'];
132
133 $config['readOnly'] = !empty( $config['readOnly'] )
134 ? $config['readOnly']
135 : $readOnlyReason;
136
137 unset( $config['class'] ); // backend won't need this
138 $this->backends[$name] = [
139 'class' => $class,
140 'config' => $config,
141 'instance' => null
142 ];
143 }
144 }
145
146 /**
147 * Get the backend object with a given name
148 *
149 * @param string $name
150 * @return FileBackend
151 * @throws InvalidArgumentException
152 */
153 public function get( $name ) {
154 if ( !isset( $this->backends[$name] ) ) {
155 throw new InvalidArgumentException( "No backend defined with the name `$name`." );
156 }
157 // Lazy-load the actual backend instance
158 if ( !isset( $this->backends[$name]['instance'] ) ) {
159 $class = $this->backends[$name]['class'];
160 $config = $this->backends[$name]['config'];
161 $config['wikiId'] = isset( $config['wikiId'] )
162 ? $config['wikiId']
163 : wfWikiID(); // e.g. "my_wiki-en_"
164 $config['lockManager'] =
165 LockManagerGroup::singleton( $config['wikiId'] )->get( $config['lockManager'] );
166 $config['fileJournal'] = isset( $config['fileJournal'] )
167 ? FileJournal::factory( $config['fileJournal'], $name )
168 : FileJournal::factory( [ 'class' => 'NullFileJournal' ], $name );
169 $config['wanCache'] = ObjectCache::getMainWANInstance();
170 $config['mimeCallback'] = [ $this, 'guessMimeInternal' ];
171 $config['statusWrapper'] = [ 'Status', 'wrap' ];
172 $config['tmpDirectory'] = wfTempDir();
173 $config['logger'] = LoggerFactory::getInstance( 'FileOperation' );
174 $config['profiler'] = Profiler::instance();
175
176 $this->backends[$name]['instance'] = new $class( $config );
177 }
178
179 return $this->backends[$name]['instance'];
180 }
181
182 /**
183 * Get the config array for a backend object with a given name
184 *
185 * @param string $name
186 * @return array
187 * @throws InvalidArgumentException
188 */
189 public function config( $name ) {
190 if ( !isset( $this->backends[$name] ) ) {
191 throw new InvalidArgumentException( "No backend defined with the name `$name`." );
192 }
193 $class = $this->backends[$name]['class'];
194
195 return [ 'class' => $class ] + $this->backends[$name]['config'];
196 }
197
198 /**
199 * Get an appropriate backend object from a storage path
200 *
201 * @param string $storagePath
202 * @return FileBackend|null Backend or null on failure
203 */
204 public function backendFromPath( $storagePath ) {
205 list( $backend, , ) = FileBackend::splitStoragePath( $storagePath );
206 if ( $backend !== null && isset( $this->backends[$backend] ) ) {
207 return $this->get( $backend );
208 }
209
210 return null;
211 }
212
213 /**
214 * @param string $storagePath
215 * @param string|null $content
216 * @param string|null $fsPath
217 * @return string
218 * @since 1.27
219 */
220 public function guessMimeInternal( $storagePath, $content, $fsPath ) {
221 $magic = MimeMagic::singleton();
222 // Trust the extension of the storage path (caller must validate)
223 $ext = FileBackend::extensionFromPath( $storagePath );
224 $type = $magic->guessTypesForExtension( $ext );
225 // For files without a valid extension (or one at all), inspect the contents
226 if ( !$type && $fsPath ) {
227 $type = $magic->guessMimeType( $fsPath, false );
228 } elseif ( !$type && strlen( $content ) ) {
229 $tmpFile = TempFSFile::factory( 'mime_', '', wfTempDir() );
230 file_put_contents( $tmpFile->getPath(), $content );
231 $type = $magic->guessMimeType( $tmpFile->getPath(), false );
232 }
233 return $type ?: 'unknown/unknown';
234 }
235 }