[ 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 active 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 $wp_scripts 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 `$display` 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   $display Optional. Whether to print the extra script
 200       *                        instead of just returning it. Default true.
 201       * @return bool|string|void Void if no data exists, extra scripts if `$display` is true,
 202       *                          true otherwise.
 203       */
 204  	public function print_scripts_l10n( $handle, $display = true ) {
 205          _deprecated_function( __FUNCTION__, '3.3.0', 'WP_Scripts::print_extra_script()' );
 206          return $this->print_extra_script( $handle, $display );
 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   $display Optional. Whether to print the extra script
 216       *                        instead of just returning it. Default true.
 217       * @return bool|string|void Void if no data exists, extra scripts if `$display` is true,
 218       *                          true otherwise.
 219       */
 220  	public function print_extra_script( $handle, $display = true ) {
 221          $output = $this->get_data( $handle, 'data' );
 222          if ( ! $output ) {
 223              return;
 224          }
 225  
 226          if ( ! $display ) {
 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          /*
 315           * Prevent concatenation of scripts if the text domain is defined
 316           * to ensure the dependency order is respected.
 317           */
 318          $translations_stop_concat = ! empty( $obj->textdomain );
 319  
 320          $translations = $this->print_translations( $handle, false );
 321          if ( $translations ) {
 322              $translations = sprintf( "<script%s id='%s-js-translations'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), $translations );
 323          }
 324  
 325          if ( $this->do_concat ) {
 326              /**
 327               * Filters the script loader source.
 328               *
 329               * @since 2.2.0
 330               *
 331               * @param string $src    Script loader source path.
 332               * @param string $handle Script handle.
 333               */
 334              $srce = apply_filters( 'script_loader_src', $src, $handle );
 335  
 336              if ( $this->in_default_dir( $srce ) && ( $before_handle || $after_handle || $translations_stop_concat ) ) {
 337                  $this->do_concat = false;
 338  
 339                  // Have to print the so-far concatenated scripts right away to maintain the right order.
 340                  _print_scripts();
 341                  $this->reset();
 342              } elseif ( $this->in_default_dir( $srce ) && ! $conditional ) {
 343                  $this->print_code     .= $this->print_extra_script( $handle, false );
 344                  $this->concat         .= "$handle,";
 345                  $this->concat_version .= "$handle$ver";
 346                  return true;
 347              } else {
 348                  $this->ext_handles .= "$handle,";
 349                  $this->ext_version .= "$handle$ver";
 350              }
 351          }
 352  
 353          $has_conditional_data = $conditional && $this->get_data( $handle, 'data' );
 354  
 355          if ( $has_conditional_data ) {
 356              echo $cond_before;
 357          }
 358  
 359          $this->print_extra_script( $handle );
 360  
 361          if ( $has_conditional_data ) {
 362              echo $cond_after;
 363          }
 364  
 365          // A single item may alias a set of items, by having dependencies, but no source.
 366          if ( ! $src ) {
 367              if ( $inline_script_tag ) {
 368                  if ( $this->do_concat ) {
 369                      $this->print_html .= $inline_script_tag;
 370                  } else {
 371                      echo $inline_script_tag;
 372                  }
 373              }
 374  
 375              return true;
 376          }
 377  
 378          if ( ! preg_match( '|^(https?:)?//|', $src ) && ! ( $this->content_url && 0 === strpos( $src, $this->content_url ) ) ) {
 379              $src = $this->base_url . $src;
 380          }
 381  
 382          if ( ! empty( $ver ) ) {
 383              $src = add_query_arg( 'ver', $ver, $src );
 384          }
 385  
 386          /** This filter is documented in wp-includes/class.wp-scripts.php */
 387          $src = esc_url( apply_filters( 'script_loader_src', $src, $handle ) );
 388  
 389          if ( ! $src ) {
 390              return true;
 391          }
 392  
 393          $tag  = $translations . $cond_before . $before_handle;
 394          $tag .= sprintf( "<script%s src='%s' id='%s-js'></script>\n", $this->type_attr, $src, esc_attr( $handle ) );
 395          $tag .= $after_handle . $cond_after;
 396  
 397          /**
 398           * Filters the HTML script tag of an enqueued script.
 399           *
 400           * @since 4.1.0
 401           *
 402           * @param string $tag    The `<script>` tag for the enqueued script.
 403           * @param string $handle The script's registered handle.
 404           * @param string $src    The script's source URL.
 405           */
 406          $tag = apply_filters( 'script_loader_tag', $tag, $handle, $src );
 407  
 408          if ( $this->do_concat ) {
 409              $this->print_html .= $tag;
 410          } else {
 411              echo $tag;
 412          }
 413  
 414          return true;
 415      }
 416  
 417      /**
 418       * Adds extra code to a registered script.
 419       *
 420       * @since 4.5.0
 421       *
 422       * @param string $handle   Name of the script to add the inline script to.
 423       *                         Must be lowercase.
 424       * @param string $data     String containing the JavaScript to be added.
 425       * @param string $position Optional. Whether to add the inline script
 426       *                         before the handle or after. Default 'after'.
 427       * @return bool True on success, false on failure.
 428       */
 429  	public function add_inline_script( $handle, $data, $position = 'after' ) {
 430          if ( ! $data ) {
 431              return false;
 432          }
 433  
 434          if ( 'after' !== $position ) {
 435              $position = 'before';
 436          }
 437  
 438          $script   = (array) $this->get_data( $handle, $position );
 439          $script[] = $data;
 440  
 441          return $this->add_data( $handle, $position, $script );
 442      }
 443  
 444      /**
 445       * Prints inline scripts registered for a specific handle.
 446       *
 447       * @since 4.5.0
 448       *
 449       * @param string $handle   Name of the script to add the inline script to.
 450       *                         Must be lowercase.
 451       * @param string $position Optional. Whether to add the inline script
 452       *                         before the handle or after. Default 'after'.
 453       * @param bool   $display  Optional. Whether to print the script
 454       *                         instead of just returning it. Default true.
 455       * @return string|false Script on success, false otherwise.
 456       */
 457  	public function print_inline_script( $handle, $position = 'after', $display = true ) {
 458          $output = $this->get_data( $handle, $position );
 459  
 460          if ( empty( $output ) ) {
 461              return false;
 462          }
 463  
 464          $output = trim( implode( "\n", $output ), "\n" );
 465  
 466          if ( $display ) {
 467              printf( "<script%s id='%s-js-%s'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), esc_attr( $position ), $output );
 468          }
 469  
 470          return $output;
 471      }
 472  
 473      /**
 474       * Localizes a script, only if the script has already been added.
 475       *
 476       * @since 2.1.0
 477       *
 478       * @param string $handle      Name of the script to attach data to.
 479       * @param string $object_name Name of the variable that will contain the data.
 480       * @param array  $l10n        Array of data to localize.
 481       * @return bool True on success, false on failure.
 482       */
 483  	public function localize( $handle, $object_name, $l10n ) {
 484          if ( 'jquery' === $handle ) {
 485              $handle = 'jquery-core';
 486          }
 487  
 488          if ( is_array( $l10n ) && isset( $l10n['l10n_print_after'] ) ) { // back compat, preserve the code in 'l10n_print_after' if present.
 489              $after = $l10n['l10n_print_after'];
 490              unset( $l10n['l10n_print_after'] );
 491          }
 492  
 493          if ( ! is_array( $l10n ) ) {
 494              _doing_it_wrong(
 495                  __METHOD__,
 496                  sprintf(
 497                      /* translators: 1: $l10n, 2: wp_add_inline_script() */
 498                      __( 'The %1$s parameter must be an array. To pass arbitrary data to scripts, use the %2$s function instead.' ),
 499                      '<code>$l10n</code>',
 500                      '<code>wp_add_inline_script()</code>'
 501                  ),
 502                  '5.7.0'
 503              );
 504          }
 505  
 506          if ( is_string( $l10n ) ) {
 507              $l10n = html_entity_decode( $l10n, ENT_QUOTES, 'UTF-8' );
 508          } else {
 509              foreach ( (array) $l10n as $key => $value ) {
 510                  if ( ! is_scalar( $value ) ) {
 511                      continue;
 512                  }
 513  
 514                  $l10n[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
 515              }
 516          }
 517  
 518          $script = "var $object_name = " . wp_json_encode( $l10n ) . ';';
 519  
 520          if ( ! empty( $after ) ) {
 521              $script .= "\n$after;";
 522          }
 523  
 524          $data = $this->get_data( $handle, 'data' );
 525  
 526          if ( ! empty( $data ) ) {
 527              $script = "$data\n$script";
 528          }
 529  
 530          return $this->add_data( $handle, 'data', $script );
 531      }
 532  
 533      /**
 534       * Sets handle group.
 535       *
 536       * @since 2.8.0
 537       *
 538       * @see WP_Dependencies::set_group()
 539       *
 540       * @param string    $handle    Name of the item. Should be unique.
 541       * @param bool      $recursion Internal flag that calling function was called recursively.
 542       * @param int|false $group     Optional. Group level: level (int), no groups (false).
 543       *                             Default false.
 544       * @return bool Not already in the group or a lower group.
 545       */
 546  	public function set_group( $handle, $recursion, $group = false ) {
 547          if ( isset( $this->registered[ $handle ]->args ) && 1 === $this->registered[ $handle ]->args ) {
 548              $grp = 1;
 549          } else {
 550              $grp = (int) $this->get_data( $handle, 'group' );
 551          }
 552  
 553          if ( false !== $group && $grp > $group ) {
 554              $grp = $group;
 555          }
 556  
 557          return parent::set_group( $handle, $recursion, $grp );
 558      }
 559  
 560      /**
 561       * Sets a translation textdomain.
 562       *
 563       * @since 5.0.0
 564       * @since 5.1.0 The `$domain` parameter was made optional.
 565       *
 566       * @param string $handle Name of the script to register a translation domain to.
 567       * @param string $domain Optional. Text domain. Default 'default'.
 568       * @param string $path   Optional. The full file path to the directory containing translation files.
 569       * @return bool True if the text domain was registered, false if not.
 570       */
 571  	public function set_translations( $handle, $domain = 'default', $path = null ) {
 572          if ( ! isset( $this->registered[ $handle ] ) ) {
 573              return false;
 574          }
 575  
 576          /** @var \_WP_Dependency $obj */
 577          $obj = $this->registered[ $handle ];
 578  
 579          if ( ! in_array( 'wp-i18n', $obj->deps, true ) ) {
 580              $obj->deps[] = 'wp-i18n';
 581          }
 582  
 583          return $obj->set_translations( $domain, $path );
 584      }
 585  
 586      /**
 587       * Prints translations set for a specific handle.
 588       *
 589       * @since 5.0.0
 590       *
 591       * @param string $handle  Name of the script to add the inline script to.
 592       *                        Must be lowercase.
 593       * @param bool   $display Optional. Whether to print the script
 594       *                        instead of just returning it. Default true.
 595       * @return string|false Script on success, false otherwise.
 596       */
 597  	public function print_translations( $handle, $display = true ) {
 598          if ( ! isset( $this->registered[ $handle ] ) || empty( $this->registered[ $handle ]->textdomain ) ) {
 599              return false;
 600          }
 601  
 602          $domain = $this->registered[ $handle ]->textdomain;
 603          $path   = $this->registered[ $handle ]->translations_path;
 604  
 605          $json_translations = load_script_textdomain( $handle, $domain, $path );
 606  
 607          if ( ! $json_translations ) {
 608              return false;
 609          }
 610  
 611          $output = <<<JS
 612  ( function( domain, translations ) {
 613      var localeData = translations.locale_data[ domain ] || translations.locale_data.messages;
 614      localeData[""].domain = domain;
 615      wp.i18n.setLocaleData( localeData, domain );
 616  } )( "{$domain}", {$json_translations} );
 617  JS;
 618  
 619          if ( $display ) {
 620              printf( "<script%s id='%s-js-translations'>\n%s\n</script>\n", $this->type_attr, esc_attr( $handle ), $output );
 621          }
 622  
 623          return $output;
 624      }
 625  
 626      /**
 627       * Determines script dependencies.
 628       *
 629       * @since 2.1.0
 630       *
 631       * @see WP_Dependencies::all_deps()
 632       *
 633       * @param string|string[] $handles   Item handle (string) or item handles (array of strings).
 634       * @param bool            $recursion Optional. Internal flag that function is calling itself.
 635       *                                   Default false.
 636       * @param int|false       $group     Optional. Group level: level (int), no groups (false).
 637       *                                   Default false.
 638       * @return bool True on success, false on failure.
 639       */
 640  	public function all_deps( $handles, $recursion = false, $group = false ) {
 641          $r = parent::all_deps( $handles, $recursion, $group );
 642          if ( ! $recursion ) {
 643              /**
 644               * Filters the list of script dependencies left to print.
 645               *
 646               * @since 2.3.0
 647               *
 648               * @param string[] $to_do An array of script dependency handles.
 649               */
 650              $this->to_do = apply_filters( 'print_scripts_array', $this->to_do );
 651          }
 652          return $r;
 653      }
 654  
 655      /**
 656       * Processes items and dependencies for the head group.
 657       *
 658       * @since 2.8.0
 659       *
 660       * @see WP_Dependencies::do_items()
 661       *
 662       * @return string[] Handles of items that have been processed.
 663       */
 664  	public function do_head_items() {
 665          $this->do_items( false, 0 );
 666          return $this->done;
 667      }
 668  
 669      /**
 670       * Processes items and dependencies for the footer group.
 671       *
 672       * @since 2.8.0
 673       *
 674       * @see WP_Dependencies::do_items()
 675       *
 676       * @return string[] Handles of items that have been processed.
 677       */
 678  	public function do_footer_items() {
 679          $this->do_items( false, 1 );
 680          return $this->done;
 681      }
 682  
 683      /**
 684       * Whether a handle's source is in a default directory.
 685       *
 686       * @since 2.8.0
 687       *
 688       * @param string $src The source of the enqueued script.
 689       * @return bool True if found, false if not.
 690       */
 691  	public function in_default_dir( $src ) {
 692          if ( ! $this->default_dirs ) {
 693              return true;
 694          }
 695  
 696          if ( 0 === strpos( $src, '/' . WPINC . '/js/l10n' ) ) {
 697              return false;
 698          }
 699  
 700          foreach ( (array) $this->default_dirs as $test ) {
 701              if ( 0 === strpos( $src, $test ) ) {
 702                  return true;
 703              }
 704          }
 705          return false;
 706      }
 707  
 708      /**
 709       * Resets class properties.
 710       *
 711       * @since 2.8.0
 712       */
 713  	public function reset() {
 714          $this->do_concat      = false;
 715          $this->print_code     = '';
 716          $this->concat         = '';
 717          $this->concat_version = '';
 718          $this->print_html     = '';
 719          $this->ext_version    = '';
 720          $this->ext_handles    = '';
 721      }
 722  }


Generated: Sun Dec 22 01:00:02 2024 Cross-referenced by PHPXref 0.7.1