[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/ -> class.wp-scripts.php (source)

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


Generated: Wed Oct 28 01:00:03 2020 Cross-referenced by PHPXref 0.7.1