ResourceLoaderFileModule.php 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. <?php
  2. /**
  3. * ResourceLoader module based on local JavaScript/CSS files.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @author Trevor Parscal
  22. * @author Roan Kattouw
  23. */
  24. /**
  25. * ResourceLoader module based on local JavaScript/CSS files.
  26. */
  27. class ResourceLoaderFileModule extends ResourceLoaderModule {
  28. /** @var string Local base path, see __construct() */
  29. protected $localBasePath = '';
  30. /** @var string Remote base path, see __construct() */
  31. protected $remoteBasePath = '';
  32. /** @var array Saves a list of the templates named by the modules. */
  33. protected $templates = [];
  34. /**
  35. * @var array List of paths to JavaScript files to always include
  36. * @par Usage:
  37. * @code
  38. * [ [file-path], [file-path], ... ]
  39. * @endcode
  40. */
  41. protected $scripts = [];
  42. /**
  43. * @var array List of JavaScript files to include when using a specific language
  44. * @par Usage:
  45. * @code
  46. * [ [language-code] => [ [file-path], [file-path], ... ], ... ]
  47. * @endcode
  48. */
  49. protected $languageScripts = [];
  50. /**
  51. * @var array List of JavaScript files to include when using a specific skin
  52. * @par Usage:
  53. * @code
  54. * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
  55. * @endcode
  56. */
  57. protected $skinScripts = [];
  58. /**
  59. * @var array List of paths to JavaScript files to include in debug mode
  60. * @par Usage:
  61. * @code
  62. * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
  63. * @endcode
  64. */
  65. protected $debugScripts = [];
  66. /**
  67. * @var array List of paths to CSS files to always include
  68. * @par Usage:
  69. * @code
  70. * [ [file-path], [file-path], ... ]
  71. * @endcode
  72. */
  73. protected $styles = [];
  74. /**
  75. * @var array List of paths to CSS files to include when using specific skins
  76. * @par Usage:
  77. * @code
  78. * [ [file-path], [file-path], ... ]
  79. * @endcode
  80. */
  81. protected $skinStyles = [];
  82. /**
  83. * @var array List of modules this module depends on
  84. * @par Usage:
  85. * @code
  86. * [ [file-path], [file-path], ... ]
  87. * @endcode
  88. */
  89. protected $dependencies = [];
  90. /**
  91. * @var string File name containing the body of the skip function
  92. */
  93. protected $skipFunction = null;
  94. /**
  95. * @var array List of message keys used by this module
  96. * @par Usage:
  97. * @code
  98. * [ [message-key], [message-key], ... ]
  99. * @endcode
  100. */
  101. protected $messages = [];
  102. /** @var string Name of group to load this module in */
  103. protected $group;
  104. /** @var bool Link to raw files in debug mode */
  105. protected $debugRaw = true;
  106. /** @var bool Whether mw.loader.state() call should be omitted */
  107. protected $raw = false;
  108. protected $targets = [ 'desktop' ];
  109. /** @var bool Whether CSSJanus flipping should be skipped for this module */
  110. protected $noflip = false;
  111. /**
  112. * @var bool Whether getStyleURLsForDebug should return raw file paths,
  113. * or return load.php urls
  114. */
  115. protected $hasGeneratedStyles = false;
  116. /**
  117. * @var array Place where readStyleFile() tracks file dependencies
  118. * @par Usage:
  119. * @code
  120. * [ [file-path], [file-path], ... ]
  121. * @endcode
  122. */
  123. protected $localFileRefs = [];
  124. /**
  125. * @var array Place where readStyleFile() tracks file dependencies for non-existent files.
  126. * Used in tests to detect missing dependencies.
  127. */
  128. protected $missingLocalFileRefs = [];
  129. /**
  130. * Constructs a new module from an options array.
  131. *
  132. * @param array $options List of options; if not given or empty, an empty module will be
  133. * constructed
  134. * @param string|null $localBasePath Base path to prepend to all local paths in $options.
  135. * Defaults to $IP
  136. * @param string|null $remoteBasePath Base path to prepend to all remote paths in $options.
  137. * Defaults to $wgResourceBasePath
  138. *
  139. * Below is a description for the $options array:
  140. * @throws InvalidArgumentException
  141. * @par Construction options:
  142. * @code
  143. * [
  144. * // Base path to prepend to all local paths in $options. Defaults to $IP
  145. * 'localBasePath' => [base path],
  146. * // Base path to prepend to all remote paths in $options. Defaults to $wgResourceBasePath
  147. * 'remoteBasePath' => [base path],
  148. * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
  149. * 'remoteExtPath' => [base path],
  150. * // Equivalent of remoteBasePath, but relative to $wgStylePath
  151. * 'remoteSkinPath' => [base path],
  152. * // Scripts to always include
  153. * 'scripts' => [file path string or array of file path strings],
  154. * // Scripts to include in specific language contexts
  155. * 'languageScripts' => [
  156. * [language code] => [file path string or array of file path strings],
  157. * ],
  158. * // Scripts to include in specific skin contexts
  159. * 'skinScripts' => [
  160. * [skin name] => [file path string or array of file path strings],
  161. * ],
  162. * // Scripts to include in debug contexts
  163. * 'debugScripts' => [file path string or array of file path strings],
  164. * // Modules which must be loaded before this module
  165. * 'dependencies' => [module name string or array of module name strings],
  166. * 'templates' => [
  167. * [template alias with file.ext] => [file path to a template file],
  168. * ],
  169. * // Styles to always load
  170. * 'styles' => [file path string or array of file path strings],
  171. * // Styles to include in specific skin contexts
  172. * 'skinStyles' => [
  173. * [skin name] => [file path string or array of file path strings],
  174. * ],
  175. * // Messages to always load
  176. * 'messages' => [array of message key strings],
  177. * // Group which this module should be loaded together with
  178. * 'group' => [group name string],
  179. * // Function that, if it returns true, makes the loader skip this module.
  180. * // The file must contain valid JavaScript for execution in a private function.
  181. * // The file must not contain the "function () {" and "}" wrapper though.
  182. * 'skipFunction' => [file path]
  183. * ]
  184. * @endcode
  185. */
  186. public function __construct(
  187. $options = [],
  188. $localBasePath = null,
  189. $remoteBasePath = null
  190. ) {
  191. // Flag to decide whether to automagically add the mediawiki.template module
  192. $hasTemplates = false;
  193. // localBasePath and remoteBasePath both have unbelievably long fallback chains
  194. // and need to be handled separately.
  195. list( $this->localBasePath, $this->remoteBasePath ) =
  196. self::extractBasePaths( $options, $localBasePath, $remoteBasePath );
  197. // Extract, validate and normalise remaining options
  198. foreach ( $options as $member => $option ) {
  199. switch ( $member ) {
  200. // Lists of file paths
  201. case 'scripts':
  202. case 'debugScripts':
  203. case 'styles':
  204. $this->{$member} = (array)$option;
  205. break;
  206. case 'templates':
  207. $hasTemplates = true;
  208. $this->{$member} = (array)$option;
  209. break;
  210. // Collated lists of file paths
  211. case 'languageScripts':
  212. case 'skinScripts':
  213. case 'skinStyles':
  214. if ( !is_array( $option ) ) {
  215. throw new InvalidArgumentException(
  216. "Invalid collated file path list error. " .
  217. "'$option' given, array expected."
  218. );
  219. }
  220. foreach ( $option as $key => $value ) {
  221. if ( !is_string( $key ) ) {
  222. throw new InvalidArgumentException(
  223. "Invalid collated file path list key error. " .
  224. "'$key' given, string expected."
  225. );
  226. }
  227. $this->{$member}[$key] = (array)$value;
  228. }
  229. break;
  230. case 'deprecated':
  231. $this->deprecated = $option;
  232. break;
  233. // Lists of strings
  234. case 'dependencies':
  235. case 'messages':
  236. case 'targets':
  237. // Normalise
  238. $option = array_values( array_unique( (array)$option ) );
  239. sort( $option );
  240. $this->{$member} = $option;
  241. break;
  242. // Single strings
  243. case 'group':
  244. case 'skipFunction':
  245. $this->{$member} = (string)$option;
  246. break;
  247. // Single booleans
  248. case 'debugRaw':
  249. case 'raw':
  250. case 'noflip':
  251. $this->{$member} = (bool)$option;
  252. break;
  253. }
  254. }
  255. if ( $hasTemplates ) {
  256. $this->dependencies[] = 'mediawiki.template';
  257. // Ensure relevant template compiler module gets loaded
  258. foreach ( $this->templates as $alias => $templatePath ) {
  259. if ( is_int( $alias ) ) {
  260. $alias = $templatePath;
  261. }
  262. $suffix = explode( '.', $alias );
  263. $suffix = end( $suffix );
  264. $compilerModule = 'mediawiki.template.' . $suffix;
  265. if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies ) ) {
  266. $this->dependencies[] = $compilerModule;
  267. }
  268. }
  269. }
  270. }
  271. /**
  272. * Extract a pair of local and remote base paths from module definition information.
  273. * Implementation note: the amount of global state used in this function is staggering.
  274. *
  275. * @param array $options Module definition
  276. * @param string|null $localBasePath Path to use if not provided in module definition. Defaults
  277. * to $IP
  278. * @param string|null $remoteBasePath Path to use if not provided in module definition. Defaults
  279. * to $wgResourceBasePath
  280. * @return array Array( localBasePath, remoteBasePath )
  281. */
  282. public static function extractBasePaths(
  283. $options = [],
  284. $localBasePath = null,
  285. $remoteBasePath = null
  286. ) {
  287. global $IP, $wgResourceBasePath;
  288. // The different ways these checks are done, and their ordering, look very silly,
  289. // but were preserved for backwards-compatibility just in case. Tread lightly.
  290. if ( $localBasePath === null ) {
  291. $localBasePath = $IP;
  292. }
  293. if ( $remoteBasePath === null ) {
  294. $remoteBasePath = $wgResourceBasePath;
  295. }
  296. if ( isset( $options['remoteExtPath'] ) ) {
  297. global $wgExtensionAssetsPath;
  298. $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
  299. }
  300. if ( isset( $options['remoteSkinPath'] ) ) {
  301. global $wgStylePath;
  302. $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
  303. }
  304. if ( array_key_exists( 'localBasePath', $options ) ) {
  305. $localBasePath = (string)$options['localBasePath'];
  306. }
  307. if ( array_key_exists( 'remoteBasePath', $options ) ) {
  308. $remoteBasePath = (string)$options['remoteBasePath'];
  309. }
  310. return [ $localBasePath, $remoteBasePath ];
  311. }
  312. /**
  313. * Gets all scripts for a given context concatenated together.
  314. *
  315. * @param ResourceLoaderContext $context Context in which to generate script
  316. * @return string JavaScript code for $context
  317. */
  318. public function getScript( ResourceLoaderContext $context ) {
  319. $files = $this->getScriptFiles( $context );
  320. return $this->getDeprecationInformation() . $this->readScriptFiles( $files );
  321. }
  322. /**
  323. * @param ResourceLoaderContext $context
  324. * @return array
  325. */
  326. public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
  327. $urls = [];
  328. foreach ( $this->getScriptFiles( $context ) as $file ) {
  329. $urls[] = OutputPage::transformResourcePath(
  330. $this->getConfig(),
  331. $this->getRemotePath( $file )
  332. );
  333. }
  334. return $urls;
  335. }
  336. /**
  337. * @return bool
  338. */
  339. public function supportsURLLoading() {
  340. return $this->debugRaw;
  341. }
  342. /**
  343. * Get all styles for a given context.
  344. *
  345. * @param ResourceLoaderContext $context
  346. * @return array CSS code for $context as an associative array mapping media type to CSS text.
  347. */
  348. public function getStyles( ResourceLoaderContext $context ) {
  349. $styles = $this->readStyleFiles(
  350. $this->getStyleFiles( $context ),
  351. $this->getFlip( $context ),
  352. $context
  353. );
  354. // Collect referenced files
  355. $this->saveFileDependencies( $context, $this->localFileRefs );
  356. return $styles;
  357. }
  358. /**
  359. * @param ResourceLoaderContext $context
  360. * @return array
  361. */
  362. public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
  363. if ( $this->hasGeneratedStyles ) {
  364. // Do the default behaviour of returning a url back to load.php
  365. // but with only=styles.
  366. return parent::getStyleURLsForDebug( $context );
  367. }
  368. // Our module consists entirely of real css files,
  369. // in debug mode we can load those directly.
  370. $urls = [];
  371. foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
  372. $urls[$mediaType] = [];
  373. foreach ( $list as $file ) {
  374. $urls[$mediaType][] = OutputPage::transformResourcePath(
  375. $this->getConfig(),
  376. $this->getRemotePath( $file )
  377. );
  378. }
  379. }
  380. return $urls;
  381. }
  382. /**
  383. * Gets list of message keys used by this module.
  384. *
  385. * @return array List of message keys
  386. */
  387. public function getMessages() {
  388. return $this->messages;
  389. }
  390. /**
  391. * Gets the name of the group this module should be loaded in.
  392. *
  393. * @return string Group name
  394. */
  395. public function getGroup() {
  396. return $this->group;
  397. }
  398. /**
  399. * Gets list of names of modules this module depends on.
  400. * @param ResourceLoaderContext|null $context
  401. * @return array List of module names
  402. */
  403. public function getDependencies( ResourceLoaderContext $context = null ) {
  404. return $this->dependencies;
  405. }
  406. /**
  407. * Get the skip function.
  408. * @return null|string
  409. * @throws MWException
  410. */
  411. public function getSkipFunction() {
  412. if ( !$this->skipFunction ) {
  413. return null;
  414. }
  415. $localPath = $this->getLocalPath( $this->skipFunction );
  416. if ( !file_exists( $localPath ) ) {
  417. throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
  418. }
  419. $contents = $this->stripBom( file_get_contents( $localPath ) );
  420. return $contents;
  421. }
  422. /**
  423. * @return bool
  424. */
  425. public function isRaw() {
  426. return $this->raw;
  427. }
  428. /**
  429. * Disable module content versioning.
  430. *
  431. * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
  432. * involved with building the full module content inside a startup request.
  433. *
  434. * @return bool
  435. */
  436. public function enableModuleContentVersion() {
  437. return false;
  438. }
  439. /**
  440. * Helper method for getDefinitionSummary.
  441. *
  442. * @see ResourceLoaderModule::getFileDependencies
  443. * @param ResourceLoaderContext $context
  444. * @return array
  445. */
  446. private function getFileHashes( ResourceLoaderContext $context ) {
  447. $files = [];
  448. // Flatten style files into $files
  449. $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
  450. foreach ( $styles as $styleFiles ) {
  451. $files = array_merge( $files, $styleFiles );
  452. }
  453. $skinFiles = self::collateFilePathListByOption(
  454. self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
  455. 'media',
  456. 'all'
  457. );
  458. foreach ( $skinFiles as $styleFiles ) {
  459. $files = array_merge( $files, $styleFiles );
  460. }
  461. // Final merge, this should result in a master list of dependent files
  462. $files = array_merge(
  463. $files,
  464. $this->scripts,
  465. $this->templates,
  466. $context->getDebug() ? $this->debugScripts : [],
  467. $this->getLanguageScripts( $context->getLanguage() ),
  468. self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
  469. );
  470. if ( $this->skipFunction ) {
  471. $files[] = $this->skipFunction;
  472. }
  473. $files = array_map( [ $this, 'getLocalPath' ], $files );
  474. // File deps need to be treated separately because they're already prefixed
  475. $files = array_merge( $files, $this->getFileDependencies( $context ) );
  476. // Filter out any duplicates from getFileDependencies() and others.
  477. // Most commonly introduced by compileLessFile(), which always includes the
  478. // entry point Less file we already know about.
  479. $files = array_values( array_unique( $files ) );
  480. // Don't include keys or file paths here, only the hashes. Including that would needlessly
  481. // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
  482. // Any significant ordering is already detected by the definition summary.
  483. return array_map( [ __CLASS__, 'safeFileHash' ], $files );
  484. }
  485. /**
  486. * Get the definition summary for this module.
  487. *
  488. * @param ResourceLoaderContext $context
  489. * @return array
  490. */
  491. public function getDefinitionSummary( ResourceLoaderContext $context ) {
  492. $summary = parent::getDefinitionSummary( $context );
  493. $options = [];
  494. foreach ( [
  495. // The following properties are omitted because they don't affect the module reponse:
  496. // - localBasePath (Per T104950; Changes when absolute directory name changes. If
  497. // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
  498. // - remoteBasePath (Per T104950)
  499. // - dependencies (provided via startup module)
  500. // - targets
  501. // - group (provided via startup module)
  502. 'scripts',
  503. 'debugScripts',
  504. 'styles',
  505. 'languageScripts',
  506. 'skinScripts',
  507. 'skinStyles',
  508. 'messages',
  509. 'templates',
  510. 'skipFunction',
  511. 'debugRaw',
  512. 'raw',
  513. ] as $member ) {
  514. $options[$member] = $this->{$member};
  515. };
  516. $summary[] = [
  517. 'options' => $options,
  518. 'fileHashes' => $this->getFileHashes( $context ),
  519. 'messageBlob' => $this->getMessageBlob( $context ),
  520. ];
  521. $lessVars = $this->getLessVars( $context );
  522. if ( $lessVars ) {
  523. $summary[] = [ 'lessVars' => $lessVars ];
  524. }
  525. return $summary;
  526. }
  527. /**
  528. * @param string|ResourceLoaderFilePath $path
  529. * @return string
  530. */
  531. protected function getLocalPath( $path ) {
  532. if ( $path instanceof ResourceLoaderFilePath ) {
  533. return $path->getLocalPath();
  534. }
  535. return "{$this->localBasePath}/$path";
  536. }
  537. /**
  538. * @param string|ResourceLoaderFilePath $path
  539. * @return string
  540. */
  541. protected function getRemotePath( $path ) {
  542. if ( $path instanceof ResourceLoaderFilePath ) {
  543. return $path->getRemotePath();
  544. }
  545. return "{$this->remoteBasePath}/$path";
  546. }
  547. /**
  548. * Infer the stylesheet language from a stylesheet file path.
  549. *
  550. * @since 1.22
  551. * @param string $path
  552. * @return string The stylesheet language name
  553. */
  554. public function getStyleSheetLang( $path ) {
  555. return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
  556. }
  557. /**
  558. * Collates file paths by option (where provided).
  559. *
  560. * @param array $list List of file paths in any combination of index/path
  561. * or path/options pairs
  562. * @param string $option Option name
  563. * @param mixed $default Default value if the option isn't set
  564. * @return array List of file paths, collated by $option
  565. */
  566. protected static function collateFilePathListByOption( array $list, $option, $default ) {
  567. $collatedFiles = [];
  568. foreach ( (array)$list as $key => $value ) {
  569. if ( is_int( $key ) ) {
  570. // File name as the value
  571. if ( !isset( $collatedFiles[$default] ) ) {
  572. $collatedFiles[$default] = [];
  573. }
  574. $collatedFiles[$default][] = $value;
  575. } elseif ( is_array( $value ) ) {
  576. // File name as the key, options array as the value
  577. $optionValue = $value[$option] ?? $default;
  578. if ( !isset( $collatedFiles[$optionValue] ) ) {
  579. $collatedFiles[$optionValue] = [];
  580. }
  581. $collatedFiles[$optionValue][] = $key;
  582. }
  583. }
  584. return $collatedFiles;
  585. }
  586. /**
  587. * Get a list of element that match a key, optionally using a fallback key.
  588. *
  589. * @param array $list List of lists to select from
  590. * @param string $key Key to look for in $map
  591. * @param string|null $fallback Key to look for in $list if $key doesn't exist
  592. * @return array List of elements from $map which matched $key or $fallback,
  593. * or an empty list in case of no match
  594. */
  595. protected static function tryForKey( array $list, $key, $fallback = null ) {
  596. if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
  597. return $list[$key];
  598. } elseif ( is_string( $fallback )
  599. && isset( $list[$fallback] )
  600. && is_array( $list[$fallback] )
  601. ) {
  602. return $list[$fallback];
  603. }
  604. return [];
  605. }
  606. /**
  607. * Get a list of script file paths for this module, in order of proper execution.
  608. *
  609. * @param ResourceLoaderContext $context
  610. * @return array List of file paths
  611. */
  612. private function getScriptFiles( ResourceLoaderContext $context ) {
  613. $files = array_merge(
  614. $this->scripts,
  615. $this->getLanguageScripts( $context->getLanguage() ),
  616. self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
  617. );
  618. if ( $context->getDebug() ) {
  619. $files = array_merge( $files, $this->debugScripts );
  620. }
  621. return array_unique( $files, SORT_REGULAR );
  622. }
  623. /**
  624. * Get the set of language scripts for the given language,
  625. * possibly using a fallback language.
  626. *
  627. * @param string $lang
  628. * @return array
  629. */
  630. private function getLanguageScripts( $lang ) {
  631. $scripts = self::tryForKey( $this->languageScripts, $lang );
  632. if ( $scripts ) {
  633. return $scripts;
  634. }
  635. $fallbacks = Language::getFallbacksFor( $lang );
  636. foreach ( $fallbacks as $lang ) {
  637. $scripts = self::tryForKey( $this->languageScripts, $lang );
  638. if ( $scripts ) {
  639. return $scripts;
  640. }
  641. }
  642. return [];
  643. }
  644. /**
  645. * Get a list of file paths for all styles in this module, in order of proper inclusion.
  646. *
  647. * This is considered a private method. Exposed for internal use by WebInstallerOutput.
  648. *
  649. * @private
  650. * @param ResourceLoaderContext $context
  651. * @return array List of file paths
  652. */
  653. public function getStyleFiles( ResourceLoaderContext $context ) {
  654. return array_merge_recursive(
  655. self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
  656. self::collateFilePathListByOption(
  657. self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
  658. 'media',
  659. 'all'
  660. )
  661. );
  662. }
  663. /**
  664. * Gets a list of file paths for all skin styles in the module used by
  665. * the skin.
  666. *
  667. * @param string $skinName The name of the skin
  668. * @return array A list of file paths collated by media type
  669. */
  670. protected function getSkinStyleFiles( $skinName ) {
  671. return self::collateFilePathListByOption(
  672. self::tryForKey( $this->skinStyles, $skinName ),
  673. 'media',
  674. 'all'
  675. );
  676. }
  677. /**
  678. * Gets a list of file paths for all skin style files in the module,
  679. * for all available skins.
  680. *
  681. * @return array A list of file paths collated by media type
  682. */
  683. protected function getAllSkinStyleFiles() {
  684. $styleFiles = [];
  685. $internalSkinNames = array_keys( Skin::getSkinNames() );
  686. $internalSkinNames[] = 'default';
  687. foreach ( $internalSkinNames as $internalSkinName ) {
  688. $styleFiles = array_merge_recursive(
  689. $styleFiles,
  690. $this->getSkinStyleFiles( $internalSkinName )
  691. );
  692. }
  693. return $styleFiles;
  694. }
  695. /**
  696. * Returns all style files and all skin style files used by this module.
  697. *
  698. * @return array
  699. */
  700. public function getAllStyleFiles() {
  701. $collatedStyleFiles = array_merge_recursive(
  702. self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
  703. $this->getAllSkinStyleFiles()
  704. );
  705. $result = [];
  706. foreach ( $collatedStyleFiles as $media => $styleFiles ) {
  707. foreach ( $styleFiles as $styleFile ) {
  708. $result[] = $this->getLocalPath( $styleFile );
  709. }
  710. }
  711. return $result;
  712. }
  713. /**
  714. * Get the contents of a list of JavaScript files. Helper for getScript().
  715. *
  716. * @param array $scripts List of file paths to scripts to read, remap and concetenate
  717. * @return string Concatenated and remapped JavaScript data from $scripts
  718. * @throws MWException
  719. */
  720. private function readScriptFiles( array $scripts ) {
  721. if ( empty( $scripts ) ) {
  722. return '';
  723. }
  724. $js = '';
  725. foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
  726. $localPath = $this->getLocalPath( $fileName );
  727. if ( !file_exists( $localPath ) ) {
  728. throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
  729. }
  730. $contents = $this->stripBom( file_get_contents( $localPath ) );
  731. $js .= $contents . "\n";
  732. }
  733. return $js;
  734. }
  735. /**
  736. * Get the contents of a list of CSS files.
  737. *
  738. * This is considered a private method. Exposed for internal use by WebInstallerOutput.
  739. *
  740. * @private
  741. * @param array $styles Map of media type to file paths to read, remap, and concatenate
  742. * @param bool $flip
  743. * @param ResourceLoaderContext|null $context
  744. * @return array List of concatenated and remapped CSS data from $styles,
  745. * keyed by media type
  746. * @throws MWException
  747. * @since 1.27 Calling this method without a ResourceLoaderContext instance
  748. * is deprecated.
  749. */
  750. public function readStyleFiles( array $styles, $flip, $context = null ) {
  751. if ( $context === null ) {
  752. wfDeprecated( __METHOD__ . ' without a ResourceLoader context', '1.27' );
  753. $context = ResourceLoaderContext::newDummyContext();
  754. }
  755. if ( empty( $styles ) ) {
  756. return [];
  757. }
  758. foreach ( $styles as $media => $files ) {
  759. $uniqueFiles = array_unique( $files, SORT_REGULAR );
  760. $styleFiles = [];
  761. foreach ( $uniqueFiles as $file ) {
  762. $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
  763. }
  764. $styles[$media] = implode( "\n", $styleFiles );
  765. }
  766. return $styles;
  767. }
  768. /**
  769. * Reads a style file.
  770. *
  771. * This method can be used as a callback for array_map()
  772. *
  773. * @param string $path File path of style file to read
  774. * @param bool $flip
  775. * @param ResourceLoaderContext $context
  776. *
  777. * @return string CSS data in script file
  778. * @throws MWException If the file doesn't exist
  779. */
  780. protected function readStyleFile( $path, $flip, $context ) {
  781. $localPath = $this->getLocalPath( $path );
  782. $remotePath = $this->getRemotePath( $path );
  783. if ( !file_exists( $localPath ) ) {
  784. $msg = __METHOD__ . ": style file not found: \"$localPath\"";
  785. wfDebugLog( 'resourceloader', $msg );
  786. throw new MWException( $msg );
  787. }
  788. if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
  789. $style = $this->compileLessFile( $localPath, $context );
  790. $this->hasGeneratedStyles = true;
  791. } else {
  792. $style = $this->stripBom( file_get_contents( $localPath ) );
  793. }
  794. if ( $flip ) {
  795. $style = CSSJanus::transform( $style, true, false );
  796. }
  797. $localDir = dirname( $localPath );
  798. $remoteDir = dirname( $remotePath );
  799. // Get and register local file references
  800. $localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
  801. foreach ( $localFileRefs as $file ) {
  802. if ( file_exists( $file ) ) {
  803. $this->localFileRefs[] = $file;
  804. } else {
  805. $this->missingLocalFileRefs[] = $file;
  806. }
  807. }
  808. // Don't cache this call. remap() ensures data URIs embeds are up to date,
  809. // and urls contain correct content hashes in their query string. (T128668)
  810. return CSSMin::remap( $style, $localDir, $remoteDir, true );
  811. }
  812. /**
  813. * Get whether CSS for this module should be flipped
  814. * @param ResourceLoaderContext $context
  815. * @return bool
  816. */
  817. public function getFlip( $context ) {
  818. return $context->getDirection() === 'rtl' && !$this->noflip;
  819. }
  820. /**
  821. * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
  822. *
  823. * @return array Array of strings
  824. */
  825. public function getTargets() {
  826. return $this->targets;
  827. }
  828. /**
  829. * Get the module's load type.
  830. *
  831. * @since 1.28
  832. * @return string
  833. */
  834. public function getType() {
  835. $canBeStylesOnly = !(
  836. // All options except 'styles', 'skinStyles' and 'debugRaw'
  837. $this->scripts
  838. || $this->debugScripts
  839. || $this->templates
  840. || $this->languageScripts
  841. || $this->skinScripts
  842. || $this->dependencies
  843. || $this->messages
  844. || $this->skipFunction
  845. || $this->raw
  846. );
  847. return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
  848. }
  849. /**
  850. * Compile a LESS file into CSS.
  851. *
  852. * Keeps track of all used files and adds them to localFileRefs.
  853. *
  854. * @since 1.22
  855. * @since 1.27 Added $context paramter.
  856. * @throws Exception If less.php encounters a parse error
  857. * @param string $fileName File path of LESS source
  858. * @param ResourceLoaderContext $context Context in which to generate script
  859. * @return string CSS source
  860. */
  861. protected function compileLessFile( $fileName, ResourceLoaderContext $context ) {
  862. static $cache;
  863. if ( !$cache ) {
  864. $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
  865. }
  866. $vars = $this->getLessVars( $context );
  867. // Construct a cache key from the LESS file name, and a hash digest
  868. // of the LESS variables used for compilation.
  869. ksort( $vars );
  870. $varsHash = hash( 'md4', serialize( $vars ) );
  871. $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
  872. $cachedCompile = $cache->get( $cacheKey );
  873. // If we got a cached value, we have to validate it by getting a
  874. // checksum of all the files that were loaded by the parser and
  875. // ensuring it matches the cached entry's.
  876. if ( isset( $cachedCompile['hash'] ) ) {
  877. $contentHash = FileContentsHasher::getFileContentsHash( $cachedCompile['files'] );
  878. if ( $contentHash === $cachedCompile['hash'] ) {
  879. $this->localFileRefs = array_merge( $this->localFileRefs, $cachedCompile['files'] );
  880. return $cachedCompile['css'];
  881. }
  882. }
  883. $compiler = $context->getResourceLoader()->getLessCompiler( $vars );
  884. $css = $compiler->parseFile( $fileName )->getCss();
  885. $files = $compiler->AllParsedFiles();
  886. $this->localFileRefs = array_merge( $this->localFileRefs, $files );
  887. // Cache for 24 hours (86400 seconds).
  888. $cache->set( $cacheKey, [
  889. 'css' => $css,
  890. 'files' => $files,
  891. 'hash' => FileContentsHasher::getFileContentsHash( $files ),
  892. ], 3600 * 24 );
  893. return $css;
  894. }
  895. /**
  896. * Takes named templates by the module and returns an array mapping.
  897. * @return array Templates mapping template alias to content
  898. * @throws MWException
  899. */
  900. public function getTemplates() {
  901. $templates = [];
  902. foreach ( $this->templates as $alias => $templatePath ) {
  903. // Alias is optional
  904. if ( is_int( $alias ) ) {
  905. $alias = $templatePath;
  906. }
  907. $localPath = $this->getLocalPath( $templatePath );
  908. if ( file_exists( $localPath ) ) {
  909. $content = file_get_contents( $localPath );
  910. $templates[$alias] = $this->stripBom( $content );
  911. } else {
  912. $msg = __METHOD__ . ": template file not found: \"$localPath\"";
  913. wfDebugLog( 'resourceloader', $msg );
  914. throw new MWException( $msg );
  915. }
  916. }
  917. return $templates;
  918. }
  919. /**
  920. * Takes an input string and removes the UTF-8 BOM character if present
  921. *
  922. * We need to remove these after reading a file, because we concatenate our files and
  923. * the BOM character is not valid in the middle of a string.
  924. * We already assume UTF-8 everywhere, so this should be safe.
  925. *
  926. * @param string $input
  927. * @return string Input minus the intial BOM char
  928. */
  929. protected function stripBom( $input ) {
  930. if ( substr_compare( "\xef\xbb\xbf", $input, 0, 3 ) === 0 ) {
  931. return substr( $input, 3 );
  932. }
  933. return $input;
  934. }
  935. }