class-wp-scripts.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. <?php
  2. /**
  3. * Dependencies API: WP_Scripts class
  4. *
  5. * @since 2.6.0
  6. *
  7. * @package WordPress
  8. * @subpackage Dependencies
  9. */
  10. /**
  11. * Core class used to register scripts.
  12. *
  13. * @since 2.1.0
  14. *
  15. * @see WP_Dependencies
  16. */
  17. class WP_Scripts extends WP_Dependencies {
  18. /**
  19. * Base URL for scripts.
  20. *
  21. * Full URL with trailing slash.
  22. *
  23. * @since 2.6.0
  24. * @var string
  25. */
  26. public $base_url;
  27. /**
  28. * URL of the content directory.
  29. *
  30. * @since 2.8.0
  31. * @var string
  32. */
  33. public $content_url;
  34. /**
  35. * Default version string for scripts.
  36. *
  37. * @since 2.6.0
  38. * @var string
  39. */
  40. public $default_version;
  41. /**
  42. * Holds handles of scripts which are enqueued in footer.
  43. *
  44. * @since 2.8.0
  45. * @var array
  46. */
  47. public $in_footer = array();
  48. /**
  49. * Holds a list of script handles which will be concatenated.
  50. *
  51. * @since 2.8.0
  52. * @var string
  53. */
  54. public $concat = '';
  55. /**
  56. * Holds a string which contains script handles and their version.
  57. *
  58. * @since 2.8.0
  59. * @deprecated 3.4.0
  60. * @var string
  61. */
  62. public $concat_version = '';
  63. /**
  64. * Whether to perform concatenation.
  65. *
  66. * @since 2.8.0
  67. * @var bool
  68. */
  69. public $do_concat = false;
  70. /**
  71. * Holds HTML markup of scripts and additional data if concatenation
  72. * is enabled.
  73. *
  74. * @since 2.8.0
  75. * @var string
  76. */
  77. public $print_html = '';
  78. /**
  79. * Holds inline code if concatenation is enabled.
  80. *
  81. * @since 2.8.0
  82. * @var string
  83. */
  84. public $print_code = '';
  85. /**
  86. * Holds a list of script handles which are not in the default directory
  87. * if concatenation is enabled.
  88. *
  89. * Unused in core.
  90. *
  91. * @since 2.8.0
  92. * @var string
  93. */
  94. public $ext_handles = '';
  95. /**
  96. * Holds a string which contains handles and versions of scripts which
  97. * are not in the default directory if concatenation is enabled.
  98. *
  99. * Unused in core.
  100. *
  101. * @since 2.8.0
  102. * @var string
  103. */
  104. public $ext_version = '';
  105. /**
  106. * List of default directories.
  107. *
  108. * @since 2.8.0
  109. * @var array
  110. */
  111. public $default_dirs;
  112. /**
  113. * Holds a string which contains the type attribute for script tag.
  114. *
  115. * If the active theme does not declare HTML5 support for 'script',
  116. * then it initializes as `type='text/javascript'`.
  117. *
  118. * @since 5.3.0
  119. * @var string
  120. */
  121. private $type_attr = '';
  122. /**
  123. * Constructor.
  124. *
  125. * @since 2.6.0
  126. */
  127. public function __construct() {
  128. $this->init();
  129. add_action( 'init', array( $this, 'init' ), 0 );
  130. }
  131. /**
  132. * Initialize the class.
  133. *
  134. * @since 3.4.0
  135. */
  136. public function init() {
  137. if (
  138. function_exists( 'is_admin' ) && ! is_admin()
  139. &&
  140. function_exists( 'current_theme_supports' ) && ! current_theme_supports( 'html5', 'script' )
  141. ) {
  142. $this->type_attr = " type='text/javascript'";
  143. }
  144. /**
  145. * Fires when the WP_Scripts instance is initialized.
  146. *
  147. * @since 2.6.0
  148. *
  149. * @param WP_Scripts $wp_scripts WP_Scripts instance (passed by reference).
  150. */
  151. do_action_ref_array( 'wp_default_scripts', array( &$this ) );
  152. }
  153. /**
  154. * Prints scripts.
  155. *
  156. * Prints the scripts passed to it or the print queue. Also prints all necessary dependencies.
  157. *
  158. * @since 2.1.0
  159. * @since 2.8.0 Added the `$group` parameter.
  160. *
  161. * @param string|string[]|false $handles Optional. Scripts to be printed: queue (false),
  162. * single script (string), or multiple scripts (array of strings).
  163. * Default false.
  164. * @param int|false $group Optional. Group level: level (int), no groups (false).
  165. * Default false.
  166. * @return string[] Handles of scripts that have been printed.
  167. */
  168. public function print_scripts( $handles = false, $group = false ) {
  169. return $this->do_items( $handles, $group );
  170. }
  171. /**
  172. * Prints extra scripts of a registered script.
  173. *
  174. * @since 2.1.0
  175. * @since 2.8.0 Added the `$display` parameter.
  176. * @deprecated 3.3.0
  177. *
  178. * @see print_extra_script()
  179. *
  180. * @param string $handle The script's registered handle.
  181. * @param bool $display Optional. Whether to print the extra script
  182. * instead of just returning it. Default true.
  183. * @return bool|string|void Void if no data exists, extra scripts if `$display` is true,
  184. * true otherwise.
  185. */
  186. public function print_scripts_l10n( $handle, $display = true ) {
  187. _deprecated_function( __FUNCTION__, '3.3.0', 'WP_Scripts::print_extra_script()' );
  188. return $this->print_extra_script( $handle, $display );
  189. }
  190. /**
  191. * Prints extra scripts of a registered script.
  192. *
  193. * @since 3.3.0
  194. *
  195. * @param string $handle The script's registered handle.
  196. * @param bool $display Optional. Whether to print the extra script
  197. * instead of just returning it. Default true.
  198. * @return bool|string|void Void if no data exists, extra scripts if `$display` is true,
  199. * true otherwise.
  200. */
  201. public function print_extra_script( $handle, $display = true ) {
  202. $output = $this->get_data( $handle, 'data' );
  203. if ( ! $output ) {
  204. return;
  205. }
  206. if ( ! $display ) {
  207. return $output;
  208. }
  209. printf( "<script%s id='%s-js-extra'>\n", $this->type_attr, esc_attr( $handle ) );
  210. // CDATA is not needed for HTML 5.
  211. if ( $this->type_attr ) {
  212. echo "/* <![CDATA[ */\n";
  213. }
  214. echo "$output\n";
  215. if ( $this->type_attr ) {
  216. echo "/* ]]> */\n";
  217. }
  218. echo "</script>\n";
  219. return true;
  220. }
  221. /**
  222. * Processes a script dependency.
  223. *
  224. * @since 2.6.0
  225. * @since 2.8.0 Added the `$group` parameter.
  226. *
  227. * @see WP_Dependencies::do_item()
  228. *
  229. * @param string $handle The script's registered handle.
  230. * @param int|false $group Optional. Group level: level (int), no groups (false).
  231. * Default false.
  232. * @return bool True on success, false on failure.
  233. */
  234. public function do_item( $handle, $group = false ) {
  235. if ( ! parent::do_item( $handle ) ) {
  236. return false;
  237. }
  238. if ( 0 === $group && $this->groups[ $handle ] > 0 ) {
  239. $this->in_footer[] = $handle;
  240. return false;
  241. }
  242. if ( false === $group && in_array( $handle, $this->in_footer, true ) ) {
  243. $this->in_footer = array_diff( $this->in_footer, (array) $handle );
  244. }
  245. $obj = $this->registered[ $handle ];
  246. if ( null === $obj->ver ) {
  247. $ver = '';
  248. } else {
  249. $ver = $obj->ver ? $obj->ver : $this->default_version;
  250. }
  251. if ( isset( $this->args[ $handle ] ) ) {
  252. $ver = $ver ? $ver . '&amp;' . $this->args[ $handle ] : $this->args[ $handle ];
  253. }
  254. $src = $obj->src;
  255. $cond_before = '';
  256. $cond_after = '';
  257. $conditional = isset( $obj->extra['conditional'] ) ? $obj->extra['conditional'] : '';
  258. if ( $conditional ) {
  259. $cond_before = "<!--[if {$conditional}]>\n";
  260. $cond_after = "<![endif]-->\n";
  261. }
  262. $before_handle = $this->print_inline_script( $handle, 'before', false );
  263. $after_handle = $this->print_inline_script( $handle, 'after', false );
  264. if ( $before_handle ) {
  265. $before_handle = sprintf( "<script%s id='%s-js-before'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), $before_handle );
  266. }
  267. if ( $after_handle ) {
  268. $after_handle = sprintf( "<script%s id='%s-js-after'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), $after_handle );
  269. }
  270. if ( $before_handle || $after_handle ) {
  271. $inline_script_tag = $cond_before . $before_handle . $after_handle . $cond_after;
  272. } else {
  273. $inline_script_tag = '';
  274. }
  275. /*
  276. * Prevent concatenation of scripts if the text domain is defined
  277. * to ensure the dependency order is respected.
  278. */
  279. $translations_stop_concat = ! empty( $obj->textdomain );
  280. $translations = $this->print_translations( $handle, false );
  281. if ( $translations ) {
  282. $translations = sprintf( "<script%s id='%s-js-translations'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), $translations );
  283. }
  284. if ( $this->do_concat ) {
  285. /**
  286. * Filters the script loader source.
  287. *
  288. * @since 2.2.0
  289. *
  290. * @param string $src Script loader source path.
  291. * @param string $handle Script handle.
  292. */
  293. $srce = apply_filters( 'script_loader_src', $src, $handle );
  294. if ( $this->in_default_dir( $srce ) && ( $before_handle || $after_handle || $translations_stop_concat ) ) {
  295. $this->do_concat = false;
  296. // Have to print the so-far concatenated scripts right away to maintain the right order.
  297. _print_scripts();
  298. $this->reset();
  299. } elseif ( $this->in_default_dir( $srce ) && ! $conditional ) {
  300. $this->print_code .= $this->print_extra_script( $handle, false );
  301. $this->concat .= "$handle,";
  302. $this->concat_version .= "$handle$ver";
  303. return true;
  304. } else {
  305. $this->ext_handles .= "$handle,";
  306. $this->ext_version .= "$handle$ver";
  307. }
  308. }
  309. $has_conditional_data = $conditional && $this->get_data( $handle, 'data' );
  310. if ( $has_conditional_data ) {
  311. echo $cond_before;
  312. }
  313. $this->print_extra_script( $handle );
  314. if ( $has_conditional_data ) {
  315. echo $cond_after;
  316. }
  317. // A single item may alias a set of items, by having dependencies, but no source.
  318. if ( ! $src ) {
  319. if ( $inline_script_tag ) {
  320. if ( $this->do_concat ) {
  321. $this->print_html .= $inline_script_tag;
  322. } else {
  323. echo $inline_script_tag;
  324. }
  325. }
  326. return true;
  327. }
  328. if ( ! preg_match( '|^(https?:)?//|', $src ) && ! ( $this->content_url && 0 === strpos( $src, $this->content_url ) ) ) {
  329. $src = $this->base_url . $src;
  330. }
  331. if ( ! empty( $ver ) ) {
  332. $src = add_query_arg( 'ver', $ver, $src );
  333. }
  334. /** This filter is documented in wp-includes/class-wp-scripts.php */
  335. $src = esc_url( apply_filters( 'script_loader_src', $src, $handle ) );
  336. if ( ! $src ) {
  337. return true;
  338. }
  339. $tag = $translations . $cond_before . $before_handle;
  340. $tag .= sprintf( "<script%s src='%s' id='%s-js'></script>\n", $this->type_attr, $src, esc_attr( $handle ) );
  341. $tag .= $after_handle . $cond_after;
  342. /**
  343. * Filters the HTML script tag of an enqueued script.
  344. *
  345. * @since 4.1.0
  346. *
  347. * @param string $tag The `<script>` tag for the enqueued script.
  348. * @param string $handle The script's registered handle.
  349. * @param string $src The script's source URL.
  350. */
  351. $tag = apply_filters( 'script_loader_tag', $tag, $handle, $src );
  352. if ( $this->do_concat ) {
  353. $this->print_html .= $tag;
  354. } else {
  355. echo $tag;
  356. }
  357. return true;
  358. }
  359. /**
  360. * Adds extra code to a registered script.
  361. *
  362. * @since 4.5.0
  363. *
  364. * @param string $handle Name of the script to add the inline script to.
  365. * Must be lowercase.
  366. * @param string $data String containing the JavaScript to be added.
  367. * @param string $position Optional. Whether to add the inline script
  368. * before the handle or after. Default 'after'.
  369. * @return bool True on success, false on failure.
  370. */
  371. public function add_inline_script( $handle, $data, $position = 'after' ) {
  372. if ( ! $data ) {
  373. return false;
  374. }
  375. if ( 'after' !== $position ) {
  376. $position = 'before';
  377. }
  378. $script = (array) $this->get_data( $handle, $position );
  379. $script[] = $data;
  380. return $this->add_data( $handle, $position, $script );
  381. }
  382. /**
  383. * Prints inline scripts registered for a specific handle.
  384. *
  385. * @since 4.5.0
  386. *
  387. * @param string $handle Name of the script to add the inline script to.
  388. * Must be lowercase.
  389. * @param string $position Optional. Whether to add the inline script
  390. * before the handle or after. Default 'after'.
  391. * @param bool $display Optional. Whether to print the script
  392. * instead of just returning it. Default true.
  393. * @return string|false Script on success, false otherwise.
  394. */
  395. public function print_inline_script( $handle, $position = 'after', $display = true ) {
  396. $output = $this->get_data( $handle, $position );
  397. if ( empty( $output ) ) {
  398. return false;
  399. }
  400. $output = trim( implode( "\n", $output ), "\n" );
  401. if ( $display ) {
  402. printf( "<script%s id='%s-js-%s'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), esc_attr( $position ), $output );
  403. }
  404. return $output;
  405. }
  406. /**
  407. * Localizes a script, only if the script has already been added.
  408. *
  409. * @since 2.1.0
  410. *
  411. * @param string $handle Name of the script to attach data to.
  412. * @param string $object_name Name of the variable that will contain the data.
  413. * @param array $l10n Array of data to localize.
  414. * @return bool True on success, false on failure.
  415. */
  416. public function localize( $handle, $object_name, $l10n ) {
  417. if ( 'jquery' === $handle ) {
  418. $handle = 'jquery-core';
  419. }
  420. if ( is_array( $l10n ) && isset( $l10n['l10n_print_after'] ) ) { // back compat, preserve the code in 'l10n_print_after' if present.
  421. $after = $l10n['l10n_print_after'];
  422. unset( $l10n['l10n_print_after'] );
  423. }
  424. if ( ! is_array( $l10n ) ) {
  425. _doing_it_wrong(
  426. __METHOD__,
  427. sprintf(
  428. /* translators: 1: $l10n, 2: wp_add_inline_script() */
  429. __( 'The %1$s parameter must be an array. To pass arbitrary data to scripts, use the %2$s function instead.' ),
  430. '<code>$l10n</code>',
  431. '<code>wp_add_inline_script()</code>'
  432. ),
  433. '5.7.0'
  434. );
  435. if ( false === $l10n ) {
  436. // This should really not be needed, but is necessary for backward compatibility.
  437. $l10n = array( $l10n );
  438. }
  439. }
  440. if ( is_string( $l10n ) ) {
  441. $l10n = html_entity_decode( $l10n, ENT_QUOTES, 'UTF-8' );
  442. } elseif ( is_array( $l10n ) ) {
  443. foreach ( $l10n as $key => $value ) {
  444. if ( ! is_scalar( $value ) ) {
  445. continue;
  446. }
  447. $l10n[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
  448. }
  449. }
  450. $script = "var $object_name = " . wp_json_encode( $l10n ) . ';';
  451. if ( ! empty( $after ) ) {
  452. $script .= "\n$after;";
  453. }
  454. $data = $this->get_data( $handle, 'data' );
  455. if ( ! empty( $data ) ) {
  456. $script = "$data\n$script";
  457. }
  458. return $this->add_data( $handle, 'data', $script );
  459. }
  460. /**
  461. * Sets handle group.
  462. *
  463. * @since 2.8.0
  464. *
  465. * @see WP_Dependencies::set_group()
  466. *
  467. * @param string $handle Name of the item. Should be unique.
  468. * @param bool $recursion Internal flag that calling function was called recursively.
  469. * @param int|false $group Optional. Group level: level (int), no groups (false).
  470. * Default false.
  471. * @return bool Not already in the group or a lower group.
  472. */
  473. public function set_group( $handle, $recursion, $group = false ) {
  474. if ( isset( $this->registered[ $handle ]->args ) && 1 === $this->registered[ $handle ]->args ) {
  475. $grp = 1;
  476. } else {
  477. $grp = (int) $this->get_data( $handle, 'group' );
  478. }
  479. if ( false !== $group && $grp > $group ) {
  480. $grp = $group;
  481. }
  482. return parent::set_group( $handle, $recursion, $grp );
  483. }
  484. /**
  485. * Sets a translation textdomain.
  486. *
  487. * @since 5.0.0
  488. * @since 5.1.0 The `$domain` parameter was made optional.
  489. *
  490. * @param string $handle Name of the script to register a translation domain to.
  491. * @param string $domain Optional. Text domain. Default 'default'.
  492. * @param string $path Optional. The full file path to the directory containing translation files.
  493. * @return bool True if the text domain was registered, false if not.
  494. */
  495. public function set_translations( $handle, $domain = 'default', $path = '' ) {
  496. if ( ! isset( $this->registered[ $handle ] ) ) {
  497. return false;
  498. }
  499. /** @var \_WP_Dependency $obj */
  500. $obj = $this->registered[ $handle ];
  501. if ( ! in_array( 'wp-i18n', $obj->deps, true ) ) {
  502. $obj->deps[] = 'wp-i18n';
  503. }
  504. return $obj->set_translations( $domain, $path );
  505. }
  506. /**
  507. * Prints translations set for a specific handle.
  508. *
  509. * @since 5.0.0
  510. *
  511. * @param string $handle Name of the script to add the inline script to.
  512. * Must be lowercase.
  513. * @param bool $display Optional. Whether to print the script
  514. * instead of just returning it. Default true.
  515. * @return string|false Script on success, false otherwise.
  516. */
  517. public function print_translations( $handle, $display = true ) {
  518. if ( ! isset( $this->registered[ $handle ] ) || empty( $this->registered[ $handle ]->textdomain ) ) {
  519. return false;
  520. }
  521. $domain = $this->registered[ $handle ]->textdomain;
  522. $path = '';
  523. if ( isset( $this->registered[ $handle ]->translations_path ) ) {
  524. $path = $this->registered[ $handle ]->translations_path;
  525. }
  526. $json_translations = load_script_textdomain( $handle, $domain, $path );
  527. if ( ! $json_translations ) {
  528. return false;
  529. }
  530. $output = <<<JS
  531. ( function( domain, translations ) {
  532. var localeData = translations.locale_data[ domain ] || translations.locale_data.messages;
  533. localeData[""].domain = domain;
  534. wp.i18n.setLocaleData( localeData, domain );
  535. } )( "{$domain}", {$json_translations} );
  536. JS;
  537. if ( $display ) {
  538. printf( "<script%s id='%s-js-translations'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), $output );
  539. }
  540. return $output;
  541. }
  542. /**
  543. * Determines script dependencies.
  544. *
  545. * @since 2.1.0
  546. *
  547. * @see WP_Dependencies::all_deps()
  548. *
  549. * @param string|string[] $handles Item handle (string) or item handles (array of strings).
  550. * @param bool $recursion Optional. Internal flag that function is calling itself.
  551. * Default false.
  552. * @param int|false $group Optional. Group level: level (int), no groups (false).
  553. * Default false.
  554. * @return bool True on success, false on failure.
  555. */
  556. public function all_deps( $handles, $recursion = false, $group = false ) {
  557. $r = parent::all_deps( $handles, $recursion, $group );
  558. if ( ! $recursion ) {
  559. /**
  560. * Filters the list of script dependencies left to print.
  561. *
  562. * @since 2.3.0
  563. *
  564. * @param string[] $to_do An array of script dependency handles.
  565. */
  566. $this->to_do = apply_filters( 'print_scripts_array', $this->to_do );
  567. }
  568. return $r;
  569. }
  570. /**
  571. * Processes items and dependencies for the head group.
  572. *
  573. * @since 2.8.0
  574. *
  575. * @see WP_Dependencies::do_items()
  576. *
  577. * @return string[] Handles of items that have been processed.
  578. */
  579. public function do_head_items() {
  580. $this->do_items( false, 0 );
  581. return $this->done;
  582. }
  583. /**
  584. * Processes items and dependencies for the footer group.
  585. *
  586. * @since 2.8.0
  587. *
  588. * @see WP_Dependencies::do_items()
  589. *
  590. * @return string[] Handles of items that have been processed.
  591. */
  592. public function do_footer_items() {
  593. $this->do_items( false, 1 );
  594. return $this->done;
  595. }
  596. /**
  597. * Whether a handle's source is in a default directory.
  598. *
  599. * @since 2.8.0
  600. *
  601. * @param string $src The source of the enqueued script.
  602. * @return bool True if found, false if not.
  603. */
  604. public function in_default_dir( $src ) {
  605. if ( ! $this->default_dirs ) {
  606. return true;
  607. }
  608. if ( 0 === strpos( $src, '/' . WPINC . '/js/l10n' ) ) {
  609. return false;
  610. }
  611. foreach ( (array) $this->default_dirs as $test ) {
  612. if ( 0 === strpos( $src, $test ) ) {
  613. return true;
  614. }
  615. }
  616. return false;
  617. }
  618. /**
  619. * Resets class properties.
  620. *
  621. * @since 2.8.0
  622. */
  623. public function reset() {
  624. $this->do_concat = false;
  625. $this->print_code = '';
  626. $this->concat = '';
  627. $this->concat_version = '';
  628. $this->print_html = '';
  629. $this->ext_version = '';
  630. $this->ext_handles = '';
  631. }
  632. }