MediaWiki  master
ResourceLoaderFileModule.php
Go to the documentation of this file.
1 <?php
35 
37  protected $localBasePath = '';
38 
40  protected $remoteBasePath = '';
41 
43  protected $templates = [];
44 
52  protected $scripts = [];
53 
61  protected $languageScripts = [];
62 
70  protected $skinScripts = [];
71 
79  protected $debugScripts = [];
80 
88  protected $styles = [];
89 
97  protected $skinStyles = [];
98 
106  protected $packageFiles = null;
107 
112  private $expandedPackageFiles = [];
113 
121  protected $dependencies = [];
122 
126  protected $skipFunction = null;
127 
135  protected $messages = [];
136 
138  protected $group;
139 
141  protected $debugRaw = true;
142 
143  protected $targets = [ 'desktop' ];
144 
146  protected $noflip = false;
147 
152  protected $hasGeneratedStyles = false;
153 
161  protected $localFileRefs = [];
162 
167  protected $missingLocalFileRefs = [];
168 
239  public function __construct(
240  $options = [],
243  ) {
244  // Flag to decide whether to automagically add the mediawiki.template module
245  $hasTemplates = false;
246  // localBasePath and remoteBasePath both have unbelievably long fallback chains
247  // and need to be handled separately.
248  list( $this->localBasePath, $this->remoteBasePath ) =
249  self::extractBasePaths( $options, $localBasePath, $remoteBasePath );
250 
251  // Extract, validate and normalise remaining options
252  foreach ( $options as $member => $option ) {
253  switch ( $member ) {
254  // Lists of file paths
255  case 'scripts':
256  case 'debugScripts':
257  case 'styles':
258  case 'packageFiles':
259  $this->{$member} = is_array( $option ) ? $option : [ $option ];
260  break;
261  case 'templates':
262  $hasTemplates = true;
263  $this->{$member} = is_array( $option ) ? $option : [ $option ];
264  break;
265  // Collated lists of file paths
266  case 'languageScripts':
267  case 'skinScripts':
268  case 'skinStyles':
269  if ( !is_array( $option ) ) {
270  throw new InvalidArgumentException(
271  "Invalid collated file path list error. " .
272  "'$option' given, array expected."
273  );
274  }
275  foreach ( $option as $key => $value ) {
276  if ( !is_string( $key ) ) {
277  throw new InvalidArgumentException(
278  "Invalid collated file path list key error. " .
279  "'$key' given, string expected."
280  );
281  }
282  $this->{$member}[$key] = is_array( $value ) ? $value : [ $value ];
283  }
284  break;
285  case 'deprecated':
286  $this->deprecated = $option;
287  break;
288  // Lists of strings
289  case 'dependencies':
290  case 'messages':
291  case 'targets':
292  // Normalise
293  $option = array_values( array_unique( (array)$option ) );
294  sort( $option );
295 
296  $this->{$member} = $option;
297  break;
298  // Single strings
299  case 'group':
300  case 'skipFunction':
301  $this->{$member} = (string)$option;
302  break;
303  // Single booleans
304  case 'debugRaw':
305  case 'noflip':
306  $this->{$member} = (bool)$option;
307  break;
308  }
309  }
310  if ( isset( $options['scripts'] ) && isset( $options['packageFiles'] ) ) {
311  throw new InvalidArgumentException( "A module may not set both 'scripts' and 'packageFiles'" );
312  }
313  if ( $hasTemplates ) {
314  $this->dependencies[] = 'mediawiki.template';
315  // Ensure relevant template compiler module gets loaded
316  foreach ( $this->templates as $alias => $templatePath ) {
317  if ( is_int( $alias ) ) {
318  $alias = $this->getPath( $templatePath );
319  }
320  $suffix = explode( '.', $alias );
321  $suffix = end( $suffix );
322  $compilerModule = 'mediawiki.template.' . $suffix;
323  if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies ) ) {
324  $this->dependencies[] = $compilerModule;
325  }
326  }
327  }
328  }
329 
341  public static function extractBasePaths(
342  $options = [],
345  ) {
346  global $IP, $wgResourceBasePath;
347 
348  // The different ways these checks are done, and their ordering, look very silly,
349  // but were preserved for backwards-compatibility just in case. Tread lightly.
350 
351  if ( $localBasePath === null ) {
353  }
354  if ( $remoteBasePath === null ) {
356  }
357 
358  if ( isset( $options['remoteExtPath'] ) ) {
359  global $wgExtensionAssetsPath;
360  $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
361  }
362 
363  if ( isset( $options['remoteSkinPath'] ) ) {
364  global $wgStylePath;
365  $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
366  }
367 
368  if ( array_key_exists( 'localBasePath', $options ) ) {
369  $localBasePath = (string)$options['localBasePath'];
370  }
371 
372  if ( array_key_exists( 'remoteBasePath', $options ) ) {
373  $remoteBasePath = (string)$options['remoteBasePath'];
374  }
375 
376  return [ $localBasePath, $remoteBasePath ];
377  }
378 
386  $deprecationScript = $this->getDeprecationInformation();
387  if ( $this->packageFiles !== null ) {
388  $packageFiles = $this->getPackageFiles( $context );
389  if ( $deprecationScript ) {
390  $mainFile =& $packageFiles['files'][$packageFiles['main']];
391  $mainFile['content'] = $deprecationScript . $mainFile['content'];
392  }
393  return $packageFiles;
394  }
395 
396  $files = $this->getScriptFiles( $context );
397  return $deprecationScript . $this->readScriptFiles( $files );
398  }
399 
405  $urls = [];
406  foreach ( $this->getScriptFiles( $context ) as $file ) {
408  $this->getConfig(),
409  $this->getRemotePath( $file )
410  );
411  }
412  return $urls;
413  }
414 
418  public function supportsURLLoading() {
419  // If package files are involved, don't support URL loading, because that breaks
420  // scoped require() functions
421  return $this->debugRaw && !$this->packageFiles;
422  }
423 
431  $styles = $this->readStyleFiles(
432  $this->getStyleFiles( $context ),
433  $this->getFlip( $context ),
434  $context
435  );
436  // Collect referenced files
437  $this->saveFileDependencies( $context, $this->localFileRefs );
438 
439  return $styles;
440  }
441 
447  if ( $this->hasGeneratedStyles ) {
448  // Do the default behaviour of returning a url back to load.php
449  // but with only=styles.
450  return parent::getStyleURLsForDebug( $context );
451  }
452  // Our module consists entirely of real css files,
453  // in debug mode we can load those directly.
454  $urls = [];
455  foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
456  $urls[$mediaType] = [];
457  foreach ( $list as $file ) {
459  $this->getConfig(),
460  $this->getRemotePath( $file )
461  );
462  }
463  }
464  return $urls;
465  }
466 
472  public function getMessages() {
473  return $this->messages;
474  }
475 
481  public function getGroup() {
482  return $this->group;
483  }
484 
491  return $this->dependencies;
492  }
493 
499  public function getSkipFunction() {
500  if ( !$this->skipFunction ) {
501  return null;
502  }
503 
504  $localPath = $this->getLocalPath( $this->skipFunction );
505  if ( !file_exists( $localPath ) ) {
506  throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
507  }
508  $contents = $this->stripBom( file_get_contents( $localPath ) );
509  return $contents;
510  }
511 
520  public function enableModuleContentVersion() {
521  return false;
522  }
523 
532  $files = [];
533 
534  // Flatten style files into $files
535  $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
536  foreach ( $styles as $styleFiles ) {
537  $files = array_merge( $files, $styleFiles );
538  }
539 
540  $skinFiles = self::collateFilePathListByOption(
541  self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
542  'media',
543  'all'
544  );
545  foreach ( $skinFiles as $styleFiles ) {
546  $files = array_merge( $files, $styleFiles );
547  }
548 
549  // Extract file names for package files
550  $expandedPackageFiles = $this->expandPackageFiles( $context );
552  array_filter( array_map( function ( $fileInfo ) {
553  return $fileInfo['filePath'] ?? null;
554  }, $expandedPackageFiles['files'] ) ) :
555  [];
556 
557  // Final merge, this should result in a master list of dependent files
558  $files = array_merge(
559  $files,
561  $this->scripts,
562  $this->templates,
563  $context->getDebug() ? $this->debugScripts : [],
564  $this->getLanguageScripts( $context->getLanguage() ),
565  self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
566  );
567  if ( $this->skipFunction ) {
568  $files[] = $this->skipFunction;
569  }
570  $files = array_map( [ $this, 'getLocalPath' ], $files );
571  // File deps need to be treated separately because they're already prefixed
572  $files = array_merge( $files, $this->getFileDependencies( $context ) );
573  // Filter out any duplicates from getFileDependencies() and others.
574  // Most commonly introduced by compileLessFile(), which always includes the
575  // entry point Less file we already know about.
576  $files = array_values( array_unique( $files ) );
577 
578  // Don't include keys or file paths here, only the hashes. Including that would needlessly
579  // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
580  // Any significant ordering is already detected by the definition summary.
581  return array_map( [ __CLASS__, 'safeFileHash' ], $files );
582  }
583 
591  $summary = parent::getDefinitionSummary( $context );
592 
593  $options = [];
594  foreach ( [
595  // The following properties are omitted because they don't affect the module reponse:
596  // - localBasePath (Per T104950; Changes when absolute directory name changes. If
597  // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
598  // - remoteBasePath (Per T104950)
599  // - dependencies (provided via startup module)
600  // - targets
601  // - group (provided via startup module)
602  'scripts',
603  'debugScripts',
604  'styles',
605  'languageScripts',
606  'skinScripts',
607  'skinStyles',
608  'messages',
609  'templates',
610  'skipFunction',
611  'debugRaw',
612  ] as $member ) {
613  $options[$member] = $this->{$member};
614  }
615 
616  $packageFiles = $this->expandPackageFiles( $context );
617  if ( $packageFiles ) {
618  // Extract the minimum needed:
619  // - The 'main' pointer (included as-is).
620  // - The 'files' array, simplied to only which files exist (the keys of
621  // this array), and something that represents their non-file content.
622  // For packaged files that reflect files directly from disk, the
623  // 'getFileHashes' method tracks this already.
624  // It is important that the keys of the 'files' array are preserved,
625  // as they affect the module output.
626  $packageFiles['files'] = array_map( function ( $fileInfo ) {
627  return $fileInfo['definitionSummary'] ?? ( $fileInfo['content'] ?? null );
628  }, $packageFiles['files'] );
629  }
630 
631  $summary[] = [
632  'options' => $options,
633  'packageFiles' => $packageFiles,
634  'fileHashes' => $this->getFileHashes( $context ),
635  'messageBlob' => $this->getMessageBlob( $context ),
636  ];
637 
638  $lessVars = $this->getLessVars( $context );
639  if ( $lessVars ) {
640  $summary[] = [ 'lessVars' => $lessVars ];
641  }
642 
643  return $summary;
644  }
645 
650  protected function getPath( $path ) {
651  if ( $path instanceof ResourceLoaderFilePath ) {
652  return $path->getPath();
653  }
654 
655  return $path;
656  }
657 
662  protected function getLocalPath( $path ) {
663  if ( $path instanceof ResourceLoaderFilePath ) {
664  return $path->getLocalPath();
665  }
666 
667  return "{$this->localBasePath}/$path";
668  }
669 
674  protected function getRemotePath( $path ) {
675  if ( $path instanceof ResourceLoaderFilePath ) {
676  return $path->getRemotePath();
677  }
678 
679  return "{$this->remoteBasePath}/$path";
680  }
681 
689  public function getStyleSheetLang( $path ) {
690  return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
691  }
692 
698  public static function getPackageFileType( $path ) {
699  if ( preg_match( '/\.json$/i', $path ) ) {
700  return 'data';
701  }
702  return 'script';
703  }
704 
714  protected static function collateFilePathListByOption( array $list, $option, $default ) {
715  $collatedFiles = [];
716  foreach ( (array)$list as $key => $value ) {
717  if ( is_int( $key ) ) {
718  // File name as the value
719  if ( !isset( $collatedFiles[$default] ) ) {
720  $collatedFiles[$default] = [];
721  }
722  $collatedFiles[$default][] = $value;
723  } elseif ( is_array( $value ) ) {
724  // File name as the key, options array as the value
725  $optionValue = $value[$option] ?? $default;
726  if ( !isset( $collatedFiles[$optionValue] ) ) {
727  $collatedFiles[$optionValue] = [];
728  }
729  $collatedFiles[$optionValue][] = $key;
730  }
731  }
732  return $collatedFiles;
733  }
734 
744  protected static function tryForKey( array $list, $key, $fallback = null ) {
745  if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
746  return $list[$key];
747  } elseif ( is_string( $fallback )
748  && isset( $list[$fallback] )
749  && is_array( $list[$fallback] )
750  ) {
751  return $list[$fallback];
752  }
753  return [];
754  }
755 
763  $files = array_merge(
764  $this->scripts,
765  $this->getLanguageScripts( $context->getLanguage() ),
766  self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
767  );
768  if ( $context->getDebug() ) {
769  $files = array_merge( $files, $this->debugScripts );
770  }
771 
772  return array_unique( $files, SORT_REGULAR );
773  }
774 
782  private function getLanguageScripts( $lang ) {
783  $scripts = self::tryForKey( $this->languageScripts, $lang );
784  if ( $scripts ) {
785  return $scripts;
786  }
787  $fallbacks = Language::getFallbacksFor( $lang );
788  foreach ( $fallbacks as $lang ) {
789  $scripts = self::tryForKey( $this->languageScripts, $lang );
790  if ( $scripts ) {
791  return $scripts;
792  }
793  }
794 
795  return [];
796  }
797 
808  return array_merge_recursive(
809  self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
810  self::collateFilePathListByOption(
811  self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
812  'media',
813  'all'
814  )
815  );
816  }
817 
825  protected function getSkinStyleFiles( $skinName ) {
826  return self::collateFilePathListByOption(
827  self::tryForKey( $this->skinStyles, $skinName ),
828  'media',
829  'all'
830  );
831  }
832 
839  protected function getAllSkinStyleFiles() {
840  $styleFiles = [];
841  $internalSkinNames = array_keys( Skin::getSkinNames() );
842  $internalSkinNames[] = 'default';
843 
844  foreach ( $internalSkinNames as $internalSkinName ) {
845  $styleFiles = array_merge_recursive(
846  $styleFiles,
847  $this->getSkinStyleFiles( $internalSkinName )
848  );
849  }
850 
851  return $styleFiles;
852  }
853 
859  public function getAllStyleFiles() {
860  $collatedStyleFiles = array_merge_recursive(
861  self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
862  $this->getAllSkinStyleFiles()
863  );
864 
865  $result = [];
866 
867  foreach ( $collatedStyleFiles as $media => $styleFiles ) {
868  foreach ( $styleFiles as $styleFile ) {
869  $result[] = $this->getLocalPath( $styleFile );
870  }
871  }
872 
873  return $result;
874  }
875 
883  private function readScriptFiles( array $scripts ) {
884  if ( empty( $scripts ) ) {
885  return '';
886  }
887  $js = '';
888  foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
889  $localPath = $this->getLocalPath( $fileName );
890  if ( !file_exists( $localPath ) ) {
891  throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
892  }
893  $contents = $this->stripBom( file_get_contents( $localPath ) );
894  $js .= $contents . "\n";
895  }
896  return $js;
897  }
898 
910  public function readStyleFiles( array $styles, $flip, $context ) {
911  if ( !$styles ) {
912  return [];
913  }
914  foreach ( $styles as $media => $files ) {
915  $uniqueFiles = array_unique( $files, SORT_REGULAR );
916  $styleFiles = [];
917  foreach ( $uniqueFiles as $file ) {
918  $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
919  }
920  $styles[$media] = implode( "\n", $styleFiles );
921  }
922  return $styles;
923  }
924 
937  protected function readStyleFile( $path, $flip, $context ) {
938  $localPath = $this->getLocalPath( $path );
939  $remotePath = $this->getRemotePath( $path );
940  if ( !file_exists( $localPath ) ) {
941  $msg = __METHOD__ . ": style file not found: \"$localPath\"";
942  wfDebugLog( 'resourceloader', $msg );
943  throw new MWException( $msg );
944  }
945 
946  if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
947  $style = $this->compileLessFile( $localPath, $context );
948  $this->hasGeneratedStyles = true;
949  } else {
950  $style = $this->stripBom( file_get_contents( $localPath ) );
951  }
952 
953  if ( $flip ) {
954  $style = CSSJanus::transform( $style, true, false );
955  }
956  $localDir = dirname( $localPath );
957  $remoteDir = dirname( $remotePath );
958  // Get and register local file references
959  $localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
960  foreach ( $localFileRefs as $file ) {
961  if ( file_exists( $file ) ) {
962  $this->localFileRefs[] = $file;
963  } else {
964  $this->missingLocalFileRefs[] = $file;
965  }
966  }
967  // Don't cache this call. remap() ensures data URIs embeds are up to date,
968  // and urls contain correct content hashes in their query string. (T128668)
969  return CSSMin::remap( $style, $localDir, $remoteDir, true );
970  }
971 
977  public function getFlip( $context ) {
978  return $context->getDirection() === 'rtl' && !$this->noflip;
979  }
980 
986  public function getTargets() {
987  return $this->targets;
988  }
989 
996  public function getType() {
997  $canBeStylesOnly = !(
998  // All options except 'styles', 'skinStyles' and 'debugRaw'
999  $this->scripts
1000  || $this->debugScripts
1001  || $this->templates
1002  || $this->languageScripts
1003  || $this->skinScripts
1004  || $this->dependencies
1005  || $this->messages
1006  || $this->skipFunction
1008  );
1009  return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
1010  }
1011 
1024  protected function compileLessFile( $fileName, ResourceLoaderContext $context ) {
1025  static $cache;
1026 
1027  if ( !$cache ) {
1029  }
1030 
1031  $vars = $this->getLessVars( $context );
1032  // Construct a cache key from the LESS file name, and a hash digest
1033  // of the LESS variables used for compilation.
1034  ksort( $vars );
1035  $varsHash = hash( 'md4', serialize( $vars ) );
1036  $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
1037  $cachedCompile = $cache->get( $cacheKey );
1038 
1039  // If we got a cached value, we have to validate it by getting a
1040  // checksum of all the files that were loaded by the parser and
1041  // ensuring it matches the cached entry's.
1042  if ( isset( $cachedCompile['hash'] ) ) {
1043  $contentHash = FileContentsHasher::getFileContentsHash( $cachedCompile['files'] );
1044  if ( $contentHash === $cachedCompile['hash'] ) {
1045  $this->localFileRefs = array_merge( $this->localFileRefs, $cachedCompile['files'] );
1046  return $cachedCompile['css'];
1047  }
1048  }
1049 
1050  $compiler = $context->getResourceLoader()->getLessCompiler( $vars );
1051  $css = $compiler->parseFile( $fileName )->getCss();
1052  $files = $compiler->AllParsedFiles();
1053  $this->localFileRefs = array_merge( $this->localFileRefs, $files );
1054 
1055  // Cache for 24 hours (86400 seconds).
1056  $cache->set( $cacheKey, [
1057  'css' => $css,
1058  'files' => $files,
1059  'hash' => FileContentsHasher::getFileContentsHash( $files ),
1060  ], 3600 * 24 );
1061 
1062  return $css;
1063  }
1064 
1070  public function getTemplates() {
1071  $templates = [];
1072 
1073  foreach ( $this->templates as $alias => $templatePath ) {
1074  // Alias is optional
1075  if ( is_int( $alias ) ) {
1076  $alias = $this->getPath( $templatePath );
1077  }
1078  $localPath = $this->getLocalPath( $templatePath );
1079  if ( file_exists( $localPath ) ) {
1080  $content = file_get_contents( $localPath );
1081  $templates[$alias] = $this->stripBom( $content );
1082  } else {
1083  $msg = __METHOD__ . ": template file not found: \"$localPath\"";
1084  wfDebugLog( 'resourceloader', $msg );
1085  throw new MWException( $msg );
1086  }
1087  }
1088  return $templates;
1089  }
1090 
1110  $hash = $context->getHash();
1111  if ( isset( $this->expandedPackageFiles[$hash] ) ) {
1112  return $this->expandedPackageFiles[$hash];
1113  }
1114  if ( $this->packageFiles === null ) {
1115  return null;
1116  }
1117  $expandedFiles = [];
1118  $mainFile = null;
1119 
1120  foreach ( $this->packageFiles as $alias => $fileInfo ) {
1121  if ( is_string( $fileInfo ) ) {
1122  $fileInfo = [ 'name' => $fileInfo, 'file' => $fileInfo ];
1123  } elseif ( !isset( $fileInfo['name'] ) ) {
1124  $msg = __METHOD__ . ": invalid package file definition for module " .
1125  "\"{$this->getName()}\": 'name' key is required when value is not a string";
1126  wfDebugLog( 'resourceloader', $msg );
1127  throw new MWException( $msg );
1128  }
1129 
1130  // Infer type from alias if needed
1131  $type = $fileInfo['type'] ?? self::getPackageFileType( $fileInfo['name'] );
1132  $expanded = [ 'type' => $type ];
1133  if ( !empty( $fileInfo['main'] ) ) {
1134  $mainFile = $fileInfo['name'];
1135  if ( $type !== 'script' ) {
1136  $msg = __METHOD__ . ": invalid package file definition for module " .
1137  "\"{$this->getName()}\": main file \"$mainFile\" must be of type \"script\", not \"$type\"";
1138  wfDebugLog( 'resourceloader', $msg );
1139  throw new MWException( $msg );
1140  }
1141  }
1142 
1143  // Perform expansions (except 'file' and 'callback'), creating one of these keys:
1144  // - 'content': literal value.
1145  // - 'filePath': content to be read from a file.
1146  // - 'callback': content computed by a callable.
1147  if ( isset( $fileInfo['content'] ) ) {
1148  $expanded['content'] = $fileInfo['content'];
1149  } elseif ( isset( $fileInfo['file'] ) ) {
1150  $expanded['filePath'] = $fileInfo['file'];
1151  } elseif ( isset( $fileInfo['callback'] ) ) {
1152  if ( !is_callable( $fileInfo['callback'] ) ) {
1153  $msg = __METHOD__ . ": invalid callback for package file \"{$fileInfo['name']}\"" .
1154  " in module \"{$this->getName()}\"";
1155  wfDebugLog( 'resourceloader', $msg );
1156  throw new MWException( $msg );
1157  }
1158  if ( isset( $fileInfo['versionCallback'] ) ) {
1159  if ( !is_callable( $fileInfo['versionCallback'] ) ) {
1160  throw new MWException( __METHOD__ . ": invalid versionCallback for file" .
1161  " \"{$fileInfo['name']}\" in module \"{$this->getName()}\"" );
1162  }
1163  $expanded['definitionSummary'] =
1164  ( $fileInfo['versionCallback'] )( $context, $this->getConfig() );
1165  // Don't invoke 'callback' here as it may be expensive (T223260).
1166  $expanded['callback'] = $fileInfo['callback'];
1167  } else {
1168  $expanded['content'] = ( $fileInfo['callback'] )( $context, $this->getConfig() );
1169  }
1170  } elseif ( isset( $fileInfo['config'] ) ) {
1171  if ( $type !== 'data' ) {
1172  $msg = __METHOD__ . ": invalid use of \"config\" for package file \"{$fileInfo['name']}\" " .
1173  "in module \"{$this->getName()}\": type must be \"data\" but is \"$type\"";
1174  wfDebugLog( 'resourceloader', $msg );
1175  throw new MWException( $msg );
1176  }
1177  $expandedConfig = [];
1178  foreach ( $fileInfo['config'] as $key => $var ) {
1179  $expandedConfig[ is_numeric( $key ) ? $var : $key ] = $this->getConfig()->get( $var );
1180  }
1181  $expanded['content'] = $expandedConfig;
1182  } elseif ( !empty( $fileInfo['main'] ) ) {
1183  // [ 'name' => 'foo.js', 'main' => true ] is shorthand
1184  $expanded['filePath'] = $fileInfo['name'];
1185  } else {
1186  $msg = __METHOD__ . ": invalid package file definition for \"{$fileInfo['name']}\" " .
1187  "in module \"{$this->getName()}\": one of \"file\", \"content\", \"callback\" or \"config\" " .
1188  "must be set";
1189  wfDebugLog( 'resourceloader', $msg );
1190  throw new MWException( $msg );
1191  }
1192 
1193  $expandedFiles[$fileInfo['name']] = $expanded;
1194  }
1195 
1196  if ( $expandedFiles && $mainFile === null ) {
1197  // The first package file that is a script is the main file
1198  foreach ( $expandedFiles as $path => &$file ) {
1199  if ( $file['type'] === 'script' ) {
1200  $mainFile = $path;
1201  break;
1202  }
1203  }
1204  }
1205 
1206  $result = [
1207  'main' => $mainFile,
1208  'files' => $expandedFiles
1209  ];
1210 
1211  $this->expandedPackageFiles[$hash] = $result;
1212  return $result;
1213  }
1214 
1221  if ( $this->packageFiles === null ) {
1222  return null;
1223  }
1224  $expandedPackageFiles = $this->expandPackageFiles( $context );
1225 
1226  // Expand file contents
1227  foreach ( $expandedPackageFiles['files'] as &$fileInfo ) {
1228  // Turn any 'filePath' or 'callback' key into actual 'content',
1229  // and remove the key after that.
1230  if ( isset( $fileInfo['filePath'] ) ) {
1231  $localPath = $this->getLocalPath( $fileInfo['filePath'] );
1232  if ( !file_exists( $localPath ) ) {
1233  $msg = __METHOD__ . ": package file not found: \"$localPath\"" .
1234  " in module \"{$this->getName()}\"";
1235  wfDebugLog( 'resourceloader', $msg );
1236  throw new MWException( $msg );
1237  }
1238  $content = $this->stripBom( file_get_contents( $localPath ) );
1239  if ( $fileInfo['type'] === 'data' ) {
1240  $content = json_decode( $content );
1241  }
1242  $fileInfo['content'] = $content;
1243  unset( $fileInfo['filePath'] );
1244  } elseif ( isset( $fileInfo['callback'] ) ) {
1245  $fileInfo['content'] = ( $fileInfo['callback'] )( $context, $this->getConfig() );
1246  unset( $fileInfo['callback'] );
1247  }
1248 
1249  // Not needed for client response, exists for getDefinitionSummary().
1250  unset( $fileInfo['definitionSummary'] );
1251  }
1252 
1253  return $expandedPackageFiles;
1254  }
1255 
1266  protected function stripBom( $input ) {
1267  if ( substr_compare( "\xef\xbb\xbf", $input, 0, 3 ) === 0 ) {
1268  return substr( $input, 3 );
1269  }
1270  return $input;
1271  }
1272 }
getScriptURLsForDebug(ResourceLoaderContext $context)
getFlip( $context)
Get whether CSS for this module should be flipped.
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
getDeprecationInformation()
Get JS representing deprecation information for the current module if available.
if(is_array( $mode)) switch( $mode) $input
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
serialize()
array $dependencies
List of modules this module depends on.
$IP
Definition: WebStart.php:41
array $skinStyles
List of paths to CSS files to include when using specific skins.
static getFileContentsHash( $filePaths, $algo='md4')
Get a hash of the combined contents of one or more files, either by retrieving a previously-computed ...
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
getStyleFiles(ResourceLoaderContext $context)
Get a list of file paths for all styles in this module, in order of proper inclusion.
array $packageFiles
List of packaged files to make available through require()
static getPackageFileType( $path)
Infer the file type from a package file path.
if(!isset( $args[0])) $lang
getMessageBlob(ResourceLoaderContext $context)
Get the hash of the message blob.
static getSkinNames()
Fetch the set of available skins.
Definition: Skin.php:57
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:175
$value
getAllStyleFiles()
Returns all style files and all skin style files used by this module.
readStyleFiles(array $styles, $flip, $context)
Get the contents of a list of CSS files.
getSkipFunction()
Get the skip function.
compileLessFile( $fileName, ResourceLoaderContext $context)
Compile a LESS file into CSS.
array $debugScripts
List of paths to JavaScript files to include in debug mode.
The package scripts
Definition: README.txt:1
static remap( $source, $local, $remote, $embedData=true)
Remaps CSS URL paths and automatically embeds data URIs for CSS rules or url() values preceded by an ...
Definition: CSSMin.php:239
getStyles(ResourceLoaderContext $context)
Get all styles for a given context.
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=(\*-\*)") 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. '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 '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 since 1.28! 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:1970
array $templates
Saves a list of the templates named by the modules.
passed in as a query string parameter to the various URLs constructed here(i.e. $prevlink) $ldel you ll need to handle error messages
Definition: hooks.txt:1268
getLessVars(ResourceLoaderContext $context)
Get module-specific LESS variables, if any.
stripBom( $input)
Takes an input string and removes the UTF-8 BOM character if present.
getFileHashes(ResourceLoaderContext $context)
Helper method for getDefinitionSummary.
bool $debugRaw
Link to raw files in debug mode.
$wgStylePath
The URL path of the skins directory.
getFileDependencies(ResourceLoaderContext $context)
Get the files this module depends on indirectly for a given skin.
enableModuleContentVersion()
Disable module content versioning.
$css
string $skipFunction
File name containing the body of the skip function.
bool $hasGeneratedStyles
Whether getStyleURLsForDebug should return raw file paths, or return load.php urls.
array $contents
Map of (context hash => cached module content)
static transformResourcePath(Config $config, $path)
Transform path to web-accessible static resource.
getDependencies(ResourceLoaderContext $context=null)
Gets list of names of modules this module depends on.
ResourceLoader module based on local JavaScript/CSS files.
readScriptFiles(array $scripts)
Get the contents of a list of JavaScript files.
string $group
Name of group to load this module in.
static string [] static getLocalFileReferences( $source, $path)
Get a list of local files referenced in a stylesheet (includes non-existent files).
Definition: CSSMin.php:63
array $localFileRefs
Place where readStyleFile() tracks file dependencies.
string $localBasePath
Local base path, see __construct()
$cache
Definition: mcc.php:33
$wgResourceBasePath
The default &#39;remoteBasePath&#39; value for instances of ResourceLoaderFileModule.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1972
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
getStyleSheetLang( $path)
Infer the stylesheet language from a stylesheet file path.
__construct( $options=[], $localBasePath=null, $remoteBasePath=null)
Constructs a new module from an options array.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
getSkinStyleFiles( $skinName)
Gets a list of file paths for all skin styles in the module used by the skin.
getTemplates()
Takes named templates by the module and returns an array mapping.
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
getGroup()
Gets the name of the group this module should be loaded in.
An object to represent a path to a JavaScript/CSS file, along with a remote and local base path...
getMessages()
Gets list of message keys used by this module.
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
getStyleURLsForDebug(ResourceLoaderContext $context)
string $remoteBasePath
Remote base path, see __construct()
$fallback
Definition: MessagesAb.php:11
array $messages
List of message keys used by this module.
static extractBasePaths( $options=[], $localBasePath=null, $remoteBasePath=null)
Extract a pair of local and remote base paths from module definition information. ...
getAllSkinStyleFiles()
Gets a list of file paths for all skin style files in the module, for all available skins...
expandPackageFiles(ResourceLoaderContext $context)
Internal helper for use by getPackageFiles(), getFileHashes() and getDefinitionSummary().
array $scripts
List of paths to JavaScript files to always include.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
$wgExtensionAssetsPath
The URL path of the extensions directory.
static getFallbacksFor( $code, $mode=self::MESSAGES_FALLBACKS)
Get the ordered list of fallback languages.
Definition: Language.php:4514
array $languageScripts
List of JavaScript files to include when using a specific language.
getTargets()
Get target(s) for the module, eg [&#39;desktop&#39;] or [&#39;desktop&#39;, &#39;mobile&#39;].
const CACHE_ANYTHING
Definition: Defines.php:81
getType()
Get the module&#39;s load type.
getScript(ResourceLoaderContext $context)
Gets all scripts for a given context concatenated together.
getPackageFiles(ResourceLoaderContext $context)
Resolves the package files defintion and generates the content of each package file.
getLanguageScripts( $lang)
Get the set of language scripts for the given language, possibly using a fallback language...
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2621
readStyleFile( $path, $flip, $context)
Reads a style file.
array $missingLocalFileRefs
Place where readStyleFile() tracks file dependencies for non-existent files.
static getLocalServerInstance( $fallback=CACHE_NONE)
Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
getHash()
All factors that uniquely identify this request, except &#39;modules&#39;.
array $styles
List of paths to CSS files to always include.
static collateFilePathListByOption(array $list, $option, $default)
Collates file paths by option (where provided).
array $skinScripts
List of JavaScript files to include when using a specific skin.
getScriptFiles(ResourceLoaderContext $context)
Get a list of script file paths for this module, in order of proper execution.
saveFileDependencies(ResourceLoaderContext $context, $localFileRefs)
Set the files this module depends on indirectly for a given skin.
array $expandedPackageFiles
Expanded versions of $packageFiles, lazy-computed by expandPackageFiles(); keyed by context hash...
$content
Definition: pageupdater.txt:72
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2205
bool $noflip
Whether CSSJanus flipping should be skipped for this module.
Object passed around to modules which contains information about the state of a specific loader reque...
static tryForKey(array $list, $key, $fallback=null)
Get a list of element that match a key, optionally using a fallback key.