[ Index ]

PHP Cross Reference of WordPress

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


Generated: Mon Nov 29 01:00:03 2021 Cross-referenced by PHPXref 0.7.1