[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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


Generated: Tue Oct 22 08:20:01 2019 Cross-referenced by PHPXref 0.7