MediaWiki master
ForeignResourceManager.php
Go to the documentation of this file.
1<?php
22
23use Composer\Spdx\SpdxLicenses;
24use LogicException;
27use PharData;
28use RecursiveDirectoryIterator;
29use RecursiveIteratorIterator;
30use SplFileInfo;
31use Symfony\Component\Yaml\Yaml;
32
42 private $defaultAlgo = 'sha384';
43
45 private $hasErrors = false;
46
48 private $registryFile;
49
51 private $libDir;
52
54 private $tmpParentDir;
55
57 private $cacheDir;
58
63 private $infoPrinter;
64
69 private $errorPrinter;
74 private $verbosePrinter;
75
77 private $action;
78
80 private $registry;
81
90 public function __construct(
91 $registryFile,
92 $libDir,
93 callable $infoPrinter = null,
94 callable $errorPrinter = null,
95 callable $verbosePrinter = null
96 ) {
97 $this->registryFile = $registryFile;
98 $this->libDir = $libDir;
99 $this->infoPrinter = $infoPrinter ?? static function ( $_ ) {
100 };
101 $this->errorPrinter = $errorPrinter ?? $this->infoPrinter;
102 $this->verbosePrinter = $verbosePrinter ?? static function ( $_ ) {
103 };
104
105 // Support XDG_CACHE_HOME to speed up CI by avoiding repeated downloads.
106 $conf = MediaWikiServices::getInstance()->getMainConfig();
107 if ( ( $cacheHome = getenv( 'XDG_CACHE_HOME' ) ) !== false ) {
108 $this->cacheDir = realpath( $cacheHome ) . '/mw-foreign';
109 } elseif ( ( $cacheConf = $conf->get( MainConfigNames::CacheDirectory ) ) !== false ) {
110 $this->cacheDir = "$cacheConf/ForeignResourceManager";
111 } else {
112 $this->cacheDir = "{$this->libDir}/.foreign/cache";
113 }
114 }
115
122 public function run( $action, $module ) {
123 $actions = [ 'update', 'verify', 'make-sri' ];
124 if ( !in_array( $action, $actions ) ) {
125 $this->error( "Invalid action.\n\nMust be one of " . implode( ', ', $actions ) . '.' );
126 return false;
127 }
128 $this->action = $action;
129 $this->setupTempDir( $action );
130
131 $this->registry = Yaml::parseFile( $this->registryFile );
132 if ( $module === 'all' ) {
133 $modules = $this->registry;
134 } elseif ( isset( $this->registry[$module] ) ) {
135 $modules = [ $module => $this->registry[$module] ];
136 } else {
137 $this->error( "Unknown module name.\n\nMust be one of:\n" .
138 wordwrap( implode( ', ', array_keys( $this->registry ) ), 80 ) .
139 '.'
140 );
141 return false;
142 }
143
144 foreach ( $modules as $moduleName => $info ) {
145 $this->verbose( "\n### {$moduleName}\n\n" );
146
147 if ( $this->action === 'update' ) {
148 $this->output( "... updating '{$moduleName}'\n" );
149 } elseif ( $this->action === 'verify' ) {
150 $this->output( "... verifying '{$moduleName}'\n" );
151 } else {
152 $this->output( "... checking '{$moduleName}'\n" );
153 }
154
155 // Do checks on yaml content (such as license existence, validity and type keys)
156 // before doing any potentially destructive actions (potentially deleting directories,
157 // depending on action.
158
159 if ( !isset( $info['type'] ) ) {
160 throw new LogicException( "Module '$moduleName' must have a 'type' key." );
161 }
162
163 $this->validateLicense( $moduleName, $info );
164
165 if ( $info['type'] === 'doc-only' ) {
166 $this->output( "... {$moduleName} is documentation-only, skipping integrity checks.\n" );
167 continue;
168 }
169
170 $destDir = "{$this->libDir}/$moduleName";
171
172 if ( $this->action === 'update' ) {
173 $this->verbose( "... emptying directory for $moduleName\n" );
174 wfRecursiveRemoveDir( $destDir );
175 }
176
177 $this->verbose( "... preparing {$this->tmpParentDir}\n" );
178 wfRecursiveRemoveDir( $this->tmpParentDir );
179 if ( !wfMkdirParents( $this->tmpParentDir ) ) {
180 throw new LogicException( "Unable to create {$this->tmpParentDir}" );
181 }
182
183 switch ( $info['type'] ) {
184 case 'tar':
185 case 'zip':
186 $this->handleTypeTar( $moduleName, $destDir, $info, $info['type'] );
187 break;
188 case 'file':
189 $this->handleTypeFile( $moduleName, $destDir, $info );
190 break;
191 case 'multi-file':
192 $this->handleTypeMultiFile( $moduleName, $destDir, $info );
193 break;
194 default:
195 throw new LogicException( "Unknown type '{$info['type']}' for '$moduleName'" );
196 }
197 }
198
199 $this->cleanUp();
200 if ( $this->hasErrors ) {
201 // The "verify" action should check all modules and files and fail after, not during.
202 // We don't throw on the first issue so that developers enjoy access to all actionable
203 // information at once (given we can't have cascading errors).
204 // The "verify" action prints errors along the way and simply exits here.
205 return false;
206 }
207
208 return true;
209 }
210
216 private function setupTempDir( $action ) {
217 if ( $action === 'verify' ) {
218 $this->tmpParentDir = wfTempDir() . '/ForeignResourceManager';
219 } else {
220 // Use a temporary directory under the destination directory instead
221 // of wfTempDir() because PHP's rename() does not work across file
222 // systems, and the user's /tmp and $IP may be on different filesystems.
223 $this->tmpParentDir = "{$this->libDir}/.foreign/tmp";
224 }
225 }
226
233 private function cacheKey( $src, $integrity, $moduleName ) {
234 $key = $moduleName
235 . '_' . hash( 'fnv132', $integrity )
236 . '_' . hash( 'fnv132', $src )
237 // Append readable filename to aid cache inspection and debugging
238 . '_' . basename( $src );
239 $key = preg_replace( '/[.\/+?=_-]+/', '_', $key );
240 return rtrim( $key, '_' );
241 }
242
247 private function cacheGet( $key ) {
248 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
249 return @file_get_contents( "{$this->cacheDir}/$key.data" );
250 }
251
256 private function cacheSet( $key, $data ) {
257 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
258 @mkdir( $this->cacheDir, 0777, true );
259 file_put_contents( "{$this->cacheDir}/$key.data", $data, LOCK_EX );
260 }
261
268 private function fetch( string $src, $integrity, string $moduleName ) {
269 if ( $integrity !== null ) {
270 $key = $this->cacheKey( $src, $integrity, $moduleName );
271 $data = $this->cacheGet( $key );
272 if ( $data ) {
273 return $data;
274 }
275 }
276
277 $req = MediaWikiServices::getInstance()->getHttpRequestFactory()
278 ->create( $src, [ 'method' => 'GET', 'followRedirects' => false ], __METHOD__ );
279 if ( !$req->execute()->isOK() ) {
280 throw new LogicException( "Failed to download resource at {$src}" );
281 }
282 if ( $req->getStatus() !== 200 ) {
283 throw new LogicException( "Unexpected HTTP {$req->getStatus()} response from {$src}" );
284 }
285 $data = $req->getContent();
286 $algo = $integrity === null ? $this->defaultAlgo : explode( '-', $integrity )[0];
287 $actualIntegrity = $algo . '-' . base64_encode( hash( $algo, $data, true ) );
288 if ( $integrity === $actualIntegrity ) {
289 $this->verbose( "... passed integrity check for {$src}\n" );
290 $key = $this->cacheKey( $src, $actualIntegrity, $moduleName );
291 $this->cacheSet( $key, $data );
292 } elseif ( $this->action === 'make-sri' ) {
293 $this->output( "Integrity for {$src}\n\tintegrity: {$actualIntegrity}\n" );
294 } else {
295 $expectedIntegrity = $integrity ?? 'null';
296 throw new LogicException( "Integrity check failed for {$src}\n" .
297 "\tExpected: {$expectedIntegrity}\n" .
298 "\tActual: {$actualIntegrity}"
299 );
300 }
301 return $data;
302 }
303
309 private function handleTypeFile( $moduleName, $destDir, array $info ) {
310 if ( !isset( $info['src'] ) ) {
311 throw new LogicException( "Module '$moduleName' must have a 'src' key." );
312 }
313 $data = $this->fetch( $info['src'], $info['integrity'] ?? null, $moduleName );
314 $dest = $info['dest'] ?? basename( $info['src'] );
315 $path = "$destDir/$dest";
316 if ( $this->action === 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
317 $this->error( "File for '$moduleName' is different.\n" );
318 }
319 if ( $this->action === 'update' ) {
320 wfMkdirParents( $destDir );
321 file_put_contents( "$destDir/$dest", $data );
322 }
323 }
324
330 private function handleTypeMultiFile( $moduleName, $destDir, array $info ) {
331 if ( !isset( $info['files'] ) ) {
332 throw new LogicException( "Module '$moduleName' must have a 'files' key." );
333 }
334 foreach ( $info['files'] as $dest => $file ) {
335 if ( !isset( $file['src'] ) ) {
336 throw new LogicException( "Module '$moduleName' file '$dest' must have a 'src' key." );
337 }
338 $data = $this->fetch( $file['src'], $file['integrity'] ?? null, $moduleName );
339 $path = "$destDir/$dest";
340 if ( $this->action === 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
341 $this->error( "File '$dest' for '$moduleName' is different.\n" );
342 } elseif ( $this->action === 'update' ) {
343 wfMkdirParents( $destDir );
344 file_put_contents( "$destDir/$dest", $data );
345 }
346 }
347 }
348
355 private function handleTypeTar( $moduleName, $destDir, array $info, string $fileType ) {
356 $info += [ 'src' => null, 'integrity' => null, 'dest' => null ];
357 if ( $info['src'] === null ) {
358 throw new LogicException( "Module '$moduleName' must have a 'src' key." );
359 }
360 // Download the resource to a temporary file and open it
361 $data = $this->fetch( $info['src'], $info['integrity'], $moduleName );
362 $tmpFile = "{$this->tmpParentDir}/$moduleName." . $fileType;
363 $this->verbose( "... writing '$moduleName' src to $tmpFile\n" );
364 file_put_contents( $tmpFile, $data );
365 $p = new PharData( $tmpFile );
366 $tmpDir = "{$this->tmpParentDir}/$moduleName";
367 $p->extractTo( $tmpDir );
368 unset( $data, $p );
369
370 if ( $info['dest'] === null ) {
371 // Default: Replace the entire directory
372 $toCopy = [ $tmpDir => $destDir ];
373 } else {
374 // Expand and normalise the 'dest' entries
375 $toCopy = [];
376 foreach ( $info['dest'] as $fromSubPath => $toSubPath ) {
377 // Use glob() to expand wildcards and check existence
378 $fromPaths = glob( "{$tmpDir}/{$fromSubPath}", GLOB_BRACE );
379 if ( !$fromPaths ) {
380 throw new LogicException( "Path '$fromSubPath' of '$moduleName' not found." );
381 }
382 foreach ( $fromPaths as $fromPath ) {
383 $toCopy[$fromPath] = $toSubPath === null
384 ? "$destDir/" . basename( $fromPath )
385 : "$destDir/$toSubPath/" . basename( $fromPath );
386 }
387 }
388 }
389 foreach ( $toCopy as $from => $to ) {
390 if ( $this->action === 'verify' ) {
391 $this->verbose( "... verifying $to\n" );
392 if ( is_dir( $from ) ) {
393 $rii = new RecursiveIteratorIterator( new RecursiveDirectoryIterator(
394 $from,
395 RecursiveDirectoryIterator::SKIP_DOTS
396 ) );
398 foreach ( $rii as $file ) {
399 $remote = $file->getPathname();
400 $local = strtr( $remote, [ $from => $to ] );
401 if ( sha1_file( $remote ) !== sha1_file( $local ) ) {
402 $this->error( "File '$local' is different.\n" );
403 }
404 }
405 } elseif ( sha1_file( $from ) !== sha1_file( $to ) ) {
406 $this->error( "File '$to' is different.\n" );
407 }
408 } elseif ( $this->action === 'update' ) {
409 $this->verbose( "... moving $from to $to\n" );
410 wfMkdirParents( dirname( $to ) );
411 if ( !rename( $from, $to ) ) {
412 throw new LogicException( "Could not move $from to $to." );
413 }
414 }
415 }
416 }
417
421 private function verbose( $text ) {
422 ( $this->verbosePrinter )( $text );
423 }
424
428 private function output( $text ) {
429 ( $this->infoPrinter )( $text );
430 }
431
435 private function error( $text ) {
436 $this->hasErrors = true;
437 ( $this->errorPrinter )( $text );
438 }
439
440 private function cleanUp() {
441 wfRecursiveRemoveDir( $this->tmpParentDir );
442
443 // Prune the cache of files we don't recognise.
444 $knownKeys = [];
445 foreach ( $this->registry as $module => $info ) {
446 if ( $info['type'] === 'file' || $info['type'] === 'tar' ) {
447 $knownKeys[] = $this->cacheKey( $info['src'], $info['integrity'], $module );
448 } elseif ( $info['type'] === 'multi-file' ) {
449 foreach ( $info['files'] as $file ) {
450 $knownKeys[] = $this->cacheKey( $file['src'], $file['integrity'], $module );
451 }
452 }
453 }
454 foreach ( glob( "{$this->cacheDir}/*" ) as $cacheFile ) {
455 if ( !in_array( basename( $cacheFile, '.data' ), $knownKeys ) ) {
456 unlink( $cacheFile );
457 }
458 }
459 }
460
465 private function validateLicense( $moduleName, $info ) {
466 if ( !isset( $info['license'] ) || !is_string( $info['license'] ) ) {
467 throw new LogicException(
468 "Module '$moduleName' needs a valid SPDX license; no license is currently present"
469 );
470 }
471 $licenses = new SpdxLicenses();
472 if ( !$licenses->validate( $info['license'] ) ) {
473 $this->error(
474 "Module '$moduleName' has an invalid SPDX license identifier '{$info['license']}', "
475 . "see <https://spdx.org/licenses/>.\n"
476 );
477 }
478 }
479}
480
482class_alias( ForeignResourceManager::class, 'ForeignResourceManager' );
wfTempDir()
Tries to get the system directory for temporary files.
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
A class containing constants representing the names of configuration variables.
const CacheDirectory
Name constant for the CacheDirectory setting, for use with Config::get()
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Manage foreign resources registered with ResourceLoader.
__construct( $registryFile, $libDir, callable $infoPrinter=null, callable $errorPrinter=null, callable $verbosePrinter=null)