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


Generated: Sun Jan 26 01:00:03 2020 Cross-referenced by PHPXref 0.7.1