MediaWiki REL1_32
manageForeignResources.php
Go to the documentation of this file.
1<?php
22require_once __DIR__ . '/../Maintenance.php';
23
31 private $defaultAlgo = 'sha384';
33 private $action;
34 private $failAfterOutput = false;
35
36 public function __construct() {
37 global $IP;
38 parent::__construct();
39 $this->addDescription( <<<TEXT
40Manage foreign resources registered with ResourceLoader.
41
42This helps developers to download, verify and update local copies of upstream
43libraries registered as ResourceLoader modules. See also foreign-resources.yaml.
44
45For sources that don't publish an integrity hash, omit "integrity" (or leave empty)
46and run the "make-sri" action to compute the missing hashes.
47
48This script runs in dry-run mode by default. Use --update to actually change,
49remove, or add files to resources/lib/.
50TEXT
51 );
52 $this->addArg( 'action', 'One of "update", "verify" or "make-sri"', true );
53 $this->addArg( 'module', 'Name of a single module (Default: all)', false );
54 $this->addOption( 'verbose', 'Be verbose', false, false, 'v' );
55
56 // Use a directory in $IP instead of wfTempDir() because
57 // PHP's rename() does not work across file systems.
58 $this->tmpParentDir = "{$IP}/resources/tmp";
59 }
60
61 public function execute() {
62 global $IP;
63 $this->action = $this->getArg( 0 );
64 if ( !in_array( $this->action, [ 'update', 'verify', 'make-sri' ] ) ) {
65 $this->fatalError( "Invalid action argument." );
66 }
67
68 $registry = $this->parseBasicYaml(
69 file_get_contents( __DIR__ . '/foreign-resources.yaml' )
70 );
71 $module = $this->getArg( 1, 'all' );
72 if ( $module === 'all' ) {
73 $modules = $registry;
74 } elseif ( isset( $registry[ $module ] ) ) {
75 $modules = [ $module => $registry[ $module ] ];
76 } else {
77 $this->fatalError( 'Unknown module name.' );
78 }
79
80 foreach ( $modules as $moduleName => $info ) {
81 $this->verbose( "\n### {$moduleName}\n\n" );
82 $destDir = "{$IP}/resources/lib/$moduleName";
83
84 if ( $this->action === 'update' ) {
85 $this->output( "... updating '{$moduleName}'\n" );
86 $this->verbose( "... emptying /resources/lib/$moduleName\n" );
87 wfRecursiveRemoveDir( $destDir );
88 } elseif ( $this->action === 'verify' ) {
89 $this->output( "... verifying '{$moduleName}'\n" );
90 } else {
91 $this->output( "... checking '{$moduleName}'\n" );
92 }
93
94 $this->verbose( "... preparing {$this->tmpParentDir}\n" );
95 wfRecursiveRemoveDir( $this->tmpParentDir );
96 if ( !wfMkdirParents( $this->tmpParentDir ) ) {
97 $this->fatalError( "Unable to create {$this->tmpParentDir}" );
98 }
99
100 if ( !isset( $info['type'] ) ) {
101 $this->fatalError( "Module '$moduleName' must have a 'type' key." );
102 }
103 switch ( $info['type'] ) {
104 case 'tar':
105 $this->handleTypeTar( $moduleName, $destDir, $info );
106 break;
107 case 'file':
108 $this->handleTypeFile( $moduleName, $destDir, $info );
109 break;
110 case 'multi-file':
111 $this->handleTypeMultiFile( $moduleName, $destDir, $info );
112 break;
113 default:
114 $this->fatalError( "Unknown type '{$info['type']}' for '$moduleName'" );
115 }
116 }
117
118 $this->cleanUp();
119 $this->output( "\nDone!\n" );
120 if ( $this->failAfterOutput ) {
121 // The verify mode should check all modules/files and fail after, not during.
122 return false;
123 }
124 }
125
126 private function fetch( $src, $integrity ) {
127 $data = Http::get( $src, [ 'followRedirects' => false ] );
128 if ( $data === false ) {
129 $this->fatalError( "Failed to download resource at {$src}" );
130 }
131 $algo = $integrity === null ? $this->defaultAlgo : explode( '-', $integrity )[0];
132 $actualIntegrity = $algo . '-' . base64_encode( hash( $algo, $data, true ) );
133 if ( $integrity === $actualIntegrity ) {
134 $this->verbose( "... passed integrity check for {$src}\n" );
135 } else {
136 if ( $this->action === 'make-sri' ) {
137 $this->output( "Integrity for {$src}\n\tintegrity: ${actualIntegrity}\n" );
138 } else {
139 $this->fatalError( "Integrity check failed for {$src}\n" .
140 "\tExpected: {$integrity}\n" .
141 "\tActual: {$actualIntegrity}"
142 );
143 }
144 }
145 return $data;
146 }
147
148 private function handleTypeFile( $moduleName, $destDir, array $info ) {
149 if ( !isset( $info['src'] ) ) {
150 $this->fatalError( "Module '$moduleName' must have a 'src' key." );
151 }
152 $data = $this->fetch( $info['src'], $info['integrity'] ?? null );
153 $dest = $info['dest'] ?? basename( $info['src'] );
154 $path = "$destDir/$dest";
155 if ( $this->action === 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
156 $this->fatalError( "File for '$moduleName' is different." );
157 } elseif ( $this->action === 'update' ) {
158 wfMkdirParents( $destDir );
159 file_put_contents( "$destDir/$dest", $data );
160 }
161 }
162
163 private function handleTypeMultiFile( $moduleName, $destDir, array $info ) {
164 if ( !isset( $info['files'] ) ) {
165 $this->fatalError( "Module '$moduleName' must have a 'files' key." );
166 }
167 foreach ( $info['files'] as $dest => $file ) {
168 if ( !isset( $file['src'] ) ) {
169 $this->fatalError( "Module '$moduleName' file '$dest' must have a 'src' key." );
170 }
171 $data = $this->fetch( $file['src'], $file['integrity'] ?? null );
172 $path = "$destDir/$dest";
173 if ( $this->action === 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
174 $this->fatalError( "File '$dest' for '$moduleName' is different." );
175 } elseif ( $this->action === 'update' ) {
176 wfMkdirParents( $destDir );
177 file_put_contents( "$destDir/$dest", $data );
178 }
179 }
180 }
181
182 private function handleTypeTar( $moduleName, $destDir, array $info ) {
183 $info += [ 'src' => null, 'integrity' => null, 'dest' => null ];
184 if ( $info['src'] === null ) {
185 $this->fatalError( "Module '$moduleName' must have a 'src' key." );
186 }
187 // Download the resource to a temporary file and open it
188 $data = $this->fetch( $info['src'], $info['integrity' ] );
189 $tmpFile = "{$this->tmpParentDir}/$moduleName.tar";
190 $this->verbose( "... writing '$moduleName' src to $tmpFile\n" );
191 file_put_contents( $tmpFile, $data );
192 $p = new PharData( $tmpFile );
193 $tmpDir = "{$this->tmpParentDir}/$moduleName";
194 $p->extractTo( $tmpDir );
195 unset( $data, $p );
196
197 if ( $info['dest'] === null ) {
198 // Default: Replace the entire directory
199 $toCopy = [ $tmpDir => $destDir ];
200 } else {
201 // Expand and normalise the 'dest' entries
202 $toCopy = [];
203 foreach ( $info['dest'] as $fromSubPath => $toSubPath ) {
204 // Use glob() to expand wildcards and check existence
205 $fromPaths = glob( "{$tmpDir}/{$fromSubPath}", GLOB_BRACE );
206 if ( !$fromPaths ) {
207 $this->fatalError( "Path '$fromSubPath' of '$moduleName' not found." );
208 }
209 foreach ( $fromPaths as $fromPath ) {
210 $toCopy[$fromPath] = $toSubPath === null
211 ? "$destDir/" . basename( $fromPath )
212 : "$destDir/$toSubPath/" . basename( $fromPath );
213 }
214 }
215 }
216 foreach ( $toCopy as $from => $to ) {
217 if ( $this->action === 'verify' ) {
218 $this->verbose( "... verifying $to\n" );
219 if ( is_dir( $from ) ) {
220 $rii = new RecursiveIteratorIterator( new RecursiveDirectoryIterator(
221 $from,
222 RecursiveDirectoryIterator::SKIP_DOTS
223 ) );
224 foreach ( $rii as $file ) {
225 $remote = $file->getPathname();
226 $local = strtr( $remote, [ $from => $to ] );
227 if ( sha1_file( $remote ) !== sha1_file( $local ) ) {
228 $this->error( "File '$local' is different." );
229 $this->failAfterOutput = true;
230 }
231 }
232 } elseif ( sha1_file( $from ) !== sha1_file( $to ) ) {
233 $this->error( "File '$to' is different." );
234 $this->failAfterOutput = true;
235 }
236 } elseif ( $this->action === 'update' ) {
237 $this->verbose( "... moving $from to $to\n" );
238 wfMkdirParents( dirname( $to ) );
239 if ( !rename( $from, $to ) ) {
240 $this->fatalError( "Could not move $from to $to." );
241 }
242 }
243 }
244 }
245
246 private function verbose( $text ) {
247 if ( $this->hasOption( 'verbose' ) ) {
248 $this->output( $text );
249 }
250 }
251
252 private function cleanUp() {
253 wfRecursiveRemoveDir( $this->tmpParentDir );
254 }
255
256 protected function fatalError( $msg, $exitCode = 1 ) {
257 $this->cleanUp();
258 parent::fatalError( $msg, $exitCode );
259 }
260
270 private function parseBasicYaml( $input ) {
271 $lines = explode( "\n", $input );
272 $root = [];
273 $stack = [ &$root ];
274 $prev = 0;
275 foreach ( $lines as $i => $text ) {
276 $line = $i + 1;
277 $trimmed = ltrim( $text, ' ' );
278 if ( $trimmed === '' || $trimmed[0] === '#' ) {
279 continue;
280 }
281 $indent = strlen( $text ) - strlen( $trimmed );
282 if ( $indent % 2 !== 0 ) {
283 throw new Exception( __METHOD__ . ": Odd indentation on line $line." );
284 }
285 $depth = $indent === 0 ? 0 : ( $indent / 2 );
286 if ( $depth < $prev ) {
287 // Close previous branches we can't re-enter
288 array_splice( $stack, $depth + 1 );
289 }
290 if ( !array_key_exists( $depth, $stack ) ) {
291 throw new Exception( __METHOD__ . ": Too much indentation on line $line." );
292 }
293 if ( strpos( $trimmed, ':' ) === false ) {
294 throw new Exception( __METHOD__ . ": Missing colon on line $line." );
295 }
296 $dest =& $stack[ $depth ];
297 if ( $dest === null ) {
298 // Promote from null to object
299 $dest = [];
300 }
301 list( $key, $val ) = explode( ':', $trimmed, 2 );
302 $val = ltrim( $val, ' ' );
303 if ( $val !== '' ) {
304 // Add string
305 $dest[ $key ] = $val;
306 } else {
307 // Add null (may become an object later)
308 $val = null;
309 $stack[] = &$val;
310 $dest[ $key ] = &$val;
311 }
312 $prev = $depth;
313 unset( $dest, $val );
314 }
315 return $root;
316 }
317}
318
319$maintClass = ManageForeignResources::class;
320require_once RUN_MAINTENANCE_IF_MAIN;
and(b) You must cause any modified files to carry prominent notices stating that You changed the files
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the work(an example is provided in the Appendix below). "Derivative Works" shall mean any work
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable or merely the Work and Derivative Works thereof Contribution shall mean any work of including the original version of the Work and any modifications or additions to that Work or Derivative Works that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner For the purposes of this submitted means any form of or written communication sent to the Licensor or its including but not limited to communication on electronic mailing source code control systems
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.
$IP
Definition WebStart.php:41
$line
Definition cdb.php:59
static get( $url, $options=[], $caller=__METHOD__)
Simple wrapper for Http::request( 'GET' )
Definition Http.php:98
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
error( $err, $die=0)
Throw an error to the user.
output( $out, $channel=null)
Throw some output to the user.
hasOption( $name)
Checks to see if a particular option exists.
getArg( $argId=0, $default=null)
Get an argument.
addDescription( $text)
Set the description text.
Manage foreign resources registered with ResourceLoader.
handleTypeTar( $moduleName, $destDir, array $info)
handleTypeFile( $moduleName, $destDir, array $info)
parseBasicYaml( $input)
Basic YAML parser.
__construct()
Default constructor.
handleTypeMultiFile( $moduleName, $destDir, array $info)
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Dynamic JavaScript and CSS resource loading system.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if that
Definition deferred.txt:13
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
globals txt Globals are evil The original MediaWiki code relied on globals for processing context far too often MediaWiki development since then has been a story of slowly moving context out of global variables and into objects Storing processing context in object member variables allows those objects to be reused in a much more flexible way Consider the elegance of
database rows
Definition globals.txt:10
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing we can concentrate it all in an extension file
Definition hooks.txt:106
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
require_once RUN_MAINTENANCE_IF_MAIN
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
if(is_array($mode)) switch( $mode) $input
$tester verbose
$lines
Definition router.php:61