[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/widgets/ -> class-wp-widget-media.php (source)

   1  <?php
   2  /**
   3   * Widget API: WP_Media_Widget class
   4   *
   5   * @package WordPress
   6   * @subpackage Widgets
   7   * @since 4.8.0
   8   */
   9  
  10  /**
  11   * Core class that implements a media widget.
  12   *
  13   * @since 4.8.0
  14   *
  15   * @see WP_Widget
  16   */
  17  abstract class WP_Widget_Media extends WP_Widget {
  18  
  19      /**
  20       * Translation labels.
  21       *
  22       * @since 4.8.0
  23       * @var array
  24       */
  25      public $l10n = array(
  26          'add_to_widget'              => '',
  27          'replace_media'              => '',
  28          'edit_media'                 => '',
  29          'media_library_state_multi'  => '',
  30          'media_library_state_single' => '',
  31          'missing_attachment'         => '',
  32          'no_media_selected'          => '',
  33          'add_media'                  => '',
  34      );
  35  
  36      /**
  37       * Whether or not the widget has been registered yet.
  38       *
  39       * @since 4.8.1
  40       * @var bool
  41       */
  42      protected $registered = false;
  43  
  44      /**
  45       * The default widget description.
  46       *
  47       * @since 6.0.0
  48       * @var string
  49       */
  50      protected static $default_description = '';
  51  
  52      /**
  53       * The default localized strings used by the widget.
  54       *
  55       * @since 6.0.0
  56       * @var string[]
  57       */
  58      protected static $l10n_defaults = array();
  59  
  60      /**
  61       * Constructor.
  62       *
  63       * @since 4.8.0
  64       *
  65       * @param string $id_base         Base ID for the widget, lowercase and unique.
  66       * @param string $name            Name for the widget displayed on the configuration page.
  67       * @param array  $widget_options  Optional. Widget options. See wp_register_sidebar_widget() for
  68       *                                information on accepted arguments. Default empty array.
  69       * @param array  $control_options Optional. Widget control options. See wp_register_widget_control()
  70       *                                for information on accepted arguments. Default empty array.
  71       */
  72  	public function __construct( $id_base, $name, $widget_options = array(), $control_options = array() ) {
  73          $widget_opts = wp_parse_args(
  74              $widget_options,
  75              array(
  76                  'description'                 => self::get_default_description(),
  77                  'customize_selective_refresh' => true,
  78                  'show_instance_in_rest'       => true,
  79                  'mime_type'                   => '',
  80              )
  81          );
  82  
  83          $control_opts = wp_parse_args( $control_options, array() );
  84  
  85          $this->l10n = array_merge( self::get_l10n_defaults(), array_filter( $this->l10n ) );
  86  
  87          parent::__construct(
  88              $id_base,
  89              $name,
  90              $widget_opts,
  91              $control_opts
  92          );
  93      }
  94  
  95      /**
  96       * Add hooks while registering all widget instances of this widget class.
  97       *
  98       * @since 4.8.0
  99       *
 100       * @param int $number Optional. The unique order number of this widget instance
 101       *                    compared to other instances of the same class. Default -1.
 102       */
 103  	public function _register_one( $number = -1 ) {
 104          parent::_register_one( $number );
 105          if ( $this->registered ) {
 106              return;
 107          }
 108          $this->registered = true;
 109  
 110          /*
 111           * Note that the widgets component in the customizer will also do
 112           * the 'admin_print_scripts-widgets.php' action in WP_Customize_Widgets::print_scripts().
 113           */
 114          add_action( 'admin_print_scripts-widgets.php', array( $this, 'enqueue_admin_scripts' ) );
 115  
 116          if ( $this->is_preview() ) {
 117              add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_preview_scripts' ) );
 118          }
 119  
 120          /*
 121           * Note that the widgets component in the customizer will also do
 122           * the 'admin_footer-widgets.php' action in WP_Customize_Widgets::print_footer_scripts().
 123           */
 124          add_action( 'admin_footer-widgets.php', array( $this, 'render_control_template_scripts' ) );
 125  
 126          add_filter( 'display_media_states', array( $this, 'display_media_state' ), 10, 2 );
 127      }
 128  
 129      /**
 130       * Get schema for properties of a widget instance (item).
 131       *
 132       * @since 4.8.0
 133       *
 134       * @see WP_REST_Controller::get_item_schema()
 135       * @see WP_REST_Controller::get_additional_fields()
 136       * @link https://core.trac.wordpress.org/ticket/35574
 137       *
 138       * @return array Schema for properties.
 139       */
 140  	public function get_instance_schema() {
 141          $schema = array(
 142              'attachment_id' => array(
 143                  'type'        => 'integer',
 144                  'default'     => 0,
 145                  'minimum'     => 0,
 146                  'description' => __( 'Attachment post ID' ),
 147                  'media_prop'  => 'id',
 148              ),
 149              'url'           => array(
 150                  'type'        => 'string',
 151                  'default'     => '',
 152                  'format'      => 'uri',
 153                  'description' => __( 'URL to the media file' ),
 154              ),
 155              'title'         => array(
 156                  'type'                  => 'string',
 157                  'default'               => '',
 158                  'sanitize_callback'     => 'sanitize_text_field',
 159                  'description'           => __( 'Title for the widget' ),
 160                  'should_preview_update' => false,
 161              ),
 162          );
 163  
 164          /**
 165           * Filters the media widget instance schema to add additional properties.
 166           *
 167           * @since 4.9.0
 168           *
 169           * @param array           $schema Instance schema.
 170           * @param WP_Widget_Media $widget Widget object.
 171           */
 172          $schema = apply_filters( "widget_{$this->id_base}_instance_schema", $schema, $this );
 173  
 174          return $schema;
 175      }
 176  
 177      /**
 178       * Determine if the supplied attachment is for a valid attachment post with the specified MIME type.
 179       *
 180       * @since 4.8.0
 181       *
 182       * @param int|WP_Post $attachment Attachment post ID or object.
 183       * @param string      $mime_type  MIME type.
 184       * @return bool Is matching MIME type.
 185       */
 186  	public function is_attachment_with_mime_type( $attachment, $mime_type ) {
 187          if ( empty( $attachment ) ) {
 188              return false;
 189          }
 190          $attachment = get_post( $attachment );
 191          if ( ! $attachment ) {
 192              return false;
 193          }
 194          if ( 'attachment' !== $attachment->post_type ) {
 195              return false;
 196          }
 197          return wp_attachment_is( $mime_type, $attachment );
 198      }
 199  
 200      /**
 201       * Sanitize a token list string, such as used in HTML rel and class attributes.
 202       *
 203       * @since 4.8.0
 204       *
 205       * @link http://w3c.github.io/html/infrastructure.html#space-separated-tokens
 206       * @link https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList
 207       * @param string|array $tokens List of tokens separated by spaces, or an array of tokens.
 208       * @return string Sanitized token string list.
 209       */
 210  	public function sanitize_token_list( $tokens ) {
 211          if ( is_string( $tokens ) ) {
 212              $tokens = preg_split( '/\s+/', trim( $tokens ) );
 213          }
 214          $tokens = array_map( 'sanitize_html_class', $tokens );
 215          $tokens = array_filter( $tokens );
 216          return implode( ' ', $tokens );
 217      }
 218  
 219      /**
 220       * Displays the widget on the front-end.
 221       *
 222       * @since 4.8.0
 223       *
 224       * @see WP_Widget::widget()
 225       *
 226       * @param array $args     Display arguments including before_title, after_title, before_widget, and after_widget.
 227       * @param array $instance Saved setting from the database.
 228       */
 229  	public function widget( $args, $instance ) {
 230          $instance = wp_parse_args( $instance, wp_list_pluck( $this->get_instance_schema(), 'default' ) );
 231  
 232          // Short-circuit if no media is selected.
 233          if ( ! $this->has_content( $instance ) ) {
 234              return;
 235          }
 236  
 237          echo $args['before_widget'];
 238  
 239          /** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
 240          $title = apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base );
 241  
 242          if ( $title ) {
 243              echo $args['before_title'] . $title . $args['after_title'];
 244          }
 245  
 246          /**
 247           * Filters the media widget instance prior to rendering the media.
 248           *
 249           * @since 4.8.0
 250           *
 251           * @param array           $instance Instance data.
 252           * @param array           $args     Widget args.
 253           * @param WP_Widget_Media $widget   Widget object.
 254           */
 255          $instance = apply_filters( "widget_{$this->id_base}_instance", $instance, $args, $this );
 256  
 257          $this->render_media( $instance );
 258  
 259          echo $args['after_widget'];
 260      }
 261  
 262      /**
 263       * Sanitizes the widget form values as they are saved.
 264       *
 265       * @since 4.8.0
 266       * @since 5.9.0 Renamed `$instance` to `$old_instance` to match parent class
 267       *              for PHP 8 named parameter support.
 268       *
 269       * @see WP_Widget::update()
 270       * @see WP_REST_Request::has_valid_params()
 271       * @see WP_REST_Request::sanitize_params()
 272       *
 273       * @param array $new_instance Values just sent to be saved.
 274       * @param array $old_instance Previously saved values from database.
 275       * @return array Updated safe values to be saved.
 276       */
 277  	public function update( $new_instance, $old_instance ) {
 278  
 279          $schema = $this->get_instance_schema();
 280          foreach ( $schema as $field => $field_schema ) {
 281              if ( ! array_key_exists( $field, $new_instance ) ) {
 282                  continue;
 283              }
 284              $value = $new_instance[ $field ];
 285  
 286              /*
 287               * Workaround for rest_validate_value_from_schema() due to the fact that
 288               * rest_is_boolean( '' ) === false, while rest_is_boolean( '1' ) is true.
 289               */
 290              if ( 'boolean' === $field_schema['type'] && '' === $value ) {
 291                  $value = false;
 292              }
 293  
 294              if ( true !== rest_validate_value_from_schema( $value, $field_schema, $field ) ) {
 295                  continue;
 296              }
 297  
 298              $value = rest_sanitize_value_from_schema( $value, $field_schema );
 299  
 300              // @codeCoverageIgnoreStart
 301              if ( is_wp_error( $value ) ) {
 302                  continue; // Handle case when rest_sanitize_value_from_schema() ever returns WP_Error as its phpdoc @return tag indicates.
 303              }
 304  
 305              // @codeCoverageIgnoreEnd
 306              if ( isset( $field_schema['sanitize_callback'] ) ) {
 307                  $value = call_user_func( $field_schema['sanitize_callback'], $value );
 308              }
 309              if ( is_wp_error( $value ) ) {
 310                  continue;
 311              }
 312              $old_instance[ $field ] = $value;
 313          }
 314  
 315          return $old_instance;
 316      }
 317  
 318      /**
 319       * Render the media on the frontend.
 320       *
 321       * @since 4.8.0
 322       *
 323       * @param array $instance Widget instance props.
 324       */
 325      abstract public function render_media( $instance );
 326  
 327      /**
 328       * Outputs the settings update form.
 329       *
 330       * Note that the widget UI itself is rendered with JavaScript via `MediaWidgetControl#render()`.
 331       *
 332       * @since 4.8.0
 333       *
 334       * @see \WP_Widget_Media::render_control_template_scripts() Where the JS template is located.
 335       *
 336       * @param array $instance Current settings.
 337       */
 338  	final public function form( $instance ) {
 339          $instance_schema = $this->get_instance_schema();
 340          $instance        = wp_array_slice_assoc(
 341              wp_parse_args( (array) $instance, wp_list_pluck( $instance_schema, 'default' ) ),
 342              array_keys( $instance_schema )
 343          );
 344  
 345          foreach ( $instance as $name => $value ) : ?>
 346              <input
 347                  type="hidden"
 348                  data-property="<?php echo esc_attr( $name ); ?>"
 349                  class="media-widget-instance-property"
 350                  name="<?php echo esc_attr( $this->get_field_name( $name ) ); ?>"
 351                  id="<?php echo esc_attr( $this->get_field_id( $name ) ); // Needed specifically by wpWidgets.appendTitle(). ?>"
 352                  value="<?php echo esc_attr( is_array( $value ) ? implode( ',', $value ) : (string) $value ); ?>"
 353              />
 354              <?php
 355          endforeach;
 356      }
 357  
 358      /**
 359       * Filters the default media display states for items in the Media list table.
 360       *
 361       * @since 4.8.0
 362       *
 363       * @param array   $states An array of media states.
 364       * @param WP_Post $post   The current attachment object.
 365       * @return array
 366       */
 367  	public function display_media_state( $states, $post = null ) {
 368          if ( ! $post ) {
 369              $post = get_post();
 370          }
 371  
 372          // Count how many times this attachment is used in widgets.
 373          $use_count = 0;
 374          foreach ( $this->get_settings() as $instance ) {
 375              if ( isset( $instance['attachment_id'] ) && $instance['attachment_id'] === $post->ID ) {
 376                  ++$use_count;
 377              }
 378          }
 379  
 380          if ( 1 === $use_count ) {
 381              $states[] = $this->l10n['media_library_state_single'];
 382          } elseif ( $use_count > 0 ) {
 383              $states[] = sprintf( translate_nooped_plural( $this->l10n['media_library_state_multi'], $use_count ), number_format_i18n( $use_count ) );
 384          }
 385  
 386          return $states;
 387      }
 388  
 389      /**
 390       * Enqueue preview scripts.
 391       *
 392       * These scripts normally are enqueued just-in-time when a widget is rendered.
 393       * In the customizer, however, widgets can be dynamically added and rendered via
 394       * selective refresh, and so it is important to unconditionally enqueue them in
 395       * case a widget does get added.
 396       *
 397       * @since 4.8.0
 398       */
 399  	public function enqueue_preview_scripts() {}
 400  
 401      /**
 402       * Loads the required scripts and styles for the widget control.
 403       *
 404       * @since 4.8.0
 405       */
 406  	public function enqueue_admin_scripts() {
 407          wp_enqueue_media();
 408          wp_enqueue_script( 'media-widgets' );
 409      }
 410  
 411      /**
 412       * Render form template scripts.
 413       *
 414       * @since 4.8.0
 415       */
 416  	public function render_control_template_scripts() {
 417          ?>
 418          <script type="text/html" id="tmpl-widget-media-<?php echo esc_attr( $this->id_base ); ?>-control">
 419              <# var elementIdPrefix = 'el' + String( Math.random() ) + '_' #>
 420              <p>
 421                  <label for="{{ elementIdPrefix }}title"><?php esc_html_e( 'Title:' ); ?></label>
 422                  <input id="{{ elementIdPrefix }}title" type="text" class="widefat title">
 423              </p>
 424              <div class="media-widget-preview <?php echo esc_attr( $this->id_base ); ?>">
 425                  <div class="attachment-media-view">
 426                      <button type="button" class="select-media button-add-media not-selected">
 427                          <?php echo esc_html( $this->l10n['add_media'] ); ?>
 428                      </button>
 429                  </div>
 430              </div>
 431              <p class="media-widget-buttons">
 432                  <button type="button" class="button edit-media selected">
 433                      <?php echo esc_html( $this->l10n['edit_media'] ); ?>
 434                  </button>
 435              <?php if ( ! empty( $this->l10n['replace_media'] ) ) : ?>
 436                  <button type="button" class="button change-media select-media selected">
 437                      <?php echo esc_html( $this->l10n['replace_media'] ); ?>
 438                  </button>
 439              <?php endif; ?>
 440              </p>
 441              <div class="media-widget-fields">
 442              </div>
 443          </script>
 444          <?php
 445      }
 446  
 447      /**
 448       * Resets the cache for the default labels.
 449       *
 450       * @since 6.0.0
 451       */
 452  	public static function reset_default_labels() {
 453          self::$default_description = '';
 454          self::$l10n_defaults       = array();
 455      }
 456  
 457      /**
 458       * Whether the widget has content to show.
 459       *
 460       * @since 4.8.0
 461       *
 462       * @param array $instance Widget instance props.
 463       * @return bool Whether widget has content.
 464       */
 465  	protected function has_content( $instance ) {
 466          return ( $instance['attachment_id'] && 'attachment' === get_post_type( $instance['attachment_id'] ) ) || $instance['url'];
 467      }
 468  
 469      /**
 470       * Returns the default description of the widget.
 471       *
 472       * @since 6.0.0
 473       *
 474       * @return string
 475       */
 476  	protected static function get_default_description() {
 477          if ( self::$default_description ) {
 478              return self::$default_description;
 479          }
 480  
 481          self::$default_description = __( 'A media item.' );
 482          return self::$default_description;
 483      }
 484  
 485      /**
 486       * Returns the default localized strings used by the widget.
 487       *
 488       * @since 6.0.0
 489       *
 490       * @return (string|array)[]
 491       */
 492  	protected static function get_l10n_defaults() {
 493          if ( ! empty( self::$l10n_defaults ) ) {
 494              return self::$l10n_defaults;
 495          }
 496  
 497          self::$l10n_defaults = array(
 498              'no_media_selected'          => __( 'No media selected' ),
 499              'add_media'                  => _x( 'Add Media', 'label for button in the media widget' ),
 500              'replace_media'              => _x( 'Replace Media', 'label for button in the media widget; should preferably not be longer than ~13 characters long' ),
 501              'edit_media'                 => _x( 'Edit Media', 'label for button in the media widget; should preferably not be longer than ~13 characters long' ),
 502              'add_to_widget'              => __( 'Add to Widget' ),
 503              'missing_attachment'         => sprintf(
 504                  /* translators: %s: URL to media library. */
 505                  __( 'That file cannot be found. Check your <a href="%s">media library</a> and make sure it was not deleted.' ),
 506                  esc_url( admin_url( 'upload.php' ) )
 507              ),
 508              /* translators: %d: Widget count. */
 509              'media_library_state_multi'  => _n_noop( 'Media Widget (%d)', 'Media Widget (%d)' ),
 510              'media_library_state_single' => __( 'Media Widget' ),
 511              'unsupported_file_type'      => __( 'Looks like this is not the correct kind of file. Please link to an appropriate file instead.' ),
 512          );
 513  
 514          return self::$l10n_defaults;
 515      }
 516  }


Generated : Sat Dec 21 08:20:01 2024 Cross-referenced by PHPXref