MediaWiki  1.32.0
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' => 'removeAutodiscoveredParserTestFiles',
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  $this->addOption( 'config-prefix', 'Custom prefix for configuration settings', false, true );
63  }
64 
65  protected function getAllGlobals() {
66  $processor = new ReflectionClass( ExtensionProcessor::class );
67  $settings = $processor->getProperty( 'globalSettings' );
68  $settings->setAccessible( true );
69  return array_merge( $settings->getValue(), $this->formerGlobals );
70  }
71 
72  public function execute() {
73  // Extensions will do stuff like $wgResourceModules += array(...) which is a
74  // fatal unless an array is already set. So set an empty value.
75  // And use the weird $__settings name to avoid any conflicts
76  // with real poorly named settings.
77  $__settings = array_merge( $this->getAllGlobals(), array_keys( $this->custom ) );
78  foreach ( $__settings as $var ) {
79  $var = 'wg' . $var;
80  $$var = [];
81  }
82  unset( $var );
83  $arg = $this->getArg( 0 );
84  if ( !is_file( $arg ) ) {
85  $this->fatalError( "$arg is not a file." );
86  }
87  require $arg;
88  unset( $arg );
89  // Try not to create any local variables before this line
90  $vars = get_defined_vars();
91  unset( $vars['this'] );
92  unset( $vars['__settings'] );
93  $this->dir = dirname( realpath( $this->getArg( 0 ) ) );
94  $this->json = [];
95  $globalSettings = $this->getAllGlobals();
96  $configPrefix = $this->getOption( 'config-prefix', 'wg' );
97  if ( $configPrefix !== 'wg' ) {
98  $this->json['config']['_prefix'] = $configPrefix;
99  }
100  foreach ( $vars as $name => $value ) {
101  $realName = substr( $name, 2 ); // Strip 'wg'
102  if ( $realName === false ) {
103  continue;
104  }
105 
106  // If it's an empty array that we likely set, skip it
107  if ( is_array( $value ) && count( $value ) === 0 && in_array( $realName, $__settings ) ) {
108  continue;
109  }
110 
111  if ( isset( $this->custom[$realName] ) ) {
112  call_user_func_array( [ $this, $this->custom[$realName] ],
113  [ $realName, $value, $vars ] );
114  } elseif ( in_array( $realName, $globalSettings ) ) {
115  $this->json[$realName] = $value;
116  } elseif ( array_key_exists( $realName, $this->noLongerSupportedGlobals ) ) {
117  $this->output( 'Warning: Skipped global "' . $name . '" (' .
118  $this->noLongerSupportedGlobals[$realName] . '). ' .
119  "Please update the entry point before convert to registration.\n" );
120  $this->hasWarning = true;
121  } elseif ( strpos( $name, $configPrefix ) === 0 ) {
122  // Most likely a config setting
123  $this->json['config'][substr( $name, strlen( $configPrefix ) )] = [ 'value' => $value ];
124  } elseif ( $configPrefix !== 'wg' && strpos( $name, 'wg' ) === 0 ) {
125  // Warn about this
126  $this->output( 'Warning: Skipped global "' . $name . '" (' .
127  'config prefix is "' . $configPrefix . '"). ' .
128  "Please check that this setting isn't needed.\n" );
129  }
130  }
131 
132  // check, if the extension requires composer libraries
133  if ( $this->needsComposerAutoloader( dirname( $this->getArg( 0 ) ) ) ) {
134  // set the load composer autoloader automatically property
135  $this->output( "Detected composer dependencies, setting 'load_composer_autoloader' to true.\n" );
136  $this->json['load_composer_autoloader'] = true;
137  }
138 
139  // Move some keys to the top
140  $out = [];
141  foreach ( $this->promote as $key ) {
142  if ( isset( $this->json[$key] ) ) {
143  $out[$key] = $this->json[$key];
144  unset( $this->json[$key] );
145  }
146  }
147  // Set a requirement on the MediaWiki version that the current MANIFEST_VERSION
148  // was introduced in.
149  $out['requires'] = [
151  ];
152  $out += $this->json;
153  // Put this at the bottom
154  $out['manifest_version'] = ExtensionRegistry::MANIFEST_VERSION;
155  $type = $this->hasOption( 'skin' ) ? 'skin' : 'extension';
156  $fname = "{$this->dir}/$type.json";
157  $prettyJSON = FormatJson::encode( $out, "\t", FormatJson::ALL_OK );
158  file_put_contents( $fname, $prettyJSON . "\n" );
159  $this->output( "Wrote output to $fname.\n" );
160  if ( $this->hasWarning ) {
161  $this->output( "Found warnings! Please resolve the warnings and rerun this script.\n" );
162  }
163  }
164 
165  protected function handleExtensionFunctions( $realName, $value ) {
166  foreach ( $value as $func ) {
167  if ( $func instanceof Closure ) {
168  $this->fatalError( "Error: Closures cannot be converted to JSON. " .
169  "Please move your extension function somewhere else."
170  );
171  }
172  // check if $func exists in the global scope
173  if ( function_exists( $func ) ) {
174  $this->fatalError( "Error: Global functions cannot be converted to JSON. " .
175  "Please move your extension function ($func) into a class."
176  );
177  }
178  }
179 
180  $this->json[$realName] = $value;
181  }
182 
183  protected function handleMessagesDirs( $realName, $value ) {
184  foreach ( $value as $key => $dirs ) {
185  foreach ( (array)$dirs as $dir ) {
186  $this->json[$realName][$key][] = $this->stripPath( $dir, $this->dir );
187  }
188  }
189  }
190 
191  protected function handleExtensionMessagesFiles( $realName, $value, $vars ) {
192  foreach ( $value as $key => $file ) {
193  $strippedFile = $this->stripPath( $file, $this->dir );
194  if ( isset( $vars['wgMessagesDirs'][$key] ) ) {
195  $this->output(
196  "Note: Ignoring PHP shim $strippedFile. " .
197  "If your extension no longer supports versions of MediaWiki " .
198  "older than 1.23.0, you can safely delete it.\n"
199  );
200  } else {
201  $this->json[$realName][$key] = $strippedFile;
202  }
203  }
204  }
205 
206  private function stripPath( $val, $dir ) {
207  if ( $val === $dir ) {
208  $val = '';
209  } elseif ( strpos( $val, $dir ) === 0 ) {
210  // +1 is for the trailing / that won't be in $this->dir
211  $val = substr( $val, strlen( $dir ) + 1 );
212  }
213 
214  return $val;
215  }
216 
217  protected function removeAbsolutePath( $realName, $value ) {
218  $out = [];
219  foreach ( $value as $key => $val ) {
220  $out[$key] = $this->stripPath( $val, $this->dir );
221  }
222  $this->json[$realName] = $out;
223  }
224 
225  protected function removeAutodiscoveredParserTestFiles( $realName, $value ) {
226  $out = [];
227  foreach ( $value as $key => $val ) {
228  $path = $this->stripPath( $val, $this->dir );
229  // When path starts with tests/parser/ the file would be autodiscovered with
230  // extension registry, so no need to add it to extension.json
231  if ( substr( $path, 0, 13 ) !== 'tests/parser/' || substr( $path, -4 ) !== '.txt' ) {
232  $out[$key] = $path;
233  }
234  }
235  // in the best case all entries are filtered out
236  if ( $out ) {
237  $this->json[$realName] = $out;
238  }
239  }
240 
241  protected function handleCredits( $realName, $value ) {
242  $keys = array_keys( $value );
243  $this->json['type'] = $keys[0];
244  $values = array_values( $value );
245  foreach ( $values[0][0] as $name => $val ) {
246  if ( $name !== 'path' ) {
247  $this->json[$name] = $val;
248  }
249  }
250  }
251 
252  public function handleHooks( $realName, $value ) {
253  foreach ( $value as $hookName => &$handlers ) {
254  if ( $hookName === 'UnitTestsList' ) {
255  $this->output( "Note: the UnitTestsList hook is no longer necessary as " .
256  "long as your tests are located in the \"tests/phpunit/\" directory. " .
257  "Please see <https://www.mediawiki.org/wiki/Manual:PHP_unit_testing/" .
258  "Writing_unit_tests_for_extensions#Register_your_tests> for more details.\n"
259  );
260  }
261  foreach ( $handlers as $func ) {
262  if ( $func instanceof Closure ) {
263  $this->fatalError( "Error: Closures cannot be converted to JSON. " .
264  "Please move the handler for $hookName somewhere else."
265  );
266  }
267  // Check if $func exists in the global scope
268  if ( function_exists( $func ) ) {
269  $this->fatalError( "Error: Global functions cannot be converted to JSON. " .
270  "Please move the handler for $hookName inside a class."
271  );
272  }
273  }
274  if ( count( $handlers ) === 1 ) {
275  $handlers = $handlers[0];
276  }
277  }
278  $this->json[$realName] = $value;
279  }
280 
281  protected function handleResourceModules( $realName, $value ) {
282  $defaults = [];
283  $remote = $this->hasOption( 'skin' ) ? 'remoteSkinPath' : 'remoteExtPath';
284  foreach ( $value as $name => $data ) {
285  if ( isset( $data['localBasePath'] ) ) {
286  $data['localBasePath'] = $this->stripPath( $data['localBasePath'], $this->dir );
287  if ( !$defaults ) {
288  $defaults['localBasePath'] = $data['localBasePath'];
289  unset( $data['localBasePath'] );
290  if ( isset( $data[$remote] ) ) {
291  $defaults[$remote] = $data[$remote];
292  unset( $data[$remote] );
293  }
294  } else {
295  if ( $data['localBasePath'] === $defaults['localBasePath'] ) {
296  unset( $data['localBasePath'] );
297  }
298  if ( isset( $data[$remote] ) && isset( $defaults[$remote] )
299  && $data[$remote] === $defaults[$remote]
300  ) {
301  unset( $data[$remote] );
302  }
303  }
304  }
305 
306  $this->json[$realName][$name] = $data;
307  }
308  if ( $defaults ) {
309  $this->json['ResourceFileModulePaths'] = $defaults;
310  }
311  }
312 
313  protected function needsComposerAutoloader( $path ) {
314  $path .= '/composer.json';
315  if ( file_exists( $path ) ) {
316  // assume, that the composer.json file is in the root of the extension path
317  $composerJson = new ComposerJson( $path );
318  // check, if there are some dependencies in the require section
319  if ( $composerJson->getRequiredDependencies() ) {
320  return true;
321  }
322  }
323  return false;
324  }
325 }
326 
328 require_once RUN_MAINTENANCE_IF_MAIN;
ConvertExtensionToRegistration\handleCredits
handleCredits( $realName, $value)
Definition: convertExtensionToRegistration.php:241
ConvertExtensionToRegistration\$formerGlobals
array $formerGlobals
Things that were formerly globals and should still be converted.
Definition: convertExtensionToRegistration.php:24
ExtensionRegistry\MANIFEST_VERSION
const MANIFEST_VERSION
Version of the highest supported manifest version Note: Update MANIFEST_VERSION_MW_VERSION when chang...
Definition: ExtensionRegistry.php:25
ComposerJson
Reads a composer.json file and provides accessors to get its hash and the required dependencies.
Definition: ComposerJson.php:9
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:465
captcha-old.count
count
Definition: captcha-old.py:249
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:317
ConvertExtensionToRegistration\handleHooks
handleHooks( $realName, $value)
Definition: convertExtensionToRegistration.php:252
ConvertExtensionToRegistration\__construct
__construct()
Default constructor.
Definition: convertExtensionToRegistration.php:56
RUN_MAINTENANCE_IF_MAIN
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
ConvertExtensionToRegistration\needsComposerAutoloader
needsComposerAutoloader( $path)
Definition: convertExtensionToRegistration.php:313
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
FormatJson\ALL_OK
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
ConvertExtensionToRegistration\handleExtensionFunctions
handleExtensionFunctions( $realName, $value)
Definition: convertExtensionToRegistration.php:165
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
ConvertExtensionToRegistration\handleExtensionMessagesFiles
handleExtensionMessagesFiles( $realName, $value, $vars)
Definition: convertExtensionToRegistration.php:191
ConvertExtensionToRegistration\removeAutodiscoveredParserTestFiles
removeAutodiscoveredParserTestFiles( $realName, $value)
Definition: convertExtensionToRegistration.php:225
FormatJson\encode
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:115
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:236
ExtensionRegistry\MANIFEST_VERSION_MW_VERSION
const MANIFEST_VERSION_MW_VERSION
MediaWiki version constraint representing what the current highest MANIFEST_VERSION is supported in.
Definition: ExtensionRegistry.php:31
$dirs
$dirs
Definition: mergeMessageFileList.php:194
$vars
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2270
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))
json
The package json
Definition: README.txt:1
ConvertExtensionToRegistration\$dir
$dir
Definition: convertExtensionToRegistration.php:54
ConvertExtensionToRegistration\getAllGlobals
getAllGlobals()
Definition: convertExtensionToRegistration.php:65
$fname
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition: Setup.php:121
ExtensionRegistry\MEDIAWIKI_CORE
const MEDIAWIKI_CORE
"requires" key that applies to MediaWiki core/$wgVersion
Definition: ExtensionRegistry.php:19
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
ConvertExtensionToRegistration\$json
$json
Definition: convertExtensionToRegistration.php:54
$value
$value
Definition: styleTest.css.php:49
ConvertExtensionToRegistration\$custom
$custom
Definition: convertExtensionToRegistration.php:7
ConvertExtensionToRegistration\handleResourceModules
handleResourceModules( $realName, $value)
Definition: convertExtensionToRegistration.php:281
ConvertExtensionToRegistration\removeAbsolutePath
removeAbsolutePath( $realName, $value)
Definition: convertExtensionToRegistration.php:217
ConvertExtensionToRegistration\handleMessagesDirs
handleMessagesDirs( $realName, $value)
Definition: convertExtensionToRegistration.php:183
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:271
ConvertExtensionToRegistration\stripPath
stripPath( $val, $dir)
Definition: convertExtensionToRegistration.php:206
Maintenance\addArg
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:288
$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
ConvertExtensionToRegistration\execute
execute()
Do the actual work.
Definition: convertExtensionToRegistration.php:72
$keys
$keys
Definition: testCompression.php:67
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:414
ConvertExtensionToRegistration\$promote
array $promote
Keys that should be put at the top of the generated JSON file (T86608)
Definition: convertExtensionToRegistration.php:42
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
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
ConvertExtensionToRegistration\$hasWarning
$hasWarning
Definition: convertExtensionToRegistration.php:54
ConvertExtensionToRegistration
Definition: convertExtensionToRegistration.php:5
$maintClass
$maintClass
Definition: convertExtensionToRegistration.php:327
$out
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:813
$type
$type
Definition: testCompression.php:48
ConvertExtensionToRegistration\$noLongerSupportedGlobals
array $noLongerSupportedGlobals
No longer supported globals (with reason) should not be converted and emit a warning.
Definition: convertExtensionToRegistration.php:33