3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @ingroup Maintenance
23 * Manage foreign resources registered with ResourceLoader.
27 class ForeignResourceManager
{
28 private $defaultAlgo = 'sha384';
29 private $hasErrors = false;
30 private $registryFile;
32 private $tmpParentDir;
35 private $errorPrinter;
36 private $verbosePrinter;
41 * @param string $registryFile Path to YAML file
42 * @param string $libDir Path to a modules directory
43 * @param callable|null $infoPrinter Callback for printing info about the run.
44 * @param callable|null $errorPrinter Callback for printing errors from the run.
45 * @param callable|null $verbosePrinter Callback for printing extra verbose
46 * progress information from the run.
48 public function __construct(
51 callable
$infoPrinter = null,
52 callable
$errorPrinter = null,
53 callable
$verbosePrinter = null
55 $this->registryFile
= $registryFile;
56 $this->libDir
= $libDir;
57 $this->infoPrinter
= $infoPrinter ??
function () {
59 $this->errorPrinter
= $errorPrinter ??
$this->infoPrinter
;
60 $this->verbosePrinter
= $verbosePrinter ??
function () {
63 // Use a temporary directory under the destination directory instead
64 // of wfTempDir() because PHP's rename() does not work across file
65 // systems, and the user's /tmp and $IP may be on different filesystems.
66 $this->tmpParentDir
= "{$this->libDir}/.foreign/tmp";
68 $cacheHome = getenv( 'XDG_CACHE_HOME' ) ?
realpath( getenv( 'XDG_CACHE_HOME' ) ) : false;
69 $this->cacheDir
= $cacheHome ?
"$cacheHome/mw-foreign" : "{$this->libDir}/.foreign/cache";
76 public function run( $action, $module ) {
77 $actions = [ 'update', 'verify', 'make-sri' ];
78 if ( !in_array( $action, $actions ) ) {
79 $this->error( "Invalid action.\n\nMust be one of " . implode( ', ', $actions ) . '.' );
82 $this->action
= $action;
84 $this->registry
= $this->parseBasicYaml( file_get_contents( $this->registryFile
) );
85 if ( $module === 'all' ) {
86 $modules = $this->registry
;
87 } elseif ( isset( $this->registry
[ $module ] ) ) {
88 $modules = [ $module => $this->registry
[ $module ] ];
90 $this->error( "Unknown module name.\n\nMust be one of:\n" .
91 wordwrap( implode( ', ', array_keys( $this->registry
) ), 80 ) .
97 foreach ( $modules as $moduleName => $info ) {
98 $this->verbose( "\n### {$moduleName}\n\n" );
99 $destDir = "{$this->libDir}/$moduleName";
101 if ( $this->action
=== 'update' ) {
102 $this->output( "... updating '{$moduleName}'\n" );
103 $this->verbose( "... emptying directory for $moduleName\n" );
104 wfRecursiveRemoveDir( $destDir );
105 } elseif ( $this->action
=== 'verify' ) {
106 $this->output( "... verifying '{$moduleName}'\n" );
108 $this->output( "... checking '{$moduleName}'\n" );
111 $this->verbose( "... preparing {$this->tmpParentDir}\n" );
112 wfRecursiveRemoveDir( $this->tmpParentDir
);
113 if ( !wfMkdirParents( $this->tmpParentDir
) ) {
114 throw new Exception( "Unable to create {$this->tmpParentDir}" );
117 if ( !isset( $info['type'] ) ) {
118 throw new Exception( "Module '$moduleName' must have a 'type' key." );
120 switch ( $info['type'] ) {
122 $this->handleTypeTar( $moduleName, $destDir, $info );
125 $this->handleTypeFile( $moduleName, $destDir, $info );
128 $this->handleTypeMultiFile( $moduleName, $destDir, $info );
131 throw new Exception( "Unknown type '{$info['type']}' for '$moduleName'" );
135 $this->output( "\nDone!\n" );
137 if ( $this->hasErrors
) {
138 // The verify mode should check all modules/files and fail after, not during.
145 private function cacheKey( $src, $integrity ) {
146 $key = basename( $src ) . '_' . substr( $integrity, -12 );
147 $key = preg_replace( '/[.\/+?=_-]+/', '_', $key );
148 return rtrim( $key, '_' );
151 /** @return string|false */
152 private function cacheGet( $key ) {
153 return Wikimedia\
quietCall( 'file_get_contents', "{$this->cacheDir}/$key.data" );
156 private function cacheSet( $key, $data ) {
157 wfMkdirParents( $this->cacheDir
);
158 file_put_contents( "{$this->cacheDir}/$key.data", $data, LOCK_EX
);
161 private function fetch( $src, $integrity ) {
162 $key = $this->cacheKey( $src, $integrity );
163 $data = $this->cacheGet( $key );
168 $req = MWHttpRequest
::factory( $src, [ 'method' => 'GET', 'followRedirects' => false ] );
169 if ( !$req->execute()->isOK() ) {
170 throw new Exception( "Failed to download resource at {$src}" );
172 if ( $req->getStatus() !== 200 ) {
173 throw new Exception( "Unexpected HTTP {$req->getStatus()} response from {$src}" );
175 $data = $req->getContent();
176 $algo = $integrity === null ?
$this->defaultAlgo
: explode( '-', $integrity )[0];
177 $actualIntegrity = $algo . '-' . base64_encode( hash( $algo, $data, true ) );
178 if ( $integrity === $actualIntegrity ) {
179 $this->verbose( "... passed integrity check for {$src}\n" );
180 $this->cacheSet( $key, $data );
182 if ( $this->action
=== 'make-sri' ) {
183 $this->output( "Integrity for {$src}\n\tintegrity: ${actualIntegrity}\n" );
185 throw new Exception( "Integrity check failed for {$src}\n" .
186 "\tExpected: {$integrity}\n" .
187 "\tActual: {$actualIntegrity}"
194 private function handleTypeFile( $moduleName, $destDir, array $info ) {
195 if ( !isset( $info['src'] ) ) {
196 throw new Exception( "Module '$moduleName' must have a 'src' key." );
198 $data = $this->fetch( $info['src'], $info['integrity'] ??
null );
199 $dest = $info['dest'] ??
basename( $info['src'] );
200 $path = "$destDir/$dest";
201 if ( $this->action
=== 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
202 throw new Exception( "File for '$moduleName' is different." );
204 if ( $this->action
=== 'update' ) {
205 wfMkdirParents( $destDir );
206 file_put_contents( "$destDir/$dest", $data );
210 private function handleTypeMultiFile( $moduleName, $destDir, array $info ) {
211 if ( !isset( $info['files'] ) ) {
212 throw new Exception( "Module '$moduleName' must have a 'files' key." );
214 foreach ( $info['files'] as $dest => $file ) {
215 if ( !isset( $file['src'] ) ) {
216 throw new Exception( "Module '$moduleName' file '$dest' must have a 'src' key." );
218 $data = $this->fetch( $file['src'], $file['integrity'] ??
null );
219 $path = "$destDir/$dest";
220 if ( $this->action
=== 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
221 throw new Exception( "File '$dest' for '$moduleName' is different." );
222 } elseif ( $this->action
=== 'update' ) {
223 wfMkdirParents( $destDir );
224 file_put_contents( "$destDir/$dest", $data );
229 private function handleTypeTar( $moduleName, $destDir, array $info ) {
230 $info +
= [ 'src' => null, 'integrity' => null, 'dest' => null ];
231 if ( $info['src'] === null ) {
232 throw new Exception( "Module '$moduleName' must have a 'src' key." );
234 // Download the resource to a temporary file and open it
235 $data = $this->fetch( $info['src'], $info['integrity' ] );
236 $tmpFile = "{$this->tmpParentDir}/$moduleName.tar";
237 $this->verbose( "... writing '$moduleName' src to $tmpFile\n" );
238 file_put_contents( $tmpFile, $data );
239 $p = new PharData( $tmpFile );
240 $tmpDir = "{$this->tmpParentDir}/$moduleName";
241 $p->extractTo( $tmpDir );
244 if ( $info['dest'] === null ) {
245 // Default: Replace the entire directory
246 $toCopy = [ $tmpDir => $destDir ];
248 // Expand and normalise the 'dest' entries
250 foreach ( $info['dest'] as $fromSubPath => $toSubPath ) {
251 // Use glob() to expand wildcards and check existence
252 $fromPaths = glob( "{$tmpDir}/{$fromSubPath}", GLOB_BRACE
);
254 throw new Exception( "Path '$fromSubPath' of '$moduleName' not found." );
256 foreach ( $fromPaths as $fromPath ) {
257 $toCopy[$fromPath] = $toSubPath === null
258 ?
"$destDir/" . basename( $fromPath )
259 : "$destDir/$toSubPath/" . basename( $fromPath );
263 foreach ( $toCopy as $from => $to ) {
264 if ( $this->action
=== 'verify' ) {
265 $this->verbose( "... verifying $to\n" );
266 if ( is_dir( $from ) ) {
267 $rii = new RecursiveIteratorIterator( new RecursiveDirectoryIterator(
269 RecursiveDirectoryIterator
::SKIP_DOTS
271 /** @var SplFileInfo $file */
272 foreach ( $rii as $file ) {
273 $remote = $file->getPathname();
274 $local = strtr( $remote, [ $from => $to ] );
275 if ( sha1_file( $remote ) !== sha1_file( $local ) ) {
276 $this->error( "File '$local' is different." );
277 $this->hasErrors
= true;
280 } elseif ( sha1_file( $from ) !== sha1_file( $to ) ) {
281 $this->error( "File '$to' is different." );
282 $this->hasErrors
= true;
284 } elseif ( $this->action
=== 'update' ) {
285 $this->verbose( "... moving $from to $to\n" );
286 wfMkdirParents( dirname( $to ) );
287 if ( !rename( $from, $to ) ) {
288 throw new Exception( "Could not move $from to $to." );
294 private function verbose( $text ) {
295 ( $this->verbosePrinter
)( $text );
298 private function output( $text ) {
299 ( $this->infoPrinter
)( $text );
302 private function error( $text ) {
303 ( $this->errorPrinter
)( $text );
306 private function cleanUp() {
307 wfRecursiveRemoveDir( $this->tmpParentDir
);
309 // Prune the cache of files we don't recognise.
311 foreach ( $this->registry
as $info ) {
312 if ( $info['type'] === 'file' ||
$info['type'] === 'tar' ) {
313 $knownKeys[] = $this->cacheKey( $info['src'], $info['integrity'] );
314 } elseif ( $info['type'] === 'multi-file' ) {
315 foreach ( $info['files'] as $file ) {
316 $knownKeys[] = $this->cacheKey( $file['src'], $file['integrity'] );
320 foreach ( glob( "{$this->cacheDir}/*" ) as $cacheFile ) {
321 if ( !in_array( basename( $cacheFile, '.data' ), $knownKeys ) ) {
322 unlink( $cacheFile );
330 * Supports only string or object values, and 2 spaces indentation.
332 * @todo Just ship symfony/yaml.
333 * @param string $input
336 private function parseBasicYaml( $input ) {
337 $lines = explode( "\n", $input );
341 foreach ( $lines as $i => $text ) {
343 $trimmed = ltrim( $text, ' ' );
344 if ( $trimmed === '' ||
$trimmed[0] === '#' ) {
347 $indent = strlen( $text ) - strlen( $trimmed );
348 if ( $indent %
2 !== 0 ) {
349 throw new Exception( __METHOD__
. ": Odd indentation on line $line." );
351 $depth = $indent === 0 ?
0 : ( $indent / 2 );
352 if ( $depth < $prev ) {
353 // Close previous branches we can't re-enter
354 array_splice( $stack, $depth +
1 );
356 if ( !array_key_exists( $depth, $stack ) ) {
357 throw new Exception( __METHOD__
. ": Too much indentation on line $line." );
359 if ( strpos( $trimmed, ':' ) === false ) {
360 throw new Exception( __METHOD__
. ": Missing colon on line $line." );
362 $dest =& $stack[ $depth ];
363 if ( $dest === null ) {
364 // Promote from null to object
367 list( $key, $val ) = explode( ':', $trimmed, 2 );
368 $val = ltrim( $val, ' ' );
371 $dest[ $key ] = $val;
373 // Add null (may become an object later)
376 $dest[ $key ] = &$val;
379 unset( $dest, $val );