MediaWiki  1.32.5
manageForeignResources.php
Go to the documentation of this file.
1 <?php
22 require_once __DIR__ . '/../Maintenance.php';
23 
31  private $defaultAlgo = 'sha384';
32  private $tmpParentDir;
33  private $action;
34  private $failAfterOutput = false;
35 
36  public function __construct() {
37  global $IP;
38  parent::__construct();
39  $this->addDescription( <<<TEXT
40 Manage foreign resources registered with ResourceLoader.
41 
42 This helps developers to download, verify and update local copies of upstream
43 libraries registered as ResourceLoader modules. See also foreign-resources.yaml.
44 
45 For sources that don't publish an integrity hash, omit "integrity" (or leave empty)
46 and run the "make-sri" action to compute the missing hashes.
47 
48 This script runs in dry-run mode by default. Use --update to actually change,
49 remove, or add files to resources/lib/.
50 TEXT
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 
320 require_once RUN_MAINTENANCE_IF_MAIN;
ManageForeignResources\handleTypeFile
handleTypeFile( $moduleName, $destDir, array $info)
Definition: manageForeignResources.php:148
file
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:91
ManageForeignResources
Manage foreign resources registered with ResourceLoader.
Definition: manageForeignResources.php:30
wfMkdirParents
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Definition: GlobalFunctions.php:2050
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:317
RUN_MAINTENANCE_IF_MAIN
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
a
</source > ! result< div class="mw-highlight mw-content-ltr" dir="ltr">< pre >< span ></span >< span class="kd"> var</span >< span class="nx"> a</span >< span class="p"></span ></pre ></div > ! end ! test Multiline< source/> in lists !input *< source > a b</source > *foo< source > a b</source > ! html< ul >< li >< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul >< ul >< li > foo< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul > ! html tidy< ul >< li >< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul >< ul >< li > foo< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul > ! end ! test Custom attributes !input< source lang="javascript" id="foo" class="bar" dir="rtl" style="font-size: larger;"> var a
Definition: parserTests.txt:89
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
ManageForeignResources\$tmpParentDir
$tmpParentDir
Definition: manageForeignResources.php:32
ManageForeignResources\parseBasicYaml
parseBasicYaml( $input)
Basic YAML parser.
Definition: manageForeignResources.php:270
php
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:35
Makefile.download
def download(url, dest)
Definition: Makefile.py:47
systems
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
Definition: APACHE-LICENSE-2.0.txt:49
ManageForeignResources\cleanUp
cleanUp()
Definition: manageForeignResources.php:252
ManageForeignResources\handleTypeMultiFile
handleTypeMultiFile( $moduleName, $destDir, array $info)
Definition: manageForeignResources.php:163
ManageForeignResources\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: manageForeignResources.php:256
$input
if(is_array( $mode)) switch( $mode) $input
Definition: postprocess-phan.php:141
$modules
$modules
Definition: HTMLFormElement.php:12
not
if not
Definition: COPYING.txt:307
$IP
$IP
Definition: update.php:3
$lines
$lines
Definition: router.php:61
array
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))
work
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two distribute and or modify the software for each author s protection and we want to make certain that everyone understands that there is no warranty for this free software If the software is modified by someone else and passed we want its recipients to know that what they have is not the so that any problems introduced by others will not reflect on the original authors reputations any free program is threatened constantly by software patents We wish to avoid the danger that redistributors of a free program will individually obtain patent in effect making the program proprietary To prevent we have made it clear that any patent must be licensed for everyone s free use or not licensed at all The precise terms and conditions for distribution and modification follow GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR DISTRIBUTION AND MODIFICATION This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License The refers to any such program or work
Definition: COPYING.txt:43
ManageForeignResources\handleTypeTar
handleTypeTar( $moduleName, $destDir, array $info)
Definition: manageForeignResources.php:182
ManageForeignResources\fetch
fetch( $src, $integrity)
Definition: manageForeignResources.php:126
list
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
captcha-old.action
action
Definition: captcha-old.py:212
or
or
Definition: COPYING.txt:140
Http\get
static get( $url, $options=[], $caller=__METHOD__)
Simple wrapper for Http::request( 'GET' )
Definition: Http.php:98
ManageForeignResources\$defaultAlgo
$defaultAlgo
Definition: manageForeignResources.php:31
$line
$line
Definition: cdb.php:59
ManageForeignResources\__construct
__construct()
Default constructor.
Definition: manageForeignResources.php:36
$maintClass
$maintClass
Definition: manageForeignResources.php:308
and
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two and(2) offer you this license which gives you legal permission to copy
wfRecursiveRemoveDir
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
Definition: GlobalFunctions.php:2093
$path
$path
Definition: NoLocalSettings.php:25
as
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
Definition: distributors.txt:9
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:442
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:414
ManageForeignResources\execute
execute()
Do the actual work.
Definition: manageForeignResources.php:61
of
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
Definition: globals.txt:10
ManageForeignResources\$failAfterOutput
$failAfterOutput
Definition: manageForeignResources.php:34
that
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:11
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
copies
c Accompany it with the information you received as to the offer to distribute corresponding source complete source code means all the source code for all modules it plus any associated interface definition plus the scripts used to control compilation and installation of the executable as a special the source code distributed need not include anything that is normally and so on of the operating system on which the executable unless that component itself accompanies the executable If distribution of executable or object code is made by offering access to copy from a designated then offering equivalent access to copy the source code from the same place counts as distribution of the source even though third parties are not compelled to copy the source along with the object code You may not or distribute the Program except as expressly provided under this License Any attempt otherwise to sublicense or distribute the Program is and will automatically terminate your rights under this License parties who have received copies
Definition: COPYING.txt:162
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option exists.
Definition: Maintenance.php:257
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:336
ManageForeignResources\$action
$action
Definition: manageForeignResources.php:33
ManageForeignResources\verbose
verbose( $text)
Definition: manageForeignResources.php:246