MediaWiki  1.27.2
convertExtensionToRegistration.php
Go to the documentation of this file.
1 <?php
2 
3 require_once __DIR__ . '/Maintenance.php';
4 
6 
7  protected $custom = [
8  'MessagesDirs' => 'handleMessagesDirs',
9  'ExtensionMessagesFiles' => 'handleExtensionMessagesFiles',
10  'AutoloadClasses' => 'removeAbsolutePath',
11  'ExtensionCredits' => 'handleCredits',
12  'ResourceModules' => 'handleResourceModules',
13  'ResourceModuleSkinStyles' => 'handleResourceModules',
14  'Hooks' => 'handleHooks',
15  'ExtensionFunctions' => 'handleExtensionFunctions',
16  'ParserTestFiles' => 'removeAbsolutePath',
17  ];
18 
24  protected $formerGlobals = [
25  'TrackingCategories',
26  ];
27 
34  'SpecialPageGroups' => 'deprecated', // Deprecated 1.21, removed in 1.26
35  ];
36 
42  protected $promote = [
43  'name',
44  'namemsg',
45  'version',
46  'author',
47  'url',
48  'description',
49  'descriptionmsg',
50  'license-name',
51  'type',
52  ];
53 
54  private $json, $dir, $hasWarning = false;
55 
56  public function __construct() {
57  parent::__construct();
58  $this->addDescription( 'Converts extension entry points to the new JSON registration format' );
59  $this->addArg( 'path', 'Location to the PHP entry point you wish to convert',
60  /* $required = */ true );
61  $this->addOption( 'skin', 'Whether to write to skin.json', false, false );
62  }
63 
64  protected function getAllGlobals() {
65  $processor = new ReflectionClass( 'ExtensionProcessor' );
66  $settings = $processor->getProperty( 'globalSettings' );
67  $settings->setAccessible( true );
68  return $settings->getValue() + $this->formerGlobals;
69  }
70 
71  public function execute() {
72  // Extensions will do stuff like $wgResourceModules += array(...) which is a
73  // fatal unless an array is already set. So set an empty value.
74  // And use the weird $__settings name to avoid any conflicts
75  // with real poorly named settings.
76  $__settings = array_merge( $this->getAllGlobals(), array_keys( $this->custom ) );
77  foreach ( $__settings as $var ) {
78  $var = 'wg' . $var;
79  $$var = [];
80  }
81  unset( $var );
82  $arg = $this->getArg( 0 );
83  if ( !is_file( $arg ) ) {
84  $this->error( "$arg is not a file.", true );
85  }
86  require $arg;
87  unset( $arg );
88  // Try not to create any local variables before this line
89  $vars = get_defined_vars();
90  unset( $vars['this'] );
91  unset( $vars['__settings'] );
92  $this->dir = dirname( realpath( $this->getArg( 0 ) ) );
93  $this->json = [];
94  $globalSettings = $this->getAllGlobals();
95  foreach ( $vars as $name => $value ) {
96  $realName = substr( $name, 2 ); // Strip 'wg'
97 
98  // If it's an empty array that we likely set, skip it
99  if ( is_array( $value ) && count( $value ) === 0 && in_array( $realName, $__settings ) ) {
100  continue;
101  }
102 
103  if ( isset( $this->custom[$realName] ) ) {
104  call_user_func_array( [ $this, $this->custom[$realName] ],
105  [ $realName, $value, $vars ] );
106  } elseif ( in_array( $realName, $globalSettings ) ) {
107  $this->json[$realName] = $value;
108  } elseif ( array_key_exists( $realName, $this->noLongerSupportedGlobals ) ) {
109  $this->output( 'Warning: Skipped global "' . $name . '" (' .
110  $this->noLongerSupportedGlobals[$realName] . '). ' .
111  "Please update the entry point before convert to registration.\n" );
112  $this->hasWarning = true;
113  } elseif ( strpos( $name, 'wg' ) === 0 ) {
114  // Most likely a config setting
115  $this->json['config'][$realName] = $value;
116  }
117  }
118 
119  // check, if the extension requires composer libraries
120  if ( $this->needsComposerAutoloader( dirname( $this->getArg( 0 ) ) ) ) {
121  // set the load composer autoloader automatically property
122  $this->output( "Detected composer dependencies, setting 'load_composer_autoloader' to true.\n" );
123  $this->json['load_composer_autoloader'] = true;
124  }
125 
126  // Move some keys to the top
127  $out = [];
128  foreach ( $this->promote as $key ) {
129  if ( isset( $this->json[$key] ) ) {
130  $out[$key] = $this->json[$key];
131  unset( $this->json[$key] );
132  }
133  }
134  $out += $this->json;
135  // Put this at the bottom
136  $out['manifest_version'] = ExtensionRegistry::MANIFEST_VERSION;
137  $type = $this->hasOption( 'skin' ) ? 'skin' : 'extension';
138  $fname = "{$this->dir}/$type.json";
139  $prettyJSON = FormatJson::encode( $out, "\t", FormatJson::ALL_OK );
140  file_put_contents( $fname, $prettyJSON . "\n" );
141  $this->output( "Wrote output to $fname.\n" );
142  if ( $this->hasWarning ) {
143  $this->output( "Found warnings! Please resolve the warnings and rerun this script.\n" );
144  }
145  }
146 
147  protected function handleExtensionFunctions( $realName, $value ) {
148  foreach ( $value as $func ) {
149  if ( $func instanceof Closure ) {
150  $this->error( "Error: Closures cannot be converted to JSON. " .
151  "Please move your extension function somewhere else.", 1
152  );
153  }
154  // check if $func exists in the global scope
155  if ( function_exists( $func ) ) {
156  $this->error( "Error: Global functions cannot be converted to JSON. " .
157  "Please move your extension function ($func) into a class.", 1
158  );
159  }
160  }
161 
162  $this->json[$realName] = $value;
163  }
164 
165  protected function handleMessagesDirs( $realName, $value ) {
166  foreach ( $value as $key => $dirs ) {
167  foreach ( (array)$dirs as $dir ) {
168  $this->json[$realName][$key][] = $this->stripPath( $dir, $this->dir );
169  }
170  }
171  }
172 
173  protected function handleExtensionMessagesFiles( $realName, $value, $vars ) {
174  foreach ( $value as $key => $file ) {
175  $strippedFile = $this->stripPath( $file, $this->dir );
176  if ( isset( $vars['wgMessagesDirs'][$key] ) ) {
177  $this->output(
178  "Note: Ignoring PHP shim $strippedFile. " .
179  "If your extension no longer supports versions of MediaWiki " .
180  "older than 1.23.0, you can safely delete it.\n"
181  );
182  } else {
183  $this->json[$realName][$key] = $strippedFile;
184  }
185  }
186  }
187 
188  private function stripPath( $val, $dir ) {
189  if ( $val === $dir ) {
190  $val = '';
191  } elseif ( strpos( $val, $dir ) === 0 ) {
192  // +1 is for the trailing / that won't be in $this->dir
193  $val = substr( $val, strlen( $dir ) + 1 );
194  }
195 
196  return $val;
197  }
198 
199  protected function removeAbsolutePath( $realName, $value ) {
200  $out = [];
201  foreach ( $value as $key => $val ) {
202  $out[$key] = $this->stripPath( $val, $this->dir );
203  }
204  $this->json[$realName] = $out;
205  }
206 
207  protected function handleCredits( $realName, $value ) {
208  $keys = array_keys( $value );
209  $this->json['type'] = $keys[0];
210  $values = array_values( $value );
211  foreach ( $values[0][0] as $name => $val ) {
212  if ( $name !== 'path' ) {
213  $this->json[$name] = $val;
214  }
215  }
216  }
217 
218  public function handleHooks( $realName, $value ) {
219  foreach ( $value as $hookName => &$handlers ) {
220  foreach ( $handlers as $func ) {
221  if ( $func instanceof Closure ) {
222  $this->error( "Error: Closures cannot be converted to JSON. " .
223  "Please move the handler for $hookName somewhere else.", 1
224  );
225  }
226  // Check if $func exists in the global scope
227  if ( function_exists( $func ) ) {
228  $this->error( "Error: Global functions cannot be converted to JSON. " .
229  "Please move the handler for $hookName inside a class.", 1
230  );
231  }
232  }
233  if ( count( $handlers ) === 1 ) {
234  $handlers = $handlers[0];
235  }
236  }
237  $this->json[$realName] = $value;
238  }
239 
240  protected function handleResourceModules( $realName, $value ) {
241  $defaults = [];
242  $remote = $this->hasOption( 'skin' ) ? 'remoteSkinPath' : 'remoteExtPath';
243  foreach ( $value as $name => $data ) {
244  if ( isset( $data['localBasePath'] ) ) {
245  $data['localBasePath'] = $this->stripPath( $data['localBasePath'], $this->dir );
246  if ( !$defaults ) {
247  $defaults['localBasePath'] = $data['localBasePath'];
248  unset( $data['localBasePath'] );
249  if ( isset( $data[$remote] ) ) {
250  $defaults[$remote] = $data[$remote];
251  unset( $data[$remote] );
252  }
253  } else {
254  if ( $data['localBasePath'] === $defaults['localBasePath'] ) {
255  unset( $data['localBasePath'] );
256  }
257  if ( isset( $data[$remote] ) && isset( $defaults[$remote] )
258  && $data[$remote] === $defaults[$remote]
259  ) {
260  unset( $data[$remote] );
261  }
262  }
263  }
264 
265  $this->json[$realName][$name] = $data;
266  }
267  if ( $defaults ) {
268  $this->json['ResourceFileModulePaths'] = $defaults;
269  }
270  }
271 
272  protected function needsComposerAutoloader( $path ) {
273  $path .= '/composer.json';
274  if ( file_exists( $path ) ) {
275  // assume, that the composer.json file is in the root of the extension path
276  $composerJson = new ComposerJson( $path );
277  // check, if there are some dependencies in the require section
278  if ( $composerJson->getRequiredDependencies() ) {
279  return true;
280  }
281  }
282  return false;
283  }
284 }
285 
286 $maintClass = 'ConvertExtensionToRegistration';
287 require_once RUN_MAINTENANCE_IF_MAIN;
const MANIFEST_VERSION
Version of the highest supported manifest version.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:762
The package json
Definition: README.txt:1
the array() calling protocol came about after MediaWiki 1.4rc1.
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
addArg($arg, $description, $required=true)
Add some args that are needed.
array array $promote
Keys that should be put at the top of the generated JSON file (T86608)
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
$value
handleExtensionMessagesFiles($realName, $value, $vars)
hasOption($name)
Checks to see if a particular param exists.
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
addOption($name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
array $noLongerSupportedGlobals
No longer supported globals (with reason) should not be converted and emit a warning.
static encode($value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:127
array $formerGlobals
Things that were formerly globals and should still be converted.
addDescription($text)
Set the description text.
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
output($out, $channel=null)
Throw some output to the user.
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
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Definition: Setup.php:35
error($err, $die=0)
Throw an error to the user.
getArg($argId=0, $default=null)
Get an argument.
Reads a composer.json file and provides accessors to get its hash and the required dependencies...
Definition: ComposerJson.php:9
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:1996
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2338
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310