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;
34 private $errorPrinter;
35 private $verbosePrinter;
39 * @param string $registryFile Path to YAML file
40 * @param string $libDir Path to a modules directory
41 * @param callable|null $infoPrinter Callback for printing info about the run.
42 * @param callable|null $errorPrinter Callback for printing errors from the run.
43 * @param callable|null $verbosePrinter Callback for printing extra verbose
44 * progress information from the run.
46 public function __construct(
49 callable
$infoPrinter = null,
50 callable
$errorPrinter = null,
51 callable
$verbosePrinter = null
53 $this->registryFile
= $registryFile;
54 $this->libDir
= $libDir;
55 $this->infoPrinter
= $infoPrinter ??
function () {
57 $this->errorPrinter
= $errorPrinter ??
$this->infoPrinter
;
58 $this->verbosePrinter
= $verbosePrinter ??
function () {
61 // Use a temporary directory under the destination directory instead
62 // of wfTempDir() because PHP's rename() does not work across file
63 // systems, as the user's /tmp and $IP may be on different filesystems.
64 $this->tmpParentDir
= "{$this->libDir}/.tmp";
71 public function run( $action, $module ) {
72 $actions = [ 'update', 'verify', 'make-sri' ];
73 if ( !in_array( $action, $actions ) ) {
74 $this->error( "Invalid action.\n\nMust be one of " . implode( ', ', $actions ) . '.' );
77 $this->action
= $action;
79 $registry = $this->parseBasicYaml( file_get_contents( $this->registryFile
) );
80 if ( $module === 'all' ) {
82 } elseif ( isset( $registry[ $module ] ) ) {
83 $modules = [ $module => $registry[ $module ] ];
85 $this->error( "Unknown module name.\n\nMust be one of:\n" .
86 wordwrap( implode( ', ', array_keys( $registry ) ), 80 ) .
92 foreach ( $modules as $moduleName => $info ) {
93 $this->verbose( "\n### {$moduleName}\n\n" );
94 $destDir = "{$this->libDir}/$moduleName";
96 if ( $this->action
=== 'update' ) {
97 $this->output( "... updating '{$moduleName}'\n" );
98 $this->verbose( "... emptying directory for $moduleName\n" );
99 wfRecursiveRemoveDir( $destDir );
100 } elseif ( $this->action
=== 'verify' ) {
101 $this->output( "... verifying '{$moduleName}'\n" );
103 $this->output( "... checking '{$moduleName}'\n" );
106 $this->verbose( "... preparing {$this->tmpParentDir}\n" );
107 wfRecursiveRemoveDir( $this->tmpParentDir
);
108 if ( !wfMkdirParents( $this->tmpParentDir
) ) {
109 throw new Exception( "Unable to create {$this->tmpParentDir}" );
112 if ( !isset( $info['type'] ) ) {
113 throw new Exception( "Module '$moduleName' must have a 'type' key." );
115 switch ( $info['type'] ) {
117 $this->handleTypeTar( $moduleName, $destDir, $info );
120 $this->handleTypeFile( $moduleName, $destDir, $info );
123 $this->handleTypeMultiFile( $moduleName, $destDir, $info );
126 throw new Exception( "Unknown type '{$info['type']}' for '$moduleName'" );
131 $this->output( "\nDone!\n" );
132 if ( $this->hasErrors
) {
133 // The verify mode should check all modules/files and fail after, not during.
140 private function fetch( $src, $integrity ) {
141 $req = MWHttpRequest
::factory( $src, [ 'method' => 'GET', 'followRedirects' => false ] );
142 if ( !$req->execute()->isOK() ) {
143 throw new Exception( "Failed to download resource at {$src}" );
145 if ( $req->getStatus() !== 200 ) {
146 throw new Exception( "Unexpected HTTP {$req->getStatus()} response from {$src}" );
148 $data = $req->getContent();
149 $algo = $integrity === null ?
$this->defaultAlgo
: explode( '-', $integrity )[0];
150 $actualIntegrity = $algo . '-' . base64_encode( hash( $algo, $data, true ) );
151 if ( $integrity === $actualIntegrity ) {
152 $this->verbose( "... passed integrity check for {$src}\n" );
154 if ( $this->action
=== 'make-sri' ) {
155 $this->output( "Integrity for {$src}\n\tintegrity: ${actualIntegrity}\n" );
157 throw new Exception( "Integrity check failed for {$src}\n" .
158 "\tExpected: {$integrity}\n" .
159 "\tActual: {$actualIntegrity}"
166 private function handleTypeFile( $moduleName, $destDir, array $info ) {
167 if ( !isset( $info['src'] ) ) {
168 throw new Exception( "Module '$moduleName' must have a 'src' key." );
170 $data = $this->fetch( $info['src'], $info['integrity'] ??
null );
171 $dest = $info['dest'] ??
basename( $info['src'] );
172 $path = "$destDir/$dest";
173 if ( $this->action
=== 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
174 throw new Exception( "File for '$moduleName' is different." );
176 if ( $this->action
=== 'update' ) {
177 wfMkdirParents( $destDir );
178 file_put_contents( "$destDir/$dest", $data );
182 private function handleTypeMultiFile( $moduleName, $destDir, array $info ) {
183 if ( !isset( $info['files'] ) ) {
184 throw new Exception( "Module '$moduleName' must have a 'files' key." );
186 foreach ( $info['files'] as $dest => $file ) {
187 if ( !isset( $file['src'] ) ) {
188 throw new Exception( "Module '$moduleName' file '$dest' must have a 'src' key." );
190 $data = $this->fetch( $file['src'], $file['integrity'] ??
null );
191 $path = "$destDir/$dest";
192 if ( $this->action
=== 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
193 throw new Exception( "File '$dest' for '$moduleName' is different." );
194 } elseif ( $this->action
=== 'update' ) {
195 wfMkdirParents( $destDir );
196 file_put_contents( "$destDir/$dest", $data );
201 private function handleTypeTar( $moduleName, $destDir, array $info ) {
202 $info +
= [ 'src' => null, 'integrity' => null, 'dest' => null ];
203 if ( $info['src'] === null ) {
204 throw new Exception( "Module '$moduleName' must have a 'src' key." );
206 // Download the resource to a temporary file and open it
207 $data = $this->fetch( $info['src'], $info['integrity' ] );
208 $tmpFile = "{$this->tmpParentDir}/$moduleName.tar";
209 $this->verbose( "... writing '$moduleName' src to $tmpFile\n" );
210 file_put_contents( $tmpFile, $data );
211 $p = new PharData( $tmpFile );
212 $tmpDir = "{$this->tmpParentDir}/$moduleName";
213 $p->extractTo( $tmpDir );
216 if ( $info['dest'] === null ) {
217 // Default: Replace the entire directory
218 $toCopy = [ $tmpDir => $destDir ];
220 // Expand and normalise the 'dest' entries
222 foreach ( $info['dest'] as $fromSubPath => $toSubPath ) {
223 // Use glob() to expand wildcards and check existence
224 $fromPaths = glob( "{$tmpDir}/{$fromSubPath}", GLOB_BRACE
);
226 throw new Exception( "Path '$fromSubPath' of '$moduleName' not found." );
228 foreach ( $fromPaths as $fromPath ) {
229 $toCopy[$fromPath] = $toSubPath === null
230 ?
"$destDir/" . basename( $fromPath )
231 : "$destDir/$toSubPath/" . basename( $fromPath );
235 foreach ( $toCopy as $from => $to ) {
236 if ( $this->action
=== 'verify' ) {
237 $this->verbose( "... verifying $to\n" );
238 if ( is_dir( $from ) ) {
239 $rii = new RecursiveIteratorIterator( new RecursiveDirectoryIterator(
241 RecursiveDirectoryIterator
::SKIP_DOTS
243 /** @var SplFileInfo $file */
244 foreach ( $rii as $file ) {
245 $remote = $file->getPathname();
246 $local = strtr( $remote, [ $from => $to ] );
247 if ( sha1_file( $remote ) !== sha1_file( $local ) ) {
248 $this->error( "File '$local' is different." );
249 $this->hasErrors
= true;
252 } elseif ( sha1_file( $from ) !== sha1_file( $to ) ) {
253 $this->error( "File '$to' is different." );
254 $this->hasErrors
= true;
256 } elseif ( $this->action
=== 'update' ) {
257 $this->verbose( "... moving $from to $to\n" );
258 wfMkdirParents( dirname( $to ) );
259 if ( !rename( $from, $to ) ) {
260 throw new Exception( "Could not move $from to $to." );
266 private function verbose( $text ) {
267 ( $this->verbosePrinter
)( $text );
270 private function output( $text ) {
271 ( $this->infoPrinter
)( $text );
274 private function error( $text ) {
275 ( $this->errorPrinter
)( $text );
278 private function cleanUp() {
279 wfRecursiveRemoveDir( $this->tmpParentDir
);
285 * Supports only string or object values, and 2 spaces indentation.
287 * @todo Just ship symfony/yaml.
288 * @param string $input
291 private function parseBasicYaml( $input ) {
292 $lines = explode( "\n", $input );
296 foreach ( $lines as $i => $text ) {
298 $trimmed = ltrim( $text, ' ' );
299 if ( $trimmed === '' ||
$trimmed[0] === '#' ) {
302 $indent = strlen( $text ) - strlen( $trimmed );
303 if ( $indent %
2 !== 0 ) {
304 throw new Exception( __METHOD__
. ": Odd indentation on line $line." );
306 $depth = $indent === 0 ?
0 : ( $indent / 2 );
307 if ( $depth < $prev ) {
308 // Close previous branches we can't re-enter
309 array_splice( $stack, $depth +
1 );
311 if ( !array_key_exists( $depth, $stack ) ) {
312 throw new Exception( __METHOD__
. ": Too much indentation on line $line." );
314 if ( strpos( $trimmed, ':' ) === false ) {
315 throw new Exception( __METHOD__
. ": Missing colon on line $line." );
317 $dest =& $stack[ $depth ];
318 if ( $dest === null ) {
319 // Promote from null to object
322 list( $key, $val ) = explode( ':', $trimmed, 2 );
323 $val = ltrim( $val, ' ' );
326 $dest[ $key ] = $val;
328 // Add null (may become an object later)
331 $dest[ $key ] = &$val;
334 unset( $dest, $val );