ResourceLoaderFileModule.php 40 KB

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