ResourceLoaderClientHtml.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. */
  20. use Wikimedia\WrappedString;
  21. use Wikimedia\WrappedStringList;
  22. /**
  23. * Bootstrap a ResourceLoader client on an HTML page.
  24. *
  25. * @since 1.28
  26. */
  27. class ResourceLoaderClientHtml {
  28. /** @var ResourceLoaderContext */
  29. private $context;
  30. /** @var ResourceLoader */
  31. private $resourceLoader;
  32. /** @var array */
  33. private $options;
  34. /** @var array */
  35. private $config = [];
  36. /** @var array */
  37. private $modules = [];
  38. /** @var array */
  39. private $moduleStyles = [];
  40. /** @var array */
  41. private $moduleScripts = [];
  42. /** @var array */
  43. private $exemptStates = [];
  44. /** @var array */
  45. private $data;
  46. /**
  47. * @param ResourceLoaderContext $context
  48. * @param array $options [optional] Array of options
  49. * - 'target': Parameter for modules=startup request, see ResourceLoaderStartUpModule.
  50. * - 'safemode': Parameter for modules=startup request, see ResourceLoaderStartUpModule.
  51. * - 'nonce': From OutputPage::getCSPNonce().
  52. */
  53. public function __construct( ResourceLoaderContext $context, array $options = [] ) {
  54. $this->context = $context;
  55. $this->resourceLoader = $context->getResourceLoader();
  56. $this->options = $options + [
  57. 'target' => null,
  58. 'safemode' => null,
  59. 'nonce' => null,
  60. ];
  61. }
  62. /**
  63. * Set mw.config variables.
  64. *
  65. * @param array $vars Array of key/value pairs
  66. */
  67. public function setConfig( array $vars ) {
  68. foreach ( $vars as $key => $value ) {
  69. $this->config[$key] = $value;
  70. }
  71. }
  72. /**
  73. * Ensure one or more modules are loaded.
  74. *
  75. * @param array $modules Array of module names
  76. */
  77. public function setModules( array $modules ) {
  78. $this->modules = $modules;
  79. }
  80. /**
  81. * Ensure the styles of one or more modules are loaded.
  82. *
  83. * @param array $modules Array of module names
  84. */
  85. public function setModuleStyles( array $modules ) {
  86. $this->moduleStyles = $modules;
  87. }
  88. /**
  89. * Ensure the scripts of one or more modules are loaded.
  90. *
  91. * @deprecated since 1.28
  92. * @param array $modules Array of module names
  93. */
  94. public function setModuleScripts( array $modules ) {
  95. $this->moduleScripts = $modules;
  96. }
  97. /**
  98. * Set state of special modules that are handled by the caller manually.
  99. *
  100. * See OutputPage::buildExemptModules() for use cases.
  101. *
  102. * @param array $states Module state keyed by module name
  103. */
  104. public function setExemptStates( array $states ) {
  105. $this->exemptStates = $states;
  106. }
  107. /**
  108. * @return array
  109. */
  110. private function getData() {
  111. if ( $this->data ) {
  112. // @codeCoverageIgnoreStart
  113. return $this->data;
  114. // @codeCoverageIgnoreEnd
  115. }
  116. $rl = $this->resourceLoader;
  117. $data = [
  118. 'states' => [
  119. // moduleName => state
  120. ],
  121. 'general' => [],
  122. 'styles' => [],
  123. 'scripts' => [],
  124. // Embedding for private modules
  125. 'embed' => [
  126. 'styles' => [],
  127. 'general' => [],
  128. ],
  129. // Deprecations for style-only modules
  130. 'styleDeprecations' => [],
  131. ];
  132. foreach ( $this->modules as $name ) {
  133. $module = $rl->getModule( $name );
  134. if ( !$module ) {
  135. continue;
  136. }
  137. $group = $module->getGroup();
  138. $context = $this->getContext( $group, ResourceLoaderModule::TYPE_COMBINED );
  139. if ( $module->isKnownEmpty( $context ) ) {
  140. // Avoid needless request or embed for empty module
  141. $data['states'][$name] = 'ready';
  142. continue;
  143. }
  144. if ( $group === 'user' || $module->shouldEmbedModule( $this->context ) ) {
  145. // Call makeLoad() to decide how to load these, instead of
  146. // loading via mw.loader.load().
  147. // - For group=user: We need to provide a pre-generated load.php
  148. // url to the client that has the 'user' and 'version' parameters
  149. // filled in. Without this, the client would wrongly use the static
  150. // version hash, per T64602.
  151. // - For shouldEmbed=true: Embed via mw.loader.implement, per T36907.
  152. $data['embed']['general'][] = $name;
  153. // Avoid duplicate request from mw.loader
  154. $data['states'][$name] = 'loading';
  155. } else {
  156. // Load via mw.loader.load()
  157. $data['general'][] = $name;
  158. }
  159. }
  160. foreach ( $this->moduleStyles as $name ) {
  161. $module = $rl->getModule( $name );
  162. if ( !$module ) {
  163. continue;
  164. }
  165. if ( $module->getType() !== ResourceLoaderModule::LOAD_STYLES ) {
  166. $logger = $rl->getLogger();
  167. $logger->error( 'Unexpected general module "{module}" in styles queue.', [
  168. 'module' => $name,
  169. ] );
  170. continue;
  171. }
  172. // Stylesheet doesn't trigger mw.loader callback.
  173. // Set "ready" state to allow script modules to depend on this module (T87871).
  174. // And to avoid duplicate requests at run-time from mw.loader.
  175. $data['states'][$name] = 'ready';
  176. $group = $module->getGroup();
  177. $context = $this->getContext( $group, ResourceLoaderModule::TYPE_STYLES );
  178. // Avoid needless request for empty module
  179. if ( !$module->isKnownEmpty( $context ) ) {
  180. if ( $module->shouldEmbedModule( $this->context ) ) {
  181. // Embed via style element
  182. $data['embed']['styles'][] = $name;
  183. } else {
  184. // Load from load.php?only=styles via <link rel=stylesheet>
  185. $data['styles'][] = $name;
  186. }
  187. }
  188. $deprecation = $module->getDeprecationInformation();
  189. if ( $deprecation ) {
  190. $data['styleDeprecations'][] = $deprecation;
  191. }
  192. }
  193. foreach ( $this->moduleScripts as $name ) {
  194. $module = $rl->getModule( $name );
  195. if ( !$module ) {
  196. continue;
  197. }
  198. $group = $module->getGroup();
  199. $context = $this->getContext( $group, ResourceLoaderModule::TYPE_SCRIPTS );
  200. if ( $module->isKnownEmpty( $context ) ) {
  201. // Avoid needless request for empty module
  202. $data['states'][$name] = 'ready';
  203. } else {
  204. // Load from load.php?only=scripts via <script src></script>
  205. $data['scripts'][] = $name;
  206. // Avoid duplicate request from mw.loader
  207. $data['states'][$name] = 'loading';
  208. }
  209. }
  210. return $data;
  211. }
  212. /**
  213. * @return array Attribute key-value pairs for the HTML document element
  214. */
  215. public function getDocumentAttributes() {
  216. return [ 'class' => 'client-nojs' ];
  217. }
  218. /**
  219. * The order of elements in the head is as follows:
  220. * - Inline scripts.
  221. * - Stylesheets.
  222. * - Async external script-src.
  223. *
  224. * Reasons:
  225. * - Script execution may be blocked on preceeding stylesheets.
  226. * - Async scripts are not blocked on stylesheets.
  227. * - Inline scripts can't be asynchronous.
  228. * - For styles, earlier is better.
  229. *
  230. * @return string|WrappedStringList HTML
  231. */
  232. public function getHeadHtml() {
  233. $nonce = $this->options['nonce'];
  234. $data = $this->getData();
  235. $chunks = [];
  236. // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
  237. // This happens synchronously on every page view to avoid flashes of wrong content.
  238. // See also #getDocumentAttributes() and /resources/src/startup.js.
  239. $chunks[] = Html::inlineScript(
  240. 'document.documentElement.className = document.documentElement.className'
  241. . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );',
  242. $nonce
  243. );
  244. // Inline RLQ: Set page variables
  245. if ( $this->config ) {
  246. $chunks[] = ResourceLoader::makeInlineScript(
  247. ResourceLoader::makeConfigSetScript( $this->config ),
  248. $nonce
  249. );
  250. }
  251. // Inline RLQ: Initial module states
  252. $states = array_merge( $this->exemptStates, $data['states'] );
  253. if ( $states ) {
  254. $chunks[] = ResourceLoader::makeInlineScript(
  255. ResourceLoader::makeLoaderStateScript( $states ),
  256. $nonce
  257. );
  258. }
  259. // Inline RLQ: Embedded modules
  260. if ( $data['embed']['general'] ) {
  261. $chunks[] = $this->getLoad(
  262. $data['embed']['general'],
  263. ResourceLoaderModule::TYPE_COMBINED,
  264. $nonce
  265. );
  266. }
  267. // Inline RLQ: Load general modules
  268. if ( $data['general'] ) {
  269. $chunks[] = ResourceLoader::makeInlineScript(
  270. 'RLPAGEMODULES='
  271. . ResourceLoader::encodeJsonForScript( $data['general'] )
  272. . ';'
  273. . 'mw.loader.load(RLPAGEMODULES);',
  274. $nonce
  275. );
  276. }
  277. // Inline RLQ: Load only=scripts
  278. if ( $data['scripts'] ) {
  279. $chunks[] = $this->getLoad(
  280. $data['scripts'],
  281. ResourceLoaderModule::TYPE_SCRIPTS,
  282. $nonce
  283. );
  284. }
  285. // External stylesheets (only=styles)
  286. if ( $data['styles'] ) {
  287. $chunks[] = $this->getLoad(
  288. $data['styles'],
  289. ResourceLoaderModule::TYPE_STYLES,
  290. $nonce
  291. );
  292. }
  293. // Inline stylesheets (embedded only=styles)
  294. if ( $data['embed']['styles'] ) {
  295. $chunks[] = $this->getLoad(
  296. $data['embed']['styles'],
  297. ResourceLoaderModule::TYPE_STYLES,
  298. $nonce
  299. );
  300. }
  301. // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
  302. // Pass-through a custom 'target' from OutputPage (T143066).
  303. $startupQuery = [];
  304. foreach ( [ 'target', 'safemode' ] as $param ) {
  305. if ( $this->options[$param] !== null ) {
  306. $startupQuery[$param] = (string)$this->options[$param];
  307. }
  308. }
  309. $chunks[] = $this->getLoad(
  310. 'startup',
  311. ResourceLoaderModule::TYPE_SCRIPTS,
  312. $nonce,
  313. $startupQuery
  314. );
  315. return WrappedString::join( "\n", $chunks );
  316. }
  317. /**
  318. * @return string|WrappedStringList HTML
  319. */
  320. public function getBodyHtml() {
  321. $data = $this->getData();
  322. $chunks = [];
  323. // Deprecations for only=styles modules
  324. if ( $data['styleDeprecations'] ) {
  325. $chunks[] = ResourceLoader::makeInlineScript(
  326. implode( '', $data['styleDeprecations'] ),
  327. $this->options['nonce']
  328. );
  329. }
  330. return WrappedString::join( "\n", $chunks );
  331. }
  332. private function getContext( $group, $type ) {
  333. return self::makeContext( $this->context, $group, $type );
  334. }
  335. private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
  336. return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery, $nonce );
  337. }
  338. private static function makeContext( ResourceLoaderContext $mainContext, $group, $type,
  339. array $extraQuery = []
  340. ) {
  341. // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
  342. $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
  343. // Set 'only' if not combined
  344. $req->setVal( 'only', $type === ResourceLoaderModule::TYPE_COMBINED ? null : $type );
  345. // Remove user parameter in most cases
  346. if ( $group !== 'user' && $group !== 'private' ) {
  347. $req->setVal( 'user', null );
  348. }
  349. $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
  350. // Allow caller to setVersion() and setModules()
  351. $ret = new DerivativeResourceLoaderContext( $context );
  352. $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
  353. return $ret;
  354. }
  355. /**
  356. * Explicily load or embed modules on a page.
  357. *
  358. * @param ResourceLoaderContext $mainContext
  359. * @param array $modules One or more module names
  360. * @param string $only ResourceLoaderModule TYPE_ class constant
  361. * @param array $extraQuery [optional] Array with extra query parameters for the request
  362. * @param string|null $nonce [optional] Content-Security-Policy nonce
  363. * (from OutputPage::getCSPNonce)
  364. * @return string|WrappedStringList HTML
  365. */
  366. public static function makeLoad( ResourceLoaderContext $mainContext, array $modules, $only,
  367. array $extraQuery = [], $nonce = null
  368. ) {
  369. $rl = $mainContext->getResourceLoader();
  370. $chunks = [];
  371. // Sort module names so requests are more uniform
  372. sort( $modules );
  373. if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
  374. $chunks = [];
  375. // Recursively call us for every item
  376. foreach ( $modules as $name ) {
  377. $chunks[] = self::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
  378. }
  379. return new WrappedStringList( "\n", $chunks );
  380. }
  381. // Create keyed-by-source and then keyed-by-group list of module objects from modules list
  382. $sortedModules = [];
  383. foreach ( $modules as $name ) {
  384. $module = $rl->getModule( $name );
  385. if ( !$module ) {
  386. $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
  387. continue;
  388. }
  389. $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
  390. }
  391. foreach ( $sortedModules as $source => $groups ) {
  392. foreach ( $groups as $group => $grpModules ) {
  393. $context = self::makeContext( $mainContext, $group, $only, $extraQuery );
  394. // Separate sets of linked and embedded modules while preserving order
  395. $moduleSets = [];
  396. $idx = -1;
  397. foreach ( $grpModules as $name => $module ) {
  398. $shouldEmbed = $module->shouldEmbedModule( $context );
  399. if ( !$moduleSets || $moduleSets[$idx][0] !== $shouldEmbed ) {
  400. $moduleSets[++$idx] = [ $shouldEmbed, [] ];
  401. }
  402. $moduleSets[$idx][1][$name] = $module;
  403. }
  404. // Link/embed each set
  405. foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
  406. $context->setModules( array_keys( $moduleSet ) );
  407. if ( $embed ) {
  408. // Decide whether to use style or script element
  409. if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
  410. $chunks[] = Html::inlineStyle(
  411. $rl->makeModuleResponse( $context, $moduleSet )
  412. );
  413. } else {
  414. $chunks[] = ResourceLoader::makeInlineScript(
  415. $rl->makeModuleResponse( $context, $moduleSet ),
  416. $nonce
  417. );
  418. }
  419. } else {
  420. // See if we have one or more raw modules
  421. $isRaw = false;
  422. foreach ( $moduleSet as $key => $module ) {
  423. $isRaw |= $module->isRaw();
  424. }
  425. // Special handling for the user group; because users might change their stuff
  426. // on-wiki like user pages, or user preferences; we need to find the highest
  427. // timestamp of these user-changeable modules so we can ensure cache misses on change
  428. // This should NOT be done for the site group (T29564) because anons get that too
  429. // and we shouldn't be putting timestamps in CDN-cached HTML
  430. if ( $group === 'user' ) {
  431. // Must setModules() before makeVersionQuery()
  432. $context->setVersion( $rl->makeVersionQuery( $context ) );
  433. }
  434. $url = $rl->createLoaderURL( $source, $context, $extraQuery );
  435. // Decide whether to use 'style' or 'script' element
  436. if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
  437. $chunk = Html::linkedStyle( $url );
  438. } else {
  439. if ( $context->getRaw() || $isRaw ) {
  440. $chunk = Html::element( 'script', [
  441. // In SpecialJavaScriptTest, QUnit must load synchronous
  442. 'async' => !isset( $extraQuery['sync'] ),
  443. 'src' => $url
  444. ] );
  445. } else {
  446. $chunk = ResourceLoader::makeInlineScript(
  447. Xml::encodeJsCall( 'mw.loader.load', [ $url ] ),
  448. $nonce
  449. );
  450. }
  451. }
  452. if ( $group == 'noscript' ) {
  453. $chunks[] = Html::rawElement( 'noscript', [], $chunk );
  454. } else {
  455. $chunks[] = $chunk;
  456. }
  457. }
  458. }
  459. }
  460. }
  461. return new WrappedStringList( "\n", $chunks );
  462. }
  463. }