MediaWiki  1.33.0
ResourceLoaderFileModule.php
Go to the documentation of this file.
1 <?php
29 
31  protected $localBasePath = '';
32 
34  protected $remoteBasePath = '';
35 
37  protected $templates = [];
38 
46  protected $scripts = [];
47 
55  protected $languageScripts = [];
56 
64  protected $skinScripts = [];
65 
73  protected $debugScripts = [];
74 
82  protected $styles = [];
83 
91  protected $skinStyles = [];
92 
100  protected $packageFiles = null;
101 
106  private $expandedPackageFiles = [];
107 
115  protected $dependencies = [];
116 
120  protected $skipFunction = null;
121 
129  protected $messages = [];
130 
132  protected $group;
133 
135  protected $debugRaw = true;
136 
138  protected $raw = false;
139 
140  protected $targets = [ 'desktop' ];
141 
143  protected $noflip = false;
144 
149  protected $hasGeneratedStyles = false;
150 
158  protected $localFileRefs = [];
159 
164  protected $missingLocalFileRefs = [];
165 
236  public function __construct(
237  $options = [],
238  $localBasePath = null,
239  $remoteBasePath = null
240  ) {
241  // Flag to decide whether to automagically add the mediawiki.template module
242  $hasTemplates = false;
243  // localBasePath and remoteBasePath both have unbelievably long fallback chains
244  // and need to be handled separately.
245  list( $this->localBasePath, $this->remoteBasePath ) =
247 
248  // Extract, validate and normalise remaining options
249  foreach ( $options as $member => $option ) {
250  switch ( $member ) {
251  // Lists of file paths
252  case 'scripts':
253  case 'debugScripts':
254  case 'styles':
255  case 'packageFiles':
256  $this->{$member} = (array)$option;
257  break;
258  case 'templates':
259  $hasTemplates = true;
260  $this->{$member} = (array)$option;
261  break;
262  // Collated lists of file paths
263  case 'languageScripts':
264  case 'skinScripts':
265  case 'skinStyles':
266  if ( !is_array( $option ) ) {
267  throw new InvalidArgumentException(
268  "Invalid collated file path list error. " .
269  "'$option' given, array expected."
270  );
271  }
272  foreach ( $option as $key => $value ) {
273  if ( !is_string( $key ) ) {
274  throw new InvalidArgumentException(
275  "Invalid collated file path list key error. " .
276  "'$key' given, string expected."
277  );
278  }
279  $this->{$member}[$key] = (array)$value;
280  }
281  break;
282  case 'deprecated':
283  $this->deprecated = $option;
284  break;
285  // Lists of strings
286  case 'dependencies':
287  case 'messages':
288  case 'targets':
289  // Normalise
290  $option = array_values( array_unique( (array)$option ) );
291  sort( $option );
292 
293  $this->{$member} = $option;
294  break;
295  // Single strings
296  case 'group':
297  case 'skipFunction':
298  $this->{$member} = (string)$option;
299  break;
300  // Single booleans
301  case 'debugRaw':
302  case 'raw':
303  case 'noflip':
304  $this->{$member} = (bool)$option;
305  break;
306  }
307  }
308  if ( isset( $options['scripts'] ) && isset( $options['packageFiles'] ) ) {
309  throw new InvalidArgumentException( "A module may not set both 'scripts' and 'packageFiles'" );
310  }
311  if ( $hasTemplates ) {
312  $this->dependencies[] = 'mediawiki.template';
313  // Ensure relevant template compiler module gets loaded
314  foreach ( $this->templates as $alias => $templatePath ) {
315  if ( is_int( $alias ) ) {
316  $alias = $templatePath;
317  }
318  $suffix = explode( '.', $alias );
319  $suffix = end( $suffix );
320  $compilerModule = 'mediawiki.template.' . $suffix;
321  if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies ) ) {
322  $this->dependencies[] = $compilerModule;
323  }
324  }
325  }
326  }
327 
339  public static function extractBasePaths(
340  $options = [],
341  $localBasePath = null,
342  $remoteBasePath = null
343  ) {
344  global $IP, $wgResourceBasePath;
345 
346  // The different ways these checks are done, and their ordering, look very silly,
347  // but were preserved for backwards-compatibility just in case. Tread lightly.
348 
349  if ( $localBasePath === null ) {
351  }
352  if ( $remoteBasePath === null ) {
354  }
355 
356  if ( isset( $options['remoteExtPath'] ) ) {
357  global $wgExtensionAssetsPath;
358  $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
359  }
360 
361  if ( isset( $options['remoteSkinPath'] ) ) {
362  global $wgStylePath;
363  $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
364  }
365 
366  if ( array_key_exists( 'localBasePath', $options ) ) {
367  $localBasePath = (string)$options['localBasePath'];
368  }
369 
370  if ( array_key_exists( 'remoteBasePath', $options ) ) {
371  $remoteBasePath = (string)$options['remoteBasePath'];
372  }
373 
374  return [ $localBasePath, $remoteBasePath ];
375  }
376 
384  $deprecationScript = $this->getDeprecationInformation();
385  if ( $this->packageFiles !== null ) {
386  $packageFiles = $this->getPackageFiles( $context );
387  if ( $deprecationScript ) {
388  $mainFile =& $packageFiles['files'][$packageFiles['main']];
389  $mainFile['content'] = $deprecationScript . $mainFile['content'];
390  }
391  return $packageFiles;
392  }
393 
394  $files = $this->getScriptFiles( $context );
395  return $deprecationScript . $this->readScriptFiles( $files );
396  }
397 
403  $urls = [];
404  foreach ( $this->getScriptFiles( $context ) as $file ) {
405  $urls[] = OutputPage::transformResourcePath(
406  $this->getConfig(),
407  $this->getRemotePath( $file )
408  );
409  }
410  return $urls;
411  }
412 
416  public function supportsURLLoading() {
417  // If package files are involved, don't support URL loading, because that breaks
418  // scoped require() functions
419  return $this->debugRaw && !$this->packageFiles;
420  }
421 
429  $styles = $this->readStyleFiles(
430  $this->getStyleFiles( $context ),
431  $this->getFlip( $context ),
432  $context
433  );
434  // Collect referenced files
435  $this->saveFileDependencies( $context, $this->localFileRefs );
436 
437  return $styles;
438  }
439 
445  if ( $this->hasGeneratedStyles ) {
446  // Do the default behaviour of returning a url back to load.php
447  // but with only=styles.
448  return parent::getStyleURLsForDebug( $context );
449  }
450  // Our module consists entirely of real css files,
451  // in debug mode we can load those directly.
452  $urls = [];
453  foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
454  $urls[$mediaType] = [];
455  foreach ( $list as $file ) {
456  $urls[$mediaType][] = OutputPage::transformResourcePath(
457  $this->getConfig(),
458  $this->getRemotePath( $file )
459  );
460  }
461  }
462  return $urls;
463  }
464 
470  public function getMessages() {
471  return $this->messages;
472  }
473 
479  public function getGroup() {
480  return $this->group;
481  }
482 
488  public function getDependencies( ResourceLoaderContext $context = null ) {
489  return $this->dependencies;
490  }
491 
497  public function getSkipFunction() {
498  if ( !$this->skipFunction ) {
499  return null;
500  }
501 
502  $localPath = $this->getLocalPath( $this->skipFunction );
503  if ( !file_exists( $localPath ) ) {
504  throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
505  }
506  $contents = $this->stripBom( file_get_contents( $localPath ) );
507  return $contents;
508  }
509 
513  public function isRaw() {
514  return $this->raw;
515  }
516 
525  public function enableModuleContentVersion() {
526  return false;
527  }
528 
537  $files = [];
538 
539  // Flatten style files into $files
540  $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
541  foreach ( $styles as $styleFiles ) {
542  $files = array_merge( $files, $styleFiles );
543  }
544 
546  self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
547  'media',
548  'all'
549  );
550  foreach ( $skinFiles as $styleFiles ) {
551  $files = array_merge( $files, $styleFiles );
552  }
553 
554  // Extract file names for package files
555  $expandedPackageFiles = $this->expandPackageFiles( $context );
557  array_filter( array_map( function ( $fileInfo ) {
558  return $fileInfo['filePath'] ?? null;
559  }, $expandedPackageFiles['files'] ) ) :
560  [];
561 
562  // Final merge, this should result in a master list of dependent files
563  $files = array_merge(
564  $files,
566  $this->scripts,
567  $this->templates,
568  $context->getDebug() ? $this->debugScripts : [],
569  $this->getLanguageScripts( $context->getLanguage() ),
570  self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
571  );
572  if ( $this->skipFunction ) {
573  $files[] = $this->skipFunction;
574  }
575  $files = array_map( [ $this, 'getLocalPath' ], $files );
576  // File deps need to be treated separately because they're already prefixed
577  $files = array_merge( $files, $this->getFileDependencies( $context ) );
578  // Filter out any duplicates from getFileDependencies() and others.
579  // Most commonly introduced by compileLessFile(), which always includes the
580  // entry point Less file we already know about.
581  $files = array_values( array_unique( $files ) );
582 
583  // Don't include keys or file paths here, only the hashes. Including that would needlessly
584  // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
585  // Any significant ordering is already detected by the definition summary.
586  return array_map( [ __CLASS__, 'safeFileHash' ], $files );
587  }
588 
596  $summary = parent::getDefinitionSummary( $context );
597 
598  $options = [];
599  foreach ( [
600  // The following properties are omitted because they don't affect the module reponse:
601  // - localBasePath (Per T104950; Changes when absolute directory name changes. If
602  // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
603  // - remoteBasePath (Per T104950)
604  // - dependencies (provided via startup module)
605  // - targets
606  // - group (provided via startup module)
607  'scripts',
608  'debugScripts',
609  'styles',
610  'languageScripts',
611  'skinScripts',
612  'skinStyles',
613  'messages',
614  'templates',
615  'skipFunction',
616  'debugRaw',
617  'raw',
618  ] as $member ) {
619  $options[$member] = $this->{$member};
620  };
621 
622  $summary[] = [
623  'options' => $options,
624  'packageFiles' => $this->expandPackageFiles( $context ),
625  'fileHashes' => $this->getFileHashes( $context ),
626  'messageBlob' => $this->getMessageBlob( $context ),
627  ];
628 
629  $lessVars = $this->getLessVars( $context );
630  if ( $lessVars ) {
631  $summary[] = [ 'lessVars' => $lessVars ];
632  }
633 
634  return $summary;
635  }
636 
641  protected function getLocalPath( $path ) {
642  if ( $path instanceof ResourceLoaderFilePath ) {
643  return $path->getLocalPath();
644  }
645 
646  return "{$this->localBasePath}/$path";
647  }
648 
653  protected function getRemotePath( $path ) {
654  if ( $path instanceof ResourceLoaderFilePath ) {
655  return $path->getRemotePath();
656  }
657 
658  return "{$this->remoteBasePath}/$path";
659  }
660 
668  public function getStyleSheetLang( $path ) {
669  return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
670  }
671 
677  public static function getPackageFileType( $path ) {
678  if ( preg_match( '/\.json$/i', $path ) ) {
679  return 'data';
680  }
681  return 'script';
682  }
683 
693  protected static function collateFilePathListByOption( array $list, $option, $default ) {
694  $collatedFiles = [];
695  foreach ( (array)$list as $key => $value ) {
696  if ( is_int( $key ) ) {
697  // File name as the value
698  if ( !isset( $collatedFiles[$default] ) ) {
699  $collatedFiles[$default] = [];
700  }
701  $collatedFiles[$default][] = $value;
702  } elseif ( is_array( $value ) ) {
703  // File name as the key, options array as the value
704  $optionValue = $value[$option] ?? $default;
705  if ( !isset( $collatedFiles[$optionValue] ) ) {
706  $collatedFiles[$optionValue] = [];
707  }
708  $collatedFiles[$optionValue][] = $key;
709  }
710  }
711  return $collatedFiles;
712  }
713 
723  protected static function tryForKey( array $list, $key, $fallback = null ) {
724  if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
725  return $list[$key];
726  } elseif ( is_string( $fallback )
727  && isset( $list[$fallback] )
728  && is_array( $list[$fallback] )
729  ) {
730  return $list[$fallback];
731  }
732  return [];
733  }
734 
742  $files = array_merge(
743  $this->scripts,
744  $this->getLanguageScripts( $context->getLanguage() ),
745  self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
746  );
747  if ( $context->getDebug() ) {
748  $files = array_merge( $files, $this->debugScripts );
749  }
750 
751  return array_unique( $files, SORT_REGULAR );
752  }
753 
761  private function getLanguageScripts( $lang ) {
762  $scripts = self::tryForKey( $this->languageScripts, $lang );
763  if ( $scripts ) {
764  return $scripts;
765  }
766  $fallbacks = Language::getFallbacksFor( $lang );
767  foreach ( $fallbacks as $lang ) {
768  $scripts = self::tryForKey( $this->languageScripts, $lang );
769  if ( $scripts ) {
770  return $scripts;
771  }
772  }
773 
774  return [];
775  }
776 
787  return array_merge_recursive(
788  self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
789  self::collateFilePathListByOption(
790  self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
791  'media',
792  'all'
793  )
794  );
795  }
796 
804  protected function getSkinStyleFiles( $skinName ) {
806  self::tryForKey( $this->skinStyles, $skinName ),
807  'media',
808  'all'
809  );
810  }
811 
818  protected function getAllSkinStyleFiles() {
819  $styleFiles = [];
820  $internalSkinNames = array_keys( Skin::getSkinNames() );
821  $internalSkinNames[] = 'default';
822 
823  foreach ( $internalSkinNames as $internalSkinName ) {
824  $styleFiles = array_merge_recursive(
825  $styleFiles,
826  $this->getSkinStyleFiles( $internalSkinName )
827  );
828  }
829 
830  return $styleFiles;
831  }
832 
838  public function getAllStyleFiles() {
839  $collatedStyleFiles = array_merge_recursive(
840  self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
841  $this->getAllSkinStyleFiles()
842  );
843 
844  $result = [];
845 
846  foreach ( $collatedStyleFiles as $media => $styleFiles ) {
847  foreach ( $styleFiles as $styleFile ) {
848  $result[] = $this->getLocalPath( $styleFile );
849  }
850  }
851 
852  return $result;
853  }
854 
862  private function readScriptFiles( array $scripts ) {
863  if ( empty( $scripts ) ) {
864  return '';
865  }
866  $js = '';
867  foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
868  $localPath = $this->getLocalPath( $fileName );
869  if ( !file_exists( $localPath ) ) {
870  throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
871  }
872  $contents = $this->stripBom( file_get_contents( $localPath ) );
873  $js .= $contents . "\n";
874  }
875  return $js;
876  }
877 
889  public function readStyleFiles( array $styles, $flip, $context ) {
890  if ( !$styles ) {
891  return [];
892  }
893  foreach ( $styles as $media => $files ) {
894  $uniqueFiles = array_unique( $files, SORT_REGULAR );
895  $styleFiles = [];
896  foreach ( $uniqueFiles as $file ) {
897  $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
898  }
899  $styles[$media] = implode( "\n", $styleFiles );
900  }
901  return $styles;
902  }
903 
916  protected function readStyleFile( $path, $flip, $context ) {
917  $localPath = $this->getLocalPath( $path );
918  $remotePath = $this->getRemotePath( $path );
919  if ( !file_exists( $localPath ) ) {
920  $msg = __METHOD__ . ": style file not found: \"$localPath\"";
921  wfDebugLog( 'resourceloader', $msg );
922  throw new MWException( $msg );
923  }
924 
925  if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
926  $style = $this->compileLessFile( $localPath, $context );
927  $this->hasGeneratedStyles = true;
928  } else {
929  $style = $this->stripBom( file_get_contents( $localPath ) );
930  }
931 
932  if ( $flip ) {
933  $style = CSSJanus::transform( $style, true, false );
934  }
935  $localDir = dirname( $localPath );
936  $remoteDir = dirname( $remotePath );
937  // Get and register local file references
938  $localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
939  foreach ( $localFileRefs as $file ) {
940  if ( file_exists( $file ) ) {
941  $this->localFileRefs[] = $file;
942  } else {
943  $this->missingLocalFileRefs[] = $file;
944  }
945  }
946  // Don't cache this call. remap() ensures data URIs embeds are up to date,
947  // and urls contain correct content hashes in their query string. (T128668)
948  return CSSMin::remap( $style, $localDir, $remoteDir, true );
949  }
950 
956  public function getFlip( $context ) {
957  return $context->getDirection() === 'rtl' && !$this->noflip;
958  }
959 
965  public function getTargets() {
966  return $this->targets;
967  }
968 
975  public function getType() {
976  $canBeStylesOnly = !(
977  // All options except 'styles', 'skinStyles' and 'debugRaw'
978  $this->scripts
979  || $this->debugScripts
980  || $this->templates
981  || $this->languageScripts
982  || $this->skinScripts
983  || $this->dependencies
984  || $this->messages
985  || $this->skipFunction
986  || $this->raw
987  );
988  return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
989  }
990 
1003  protected function compileLessFile( $fileName, ResourceLoaderContext $context ) {
1004  static $cache;
1005 
1006  if ( !$cache ) {
1008  }
1009 
1010  $vars = $this->getLessVars( $context );
1011  // Construct a cache key from the LESS file name, and a hash digest
1012  // of the LESS variables used for compilation.
1013  ksort( $vars );
1014  $varsHash = hash( 'md4', serialize( $vars ) );
1015  $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
1016  $cachedCompile = $cache->get( $cacheKey );
1017 
1018  // If we got a cached value, we have to validate it by getting a
1019  // checksum of all the files that were loaded by the parser and
1020  // ensuring it matches the cached entry's.
1021  if ( isset( $cachedCompile['hash'] ) ) {
1022  $contentHash = FileContentsHasher::getFileContentsHash( $cachedCompile['files'] );
1023  if ( $contentHash === $cachedCompile['hash'] ) {
1024  $this->localFileRefs = array_merge( $this->localFileRefs, $cachedCompile['files'] );
1025  return $cachedCompile['css'];
1026  }
1027  }
1028 
1029  $compiler = $context->getResourceLoader()->getLessCompiler( $vars );
1030  $css = $compiler->parseFile( $fileName )->getCss();
1031  $files = $compiler->AllParsedFiles();
1032  $this->localFileRefs = array_merge( $this->localFileRefs, $files );
1033 
1034  // Cache for 24 hours (86400 seconds).
1035  $cache->set( $cacheKey, [
1036  'css' => $css,
1037  'files' => $files,
1038  'hash' => FileContentsHasher::getFileContentsHash( $files ),
1039  ], 3600 * 24 );
1040 
1041  return $css;
1042  }
1043 
1049  public function getTemplates() {
1050  $templates = [];
1051 
1052  foreach ( $this->templates as $alias => $templatePath ) {
1053  // Alias is optional
1054  if ( is_int( $alias ) ) {
1055  $alias = $templatePath;
1056  }
1057  $localPath = $this->getLocalPath( $templatePath );
1058  if ( file_exists( $localPath ) ) {
1059  $content = file_get_contents( $localPath );
1060  $templates[$alias] = $this->stripBom( $content );
1061  } else {
1062  $msg = __METHOD__ . ": template file not found: \"$localPath\"";
1063  wfDebugLog( 'resourceloader', $msg );
1064  throw new MWException( $msg );
1065  }
1066  }
1067  return $templates;
1068  }
1069 
1083  $hash = $context->getHash();
1084  if ( isset( $this->expandedPackageFiles[$hash] ) ) {
1085  return $this->expandedPackageFiles[$hash];
1086  }
1087  if ( $this->packageFiles === null ) {
1088  return null;
1089  }
1090  $expandedFiles = [];
1091  $mainFile = null;
1092 
1093  foreach ( $this->packageFiles as $alias => $fileInfo ) {
1094  if ( is_string( $fileInfo ) ) {
1095  $fileInfo = [ 'name' => $fileInfo, 'file' => $fileInfo ];
1096  } elseif ( !isset( $fileInfo['name'] ) ) {
1097  $msg = __METHOD__ . ": invalid package file definition for module " .
1098  "\"{$this->getName()}\": 'name' key is required when value is not a string";
1099  wfDebugLog( 'resourceloader', $msg );
1100  throw new MWException( $msg );
1101  }
1102 
1103  // Infer type from alias if needed
1104  $type = $fileInfo['type'] ?? self::getPackageFileType( $fileInfo['name'] );
1105  $expanded = [ 'type' => $type ];
1106  if ( !empty( $fileInfo['main'] ) ) {
1107  $mainFile = $fileInfo['name'];
1108  if ( $type !== 'script' ) {
1109  $msg = __METHOD__ . ": invalid package file definition for module " .
1110  "\"{$this->getName()}\": main file \"$mainFile\" must be of type \"script\", not \"$type\"";
1111  wfDebugLog( 'resourceloader', $msg );
1112  throw new MWException( $msg );
1113  }
1114  }
1115 
1116  if ( isset( $fileInfo['content'] ) ) {
1117  $expanded['content'] = $fileInfo['content'];
1118  } elseif ( isset( $fileInfo['file'] ) ) {
1119  $expanded['filePath'] = $fileInfo['file'];
1120  } elseif ( isset( $fileInfo['callback'] ) ) {
1121  if ( is_callable( $fileInfo['callback'] ) ) {
1122  $expanded['content'] = $fileInfo['callback']( $context );
1123  } else {
1124  $msg = __METHOD__ . ": invalid callback for package file \"{$fileInfo['name']}\"" .
1125  " in module \"{$this->getName()}\"";
1126  wfDebugLog( 'resourceloader', $msg );
1127  throw new MWException( $msg );
1128  }
1129  } elseif ( isset( $fileInfo['config'] ) ) {
1130  if ( $type !== 'data' ) {
1131  $msg = __METHOD__ . ": invalid use of \"config\" for package file \"{$fileInfo['name']}\" " .
1132  "in module \"{$this->getName()}\": type must be \"data\" but is \"$type\"";
1133  wfDebugLog( 'resourceloader', $msg );
1134  throw new MWException( $msg );
1135  }
1136  $expandedConfig = [];
1137  foreach ( $fileInfo['config'] as $key => $var ) {
1138  $expandedConfig[ is_numeric( $key ) ? $var : $key ] = $this->getConfig()->get( $var );
1139  }
1140  $expanded['content'] = $expandedConfig;
1141  } elseif ( !empty( $fileInfo['main'] ) ) {
1142  // [ 'name' => 'foo.js', 'main' => true ] is shorthand
1143  $expanded['filePath'] = $fileInfo['name'];
1144  } else {
1145  $msg = __METHOD__ . ": invalid package file definition for \"{$fileInfo['name']}\" " .
1146  "in module \"{$this->getName()}\": one of \"file\", \"content\", \"callback\" or \"config\" " .
1147  "must be set";
1148  wfDebugLog( 'resourceloader', $msg );
1149  throw new MWException( $msg );
1150  }
1151 
1152  $expandedFiles[$fileInfo['name']] = $expanded;
1153  }
1154 
1155  if ( $expandedFiles && $mainFile === null ) {
1156  // The first package file that is a script is the main file
1157  foreach ( $expandedFiles as $path => &$file ) {
1158  if ( $file['type'] === 'script' ) {
1159  $mainFile = $path;
1160  break;
1161  }
1162  }
1163  }
1164 
1165  $result = [
1166  'main' => $mainFile,
1167  'files' => $expandedFiles
1168  ];
1169 
1170  $this->expandedPackageFiles[$hash] = $result;
1171  return $result;
1172  }
1173 
1180  if ( $this->packageFiles === null ) {
1181  return null;
1182  }
1183  $expandedPackageFiles = $this->expandPackageFiles( $context );
1184 
1185  // Expand file contents
1186  foreach ( $expandedPackageFiles['files'] as &$fileInfo ) {
1187  if ( isset( $fileInfo['filePath'] ) ) {
1188  $localPath = $this->getLocalPath( $fileInfo['filePath'] );
1189  if ( !file_exists( $localPath ) ) {
1190  $msg = __METHOD__ . ": package file not found: \"$localPath\"" .
1191  " in module \"{$this->getName()}\"";
1192  wfDebugLog( 'resourceloader', $msg );
1193  throw new MWException( $msg );
1194  }
1195  $content = $this->stripBom( file_get_contents( $localPath ) );
1196  if ( $fileInfo['type'] === 'data' ) {
1197  $content = json_decode( $content );
1198  }
1199  $fileInfo['content'] = $content;
1200  unset( $fileInfo['filePath'] );
1201  }
1202  }
1203 
1204  return $expandedPackageFiles;
1205  }
1206 
1217  protected function stripBom( $input ) {
1218  if ( substr_compare( "\xef\xbb\xbf", $input, 0, 3 ) === 0 ) {
1219  return substr( $input, 3 );
1220  }
1221  return $input;
1222  }
1223 }
ResourceLoaderModule\LOAD_GENERAL
const LOAD_GENERAL
Definition: ResourceLoaderModule.php:45
ResourceLoaderFileModule\getSkipFunction
getSkipFunction()
Get the skip function.
Definition: ResourceLoaderFileModule.php:497
ResourceLoaderContext
Object passed around to modules which contains information about the state of a specific loader reque...
Definition: ResourceLoaderContext.php:32
ResourceLoaderFileModule\$styles
array $styles
List of paths to CSS files to always include.
Definition: ResourceLoaderFileModule.php:82
ResourceLoaderFileModule\$skinScripts
array $skinScripts
List of JavaScript files to include when using a specific skin.
Definition: ResourceLoaderFileModule.php:64
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
ResourceLoaderFileModule\$debugScripts
array $debugScripts
List of paths to JavaScript files to include in debug mode.
Definition: ResourceLoaderFileModule.php:73
ResourceLoaderFileModule\readStyleFiles
readStyleFiles(array $styles, $flip, $context)
Get the contents of a list of CSS files.
Definition: ResourceLoaderFileModule.php:889
$context
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:2636
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
ResourceLoaderFileModule\$templates
array $templates
Saves a list of the templates named by the modules.
Definition: ResourceLoaderFileModule.php:37
ResourceLoaderFileModule\getStyles
getStyles(ResourceLoaderContext $context)
Get all styles for a given context.
Definition: ResourceLoaderFileModule.php:428
$fallback
$fallback
Definition: MessagesAb.php:11
ResourceLoaderFileModule\getFileHashes
getFileHashes(ResourceLoaderContext $context)
Helper method for getDefinitionSummary.
Definition: ResourceLoaderFileModule.php:536
ResourceLoaderModule\saveFileDependencies
saveFileDependencies(ResourceLoaderContext $context, $localFileRefs)
Set the files this module depends on indirectly for a given skin.
Definition: ResourceLoaderModule.php:461
$result
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. '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:1983
ResourceLoaderFileModule\$noflip
bool $noflip
Whether CSSJanus flipping should be skipped for this module.
Definition: ResourceLoaderFileModule.php:143
ResourceLoaderFileModule\getScriptURLsForDebug
getScriptURLsForDebug(ResourceLoaderContext $context)
Definition: ResourceLoaderFileModule.php:402
ResourceLoaderFileModule\getFlip
getFlip( $context)
Get whether CSS for this module should be flipped.
Definition: ResourceLoaderFileModule.php:956
ResourceLoaderFilePath
An object to represent a path to a JavaScript/CSS file, along with a remote and local base path,...
Definition: ResourceLoaderFilePath.php:28
ResourceLoaderFileModule\enableModuleContentVersion
enableModuleContentVersion()
Disable module content versioning.
Definition: ResourceLoaderFileModule.php:525
ResourceLoaderFileModule\$debugRaw
bool $debugRaw
Link to raw files in debug mode.
Definition: ResourceLoaderFileModule.php:135
$wgExtensionAssetsPath
$wgExtensionAssetsPath
The URL path of the extensions directory.
Definition: DefaultSettings.php:216
ResourceLoaderFileModule\$hasGeneratedStyles
bool $hasGeneratedStyles
Whether getStyleURLsForDebug should return raw file paths, or return load.php urls.
Definition: ResourceLoaderFileModule.php:149
ResourceLoaderFileModule\$dependencies
array $dependencies
List of modules this module depends on.
Definition: ResourceLoaderFileModule.php:115
ResourceLoaderFileModule\$skinStyles
array $skinStyles
List of paths to CSS files to include when using specific skins.
Definition: ResourceLoaderFileModule.php:91
serialize
serialize()
Definition: ApiMessageTrait.php:134
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1043
$wgStylePath
$wgStylePath
The URL path of the skins directory.
Definition: DefaultSettings.php:201
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
ResourceLoaderFileModule\getDefinitionSummary
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
Definition: ResourceLoaderFileModule.php:595
FileContentsHasher\getFileContentsHash
static getFileContentsHash( $filePaths, $algo='md4')
Get a hash of the combined contents of one or more files, either by retrieving a previously-computed ...
Definition: FileContentsHasher.php:89
Skin\getSkinNames
static getSkinNames()
Fetch the set of available skins.
Definition: Skin.php:57
ResourceLoaderModule\getLessVars
getLessVars(ResourceLoaderContext $context)
Get module-specific LESS variables, if any.
Definition: ResourceLoaderModule.php:678
ResourceLoaderFileModule
ResourceLoader module based on local JavaScript/CSS files.
Definition: ResourceLoaderFileModule.php:28
MWException
MediaWiki exception.
Definition: MWException.php:26
ResourceLoaderFileModule\getGroup
getGroup()
Gets the name of the group this module should be loaded in.
Definition: ResourceLoaderFileModule.php:479
$css
$css
Definition: styleTest.css.php:54
ResourceLoaderFileModule\getSkinStyleFiles
getSkinStyleFiles( $skinName)
Gets a list of file paths for all skin styles in the module used by the skin.
Definition: ResourceLoaderFileModule.php:804
ResourceLoaderFileModule\compileLessFile
compileLessFile( $fileName, ResourceLoaderContext $context)
Compile a LESS file into CSS.
Definition: ResourceLoaderFileModule.php:1003
ResourceLoaderFileModule\getAllStyleFiles
getAllStyleFiles()
Returns all style files and all skin style files used by this module.
Definition: ResourceLoaderFileModule.php:838
$input
if(is_array( $mode)) switch( $mode) $input
Definition: postprocess-phan.php:141
ResourceLoaderModule\$contents
$contents
Definition: ResourceLoaderModule.php:79
$IP
$IP
Definition: update.php:3
ResourceLoaderFileModule\getStyleURLsForDebug
getStyleURLsForDebug(ResourceLoaderContext $context)
Definition: ResourceLoaderFileModule.php:444
ResourceLoaderFileModule\getRemotePath
getRemotePath( $path)
Definition: ResourceLoaderFileModule.php:653
ResourceLoaderFileModule\extractBasePaths
static extractBasePaths( $options=[], $localBasePath=null, $remoteBasePath=null)
Extract a pair of local and remote base paths from module definition information.
Definition: ResourceLoaderFileModule.php:339
ResourceLoaderFileModule\$targets
$targets
Definition: ResourceLoaderFileModule.php:140
ResourceLoaderFileModule\expandPackageFiles
expandPackageFiles(ResourceLoaderContext $context)
Expand the packageFiles definition into something that's (almost) the right format for getPackageFile...
Definition: ResourceLoaderFileModule.php:1082
ResourceLoaderFileModule\$raw
bool $raw
Whether mw.loader.state() call should be omitted.
Definition: ResourceLoaderFileModule.php:138
$vars
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2220
ResourceLoaderContext\getLanguage
getLanguage()
Definition: ResourceLoaderContext.php:166
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))
string
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
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
ResourceLoaderFileModule\$messages
array $messages
List of message keys used by this module.
Definition: ResourceLoaderFileModule.php:129
ResourceLoaderModule\getMessageBlob
getMessageBlob(ResourceLoaderContext $context)
Get the hash of the message blob.
Definition: ResourceLoaderModule.php:566
ResourceLoaderFileModule\$languageScripts
array $languageScripts
List of JavaScript files to include when using a specific language.
Definition: ResourceLoaderFileModule.php:55
ResourceLoaderFileModule\stripBom
stripBom( $input)
Takes an input string and removes the UTF-8 BOM character if present.
Definition: ResourceLoaderFileModule.php:1217
ResourceLoaderFileModule\getPackageFiles
getPackageFiles(ResourceLoaderContext $context)
Resolves the package files defintion and generates the content of each package file.
Definition: ResourceLoaderFileModule.php:1179
ResourceLoaderModule\getDeprecationInformation
getDeprecationInformation()
Get JS representing deprecation information for the current module if available.
Definition: ResourceLoaderModule.php:141
ResourceLoaderFileModule\getDependencies
getDependencies(ResourceLoaderContext $context=null)
Gets list of names of modules this module depends on.
Definition: ResourceLoaderFileModule.php:488
$value
$value
Definition: styleTest.css.php:49
ResourceLoaderFileModule\getTargets
getTargets()
Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile'].
Definition: ResourceLoaderFileModule.php:965
ResourceLoaderFileModule\$skipFunction
string $skipFunction
File name containing the body of the skip function.
Definition: ResourceLoaderFileModule.php:120
ResourceLoaderFileModule\$group
string $group
Name of group to load this module in.
Definition: ResourceLoaderFileModule.php:132
ResourceLoaderFileModule\readStyleFile
readStyleFile( $path, $flip, $context)
Reads a style file.
Definition: ResourceLoaderFileModule.php:916
ResourceLoaderFileModule\$localFileRefs
array $localFileRefs
Place where readStyleFile() tracks file dependencies.
Definition: ResourceLoaderFileModule.php:158
CACHE_ANYTHING
const CACHE_ANYTHING
Definition: Defines.php:101
ResourceLoaderFileModule\readScriptFiles
readScriptFiles(array $scripts)
Get the contents of a list of JavaScript files.
Definition: ResourceLoaderFileModule.php:862
ResourceLoaderModule\LOAD_STYLES
const LOAD_STYLES
Definition: ResourceLoaderModule.php:43
ResourceLoaderFileModule\collateFilePathListByOption
static collateFilePathListByOption(array $list, $option, $default)
Collates file paths by option (where provided).
Definition: ResourceLoaderFileModule.php:693
ResourceLoaderFileModule\$expandedPackageFiles
array $expandedPackageFiles
Expanded versions of $packageFiles, lazy-computed by expandPackageFiles(); keyed by context hash.
Definition: ResourceLoaderFileModule.php:106
ResourceLoaderFileModule\__construct
__construct( $options=[], $localBasePath=null, $remoteBasePath=null)
Constructs a new module from an options array.
Definition: ResourceLoaderFileModule.php:236
ResourceLoaderFileModule\$localBasePath
string $localBasePath
Local base path, see __construct()
Definition: ResourceLoaderFileModule.php:31
$wgResourceBasePath
$wgResourceBasePath
The default 'remoteBasePath' value for instances of ResourceLoaderFileModule.
Definition: DefaultSettings.php:3671
scripts
The package scripts
Definition: README.txt:1
ResourceLoaderFileModule\getScriptFiles
getScriptFiles(ResourceLoaderContext $context)
Get a list of script file paths for this module, in order of proper execution.
Definition: ResourceLoaderFileModule.php:741
ResourceLoaderFileModule\getStyleSheetLang
getStyleSheetLang( $path)
Infer the stylesheet language from a stylesheet file path.
Definition: ResourceLoaderFileModule.php:668
ResourceLoaderFileModule\getLocalPath
getLocalPath( $path)
Definition: ResourceLoaderFileModule.php:641
ResourceLoaderModule
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
Definition: ResourceLoaderModule.php:35
$cache
$cache
Definition: mcc.php:33
$options
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:1985
ResourceLoaderFileModule\tryForKey
static tryForKey(array $list, $key, $fallback=null)
Get a list of element that match a key, optionally using a fallback key.
Definition: ResourceLoaderFileModule.php:723
ResourceLoaderFileModule\getTemplates
getTemplates()
Takes named templates by the module and returns an array mapping.
Definition: ResourceLoaderFileModule.php:1049
$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
messages
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:1290
ResourceLoaderModule\getFileDependencies
getFileDependencies(ResourceLoaderContext $context)
Get the files this module depends on indirectly for a given skin.
Definition: ResourceLoaderModule.php:414
$content
$content
Definition: pageupdater.txt:72
ResourceLoaderFileModule\$remoteBasePath
string $remoteBasePath
Remote base path, see __construct()
Definition: ResourceLoaderFileModule.php:34
ResourceLoaderFileModule\supportsURLLoading
supportsURLLoading()
Definition: ResourceLoaderFileModule.php:416
ResourceLoaderFileModule\getMessages
getMessages()
Gets list of message keys used by this module.
Definition: ResourceLoaderFileModule.php:470
ResourceLoaderFileModule\getAllSkinStyleFiles
getAllSkinStyleFiles()
Gets a list of file paths for all skin style files in the module, for all available skins.
Definition: ResourceLoaderFileModule.php:818
ResourceLoaderFileModule\getStyleFiles
getStyleFiles(ResourceLoaderContext $context)
Get a list of file paths for all styles in this module, in order of proper inclusion.
Definition: ResourceLoaderFileModule.php:786
ResourceLoaderFileModule\getType
getType()
Get the module's load type.
Definition: ResourceLoaderFileModule.php:975
ResourceLoaderFileModule\getScript
getScript(ResourceLoaderContext $context)
Gets all scripts for a given context concatenated together.
Definition: ResourceLoaderFileModule.php:383
ResourceLoaderFileModule\$scripts
array $scripts
List of paths to JavaScript files to always include.
Definition: ResourceLoaderFileModule.php:46
ResourceLoaderFileModule\getLanguageScripts
getLanguageScripts( $lang)
Get the set of language scripts for the given language, possibly using a fallback language.
Definition: ResourceLoaderFileModule.php:761
ResourceLoaderModule\getConfig
getConfig()
Definition: ResourceLoaderModule.php:196
Language\getFallbacksFor
static getFallbacksFor( $code, $mode=self::MESSAGES_FALLBACKS)
Get the ordered list of fallback languages.
Definition: Language.php:4528
ResourceLoaderFileModule\$missingLocalFileRefs
array $missingLocalFileRefs
Place where readStyleFile() tracks file dependencies for non-existent files.
Definition: ResourceLoaderFileModule.php:164
ResourceLoaderFileModule\isRaw
isRaw()
Definition: ResourceLoaderFileModule.php:513
ResourceLoaderFileModule\$packageFiles
array $packageFiles
List of packaged files to make available through require()
Definition: ResourceLoaderFileModule.php:100
ObjectCache\getLocalServerInstance
static getLocalServerInstance( $fallback=CACHE_NONE)
Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
Definition: ObjectCache.php:279
ResourceLoaderFileModule\getPackageFileType
static getPackageFileType( $path)
Infer the file type from a package file path.
Definition: ResourceLoaderFileModule.php:677
$type
$type
Definition: testCompression.php:48