MediaWiki REL1_31
AutoloadGenerator.php
Go to the documentation of this file.
1<?php
2
17 const FILETYPE_JSON = 'json';
18 const FILETYPE_PHP = 'php';
19
23 protected $basepath;
24
28 protected $collector;
29
33 protected $classes = [];
34
38 protected $variableName = 'wgAutoloadClasses';
39
43 protected $overrides = [];
44
50 protected $excludePaths = [];
51
59 public function __construct( $basepath, $flags = [] ) {
60 if ( !is_array( $flags ) ) {
61 $flags = [ $flags ];
62 }
63 $this->basepath = self::normalizePathSeparator( realpath( $basepath ) );
64 $this->collector = new ClassCollector;
65 if ( in_array( 'local', $flags ) ) {
66 $this->variableName = 'wgAutoloadLocalClasses';
67 }
68 }
69
76 public function setExcludePaths( array $paths ) {
77 foreach ( $paths as $path ) {
78 $this->excludePaths[] = self::normalizePathSeparator( $path );
79 }
80 }
81
88 private function shouldExclude( $path ) {
89 foreach ( $this->excludePaths as $dir ) {
90 if ( strpos( $path, $dir ) === 0 ) {
91 return true;
92 }
93 }
94
95 return false;
96 }
97
106 public function forceClassPath( $fqcn, $inputPath ) {
107 $path = self::normalizePathSeparator( realpath( $inputPath ) );
108 if ( !$path ) {
109 throw new \Exception( "Invalid path: $inputPath" );
110 }
111 $len = strlen( $this->basepath );
112 if ( substr( $path, 0, $len ) !== $this->basepath ) {
113 throw new \Exception( "Path is not within basepath: $inputPath" );
114 }
115 $shortpath = substr( $path, $len );
116 $this->overrides[$fqcn] = $shortpath;
117 }
118
123 public function readFile( $inputPath ) {
124 // NOTE: do NOT expand $inputPath using realpath(). It is perfectly
125 // reasonable for LocalSettings.php and similiar files to be symlinks
126 // to files that are outside of $this->basepath.
127 $inputPath = self::normalizePathSeparator( $inputPath );
128 $len = strlen( $this->basepath );
129 if ( substr( $inputPath, 0, $len ) !== $this->basepath ) {
130 throw new \Exception( "Path is not within basepath: $inputPath" );
131 }
132 if ( $this->shouldExclude( $inputPath ) ) {
133 return;
134 }
135 $result = $this->collector->getClasses(
136 file_get_contents( $inputPath )
137 );
138 if ( $result ) {
139 $shortpath = substr( $inputPath, $len );
140 $this->classes[$shortpath] = $result;
141 }
142 }
143
148 public function readDir( $dir ) {
149 $it = new RecursiveDirectoryIterator(
150 self::normalizePathSeparator( realpath( $dir ) ) );
151 $it = new RecursiveIteratorIterator( $it );
152
153 foreach ( $it as $path => $file ) {
154 $ext = pathinfo( $path, PATHINFO_EXTENSION );
155 // some older files in mw use .inc
156 if ( $ext === 'php' || $ext === 'inc' ) {
157 $this->readFile( $path );
158 }
159 }
160 }
161
170 protected function generateJsonAutoload( $filename ) {
171 $key = 'AutoloadClasses';
172 $json = FormatJson::decode( file_get_contents( $filename ), true );
173 unset( $json[$key] );
174 // Inverting the key-value pairs so that they become of the
175 // format class-name : path when they get converted into json.
176 foreach ( $this->classes as $path => $contained ) {
177 foreach ( $contained as $fqcn ) {
178 // Using substr to remove the leading '/'
179 $json[$key][$fqcn] = substr( $path, 1 );
180 }
181 }
182 foreach ( $this->overrides as $path => $fqcn ) {
183 // Using substr to remove the leading '/'
184 $json[$key][$fqcn] = substr( $path, 1 );
185 }
186
187 // Sorting the list of autoload classes.
188 ksort( $json[$key] );
189
190 // Return the whole JSON file
191 return FormatJson::encode( $json, "\t", FormatJson::ALL_OK ) . "\n";
192 }
193
201 protected function generatePHPAutoload( $commandName, $filename ) {
202 // No existing JSON file found; update/generate PHP file
203 $content = [];
204
205 // We need to generate a line each rather than exporting the
206 // full array so __DIR__ can be prepended to all the paths
207 $format = "%s => __DIR__ . %s,";
208 foreach ( $this->classes as $path => $contained ) {
209 $exportedPath = var_export( $path, true );
210 foreach ( $contained as $fqcn ) {
211 $content[$fqcn] = sprintf(
212 $format,
213 var_export( $fqcn, true ),
214 $exportedPath
215 );
216 }
217 }
218
219 foreach ( $this->overrides as $fqcn => $path ) {
220 $content[$fqcn] = sprintf(
221 $format,
222 var_export( $fqcn, true ),
223 var_export( $path, true )
224 );
225 }
226
227 // sort for stable output
228 ksort( $content );
229
230 // extensions using this generator are appending to the existing
231 // autoload.
232 if ( $this->variableName === 'wgAutoloadClasses' ) {
233 $op = '+=';
234 } else {
235 $op = '=';
236 }
237
238 $output = implode( "\n\t", $content );
239 return <<<EOD
240<?php
241// This file is generated by $commandName, do not adjust manually
242// phpcs:disable Generic.Files.LineLength
243global \${$this->variableName};
244
245\${$this->variableName} {$op} [
246 {$output}
247];
248
249EOD;
250 }
251
260 public function getAutoload( $commandName = 'AutoloadGenerator' ) {
261 // We need to check whether an extenson.json or skin.json exists or not, and
262 // incase it doesn't, update the autoload.php file.
263
264 $fileinfo = $this->getTargetFileinfo();
265
266 if ( $fileinfo['type'] === self::FILETYPE_JSON ) {
267 return $this->generateJsonAutoload( $fileinfo['filename'] );
268 } else {
269 return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
270 }
271 }
272
281 public function getTargetFileinfo() {
282 $fileinfo = [
283 'filename' => $this->basepath . '/autoload.php',
284 'type' => self::FILETYPE_PHP
285 ];
286 if ( file_exists( $this->basepath . '/extension.json' ) ) {
287 $fileinfo = [
288 'filename' => $this->basepath . '/extension.json',
289 'type' => self::FILETYPE_JSON
290 ];
291 } elseif ( file_exists( $this->basepath . '/skin.json' ) ) {
292 $fileinfo = [
293 'filename' => $this->basepath . '/skin.json',
294 'type' => self::FILETYPE_JSON
295 ];
296 }
297
298 return $fileinfo;
299 }
300
307 protected static function normalizePathSeparator( $path ) {
308 return str_replace( '\\', '/', $path );
309 }
310
320 public function initMediaWikiDefault() {
321 foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
322 $this->readDir( $this->basepath . '/' . $dir );
323 }
324 foreach ( glob( $this->basepath . '/*.php' ) as $file ) {
325 $this->readFile( $file );
326 }
327 }
328}
329
334
338 protected $namespace = '';
339
343 protected $classes;
344
348 protected $startToken;
349
353 protected $tokens;
354
358 protected $alias;
359
364 public function getClasses( $code ) {
365 $this->namespace = '';
366 $this->classes = [];
367 $this->startToken = null;
368 $this->alias = null;
369 $this->tokens = [];
370
371 foreach ( token_get_all( $code ) as $token ) {
372 if ( $this->startToken === null ) {
373 $this->tryBeginExpect( $token );
374 } else {
375 $this->tryEndExpect( $token );
376 }
377 }
378
379 return $this->classes;
380 }
381
387 protected function tryBeginExpect( $token ) {
388 if ( is_string( $token ) ) {
389 return;
390 }
391 // Note: When changing class name discovery logic,
392 // AutoLoaderTest.php may also need to be updated.
393 switch ( $token[0] ) {
394 case T_NAMESPACE:
395 case T_CLASS:
396 case T_INTERFACE:
397 case T_TRAIT:
398 case T_DOUBLE_COLON:
399 $this->startToken = $token;
400 break;
401 case T_STRING:
402 if ( $token[1] === 'class_alias' ) {
403 $this->startToken = $token;
404 $this->alias = [];
405 }
406 }
407 }
408
414 protected function tryEndExpect( $token ) {
415 switch ( $this->startToken[0] ) {
416 case T_DOUBLE_COLON:
417 // Skip over T_CLASS after T_DOUBLE_COLON because this is something like
418 // "self::static" which accesses the class name. It doens't define a new class.
419 $this->startToken = null;
420 break;
421 case T_NAMESPACE:
422 if ( $token === ';' || $token === '{' ) {
423 $this->namespace = $this->implodeTokens() . '\\';
424 } else {
425 $this->tokens[] = $token;
426 }
427 break;
428
429 case T_STRING:
430 if ( $this->alias !== null ) {
431 // Flow 1 - Two string literals:
432 // - T_STRING class_alias
433 // - '('
434 // - T_CONSTANT_ENCAPSED_STRING 'TargetClass'
435 // - ','
436 // - T_WHITESPACE
437 // - T_CONSTANT_ENCAPSED_STRING 'AliasName'
438 // - ')'
439 // Flow 2 - Use of ::class syntax for first parameter
440 // - T_STRING class_alias
441 // - '('
442 // - T_STRING TargetClass
443 // - T_DOUBLE_COLON ::
444 // - T_CLASS class
445 // - ','
446 // - T_WHITESPACE
447 // - T_CONSTANT_ENCAPSED_STRING 'AliasName'
448 // - ')'
449 if ( $token === '(' ) {
450 // Start of a function call to class_alias()
451 $this->alias = [ 'target' => false, 'name' => false ];
452 } elseif ( $token === ',' ) {
453 // Record that we're past the first parameter
454 if ( $this->alias['target'] === false ) {
455 $this->alias['target'] = true;
456 }
457 } elseif ( is_array( $token ) && $token[0] === T_CONSTANT_ENCAPSED_STRING ) {
458 if ( $this->alias['target'] === true ) {
459 // We already saw a first argument, this must be the second.
460 // Strip quotes from the string literal.
461 $this->alias['name'] = substr( $token[1], 1, -1 );
462 }
463 } elseif ( $token === ')' ) {
464 // End of function call
465 $this->classes[] = $this->alias['name'];
466 $this->alias = null;
467 $this->startToken = null;
468 } elseif ( !is_array( $token ) || (
469 $token[0] !== T_STRING &&
470 $token[0] !== T_DOUBLE_COLON &&
471 $token[0] !== T_CLASS &&
472 $token[0] !== T_WHITESPACE
473 ) ) {
474 // Ignore this call to class_alias() - compat/Timestamp.php
475 $this->alias = null;
476 $this->startToken = null;
477 }
478 }
479 break;
480
481 case T_CLASS:
482 case T_INTERFACE:
483 case T_TRAIT:
484 $this->tokens[] = $token;
485 if ( is_array( $token ) && $token[0] === T_STRING ) {
486 $this->classes[] = $this->namespace . $this->implodeTokens();
487 }
488 }
489 }
490
497 protected function implodeTokens() {
498 $content = [];
499 foreach ( $this->tokens as $token ) {
500 $content[] = is_string( $token ) ? $token : $token[1];
501 }
502
503 $this->tokens = [];
504 $this->startToken = null;
505
506 return trim( implode( '', $content ), " \n\t" );
507 }
508}
Accepts a list of files and directories to search for php files and generates $wgAutoloadLocalClasses...
shouldExclude( $path)
Whether the file should be excluded.
string $basepath
Root path of the project being scanned for classes.
setExcludePaths(array $paths)
Directories that should be excluded.
getTargetFileinfo()
Returns the filename of the extension.json of skin.json, if there's any, or otherwise the path to the...
generateJsonAutoload( $filename)
Updates the AutoloadClasses field at the given filename.
__construct( $basepath, $flags=[])
getAutoload( $commandName='AutoloadGenerator')
Returns all known classes as a string, which can be used to put into a target file (e....
forceClassPath( $fqcn, $inputPath)
Force a class to be autoloaded from a specific path, regardless of where or if it was detected.
array $classes
Map of file shortpath to list of FQCN detected within file.
generatePHPAutoload( $commandName, $filename)
Generates a PHP file setting up autoload information.
string $variableName
The global variable to write output to.
initMediaWikiDefault()
Initialize the source files and directories which are used for the MediaWiki default autoloader in {m...
ClassCollector $collector
Helper class extracts class names from php files.
string[] $excludePaths
Directories that should be excluded.
static normalizePathSeparator( $path)
Ensure that Unix-style path separators ("/") are used in the path.
array $overrides
Map of FQCN to relative path(from self::$basepath)
Reads PHP code and returns the FQCN of every class defined within it.
implodeTokens()
Returns the string representation of the tokens within the current expect sequence and resets the seq...
string $namespace
Current namespace.
array $classes
List of FQCN detected in this pass.
tryEndExpect( $token)
Accepts the next token in an expect sequence.
array $startToken
Token from token_get_all() that started an expect sequence.
tryBeginExpect( $token)
Determine if $token begins the next expect sequence.
array $alias
Class alias with target/name fields.
array $tokens
List of tokens that are members of the current expect sequence.
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 will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the classes
Definition globals.txt:43
the array() calling protocol came about after MediaWiki 1.4rc1.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1993
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place $output
Definition hooks.txt:2255
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 modifiable & $code
Definition hooks.txt:865
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
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
if(!is_readable( $file)) $ext
Definition router.php:55