class-wp-widget-media.php (14104B)
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’t find that file. Check your <a href="%s">media library</a> and make sure it wasn’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’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 * 263 * @see WP_Widget::update() 264 * @see WP_REST_Request::has_valid_params() 265 * @see WP_REST_Request::sanitize_params() 266 * 267 * @param array $new_instance Values just sent to be saved. 268 * @param array $instance Previously saved values from database. 269 * @return array Updated safe values to be saved. 270 */ 271 public function update( $new_instance, $instance ) { 272 273 $schema = $this->get_instance_schema(); 274 foreach ( $schema as $field => $field_schema ) { 275 if ( ! array_key_exists( $field, $new_instance ) ) { 276 continue; 277 } 278 $value = $new_instance[ $field ]; 279 280 /* 281 * Workaround for rest_validate_value_from_schema() due to the fact that 282 * rest_is_boolean( '' ) === false, while rest_is_boolean( '1' ) is true. 283 */ 284 if ( 'boolean' === $field_schema['type'] && '' === $value ) { 285 $value = false; 286 } 287 288 if ( true !== rest_validate_value_from_schema( $value, $field_schema, $field ) ) { 289 continue; 290 } 291 292 $value = rest_sanitize_value_from_schema( $value, $field_schema ); 293 294 // @codeCoverageIgnoreStart 295 if ( is_wp_error( $value ) ) { 296 continue; // Handle case when rest_sanitize_value_from_schema() ever returns WP_Error as its phpdoc @return tag indicates. 297 } 298 299 // @codeCoverageIgnoreEnd 300 if ( isset( $field_schema['sanitize_callback'] ) ) { 301 $value = call_user_func( $field_schema['sanitize_callback'], $value ); 302 } 303 if ( is_wp_error( $value ) ) { 304 continue; 305 } 306 $instance[ $field ] = $value; 307 } 308 309 return $instance; 310 } 311 312 /** 313 * Render the media on the frontend. 314 * 315 * @since 4.8.0 316 * 317 * @param array $instance Widget instance props. 318 * @return string 319 */ 320 abstract public function render_media( $instance ); 321 322 /** 323 * Outputs the settings update form. 324 * 325 * Note that the widget UI itself is rendered with JavaScript via `MediaWidgetControl#render()`. 326 * 327 * @since 4.8.0 328 * 329 * @see \WP_Widget_Media::render_control_template_scripts() Where the JS template is located. 330 * 331 * @param array $instance Current settings. 332 */ 333 final public function form( $instance ) { 334 $instance_schema = $this->get_instance_schema(); 335 $instance = wp_array_slice_assoc( 336 wp_parse_args( (array) $instance, wp_list_pluck( $instance_schema, 'default' ) ), 337 array_keys( $instance_schema ) 338 ); 339 340 foreach ( $instance as $name => $value ) : ?> 341 <input 342 type="hidden" 343 data-property="<?php echo esc_attr( $name ); ?>" 344 class="media-widget-instance-property" 345 name="<?php echo esc_attr( $this->get_field_name( $name ) ); ?>" 346 id="<?php echo esc_attr( $this->get_field_id( $name ) ); // Needed specifically by wpWidgets.appendTitle(). ?>" 347 value="<?php echo esc_attr( is_array( $value ) ? implode( ',', $value ) : (string) $value ); ?>" 348 /> 349 <?php 350 endforeach; 351 } 352 353 /** 354 * Filters the default media display states for items in the Media list table. 355 * 356 * @since 4.8.0 357 * 358 * @param array $states An array of media states. 359 * @param WP_Post $post The current attachment object. 360 * @return array 361 */ 362 public function display_media_state( $states, $post = null ) { 363 if ( ! $post ) { 364 $post = get_post(); 365 } 366 367 // Count how many times this attachment is used in widgets. 368 $use_count = 0; 369 foreach ( $this->get_settings() as $instance ) { 370 if ( isset( $instance['attachment_id'] ) && $instance['attachment_id'] === $post->ID ) { 371 $use_count++; 372 } 373 } 374 375 if ( 1 === $use_count ) { 376 $states[] = $this->l10n['media_library_state_single']; 377 } elseif ( $use_count > 0 ) { 378 $states[] = sprintf( translate_nooped_plural( $this->l10n['media_library_state_multi'], $use_count ), number_format_i18n( $use_count ) ); 379 } 380 381 return $states; 382 } 383 384 /** 385 * Enqueue preview scripts. 386 * 387 * These scripts normally are enqueued just-in-time when a widget is rendered. 388 * In the customizer, however, widgets can be dynamically added and rendered via 389 * selective refresh, and so it is important to unconditionally enqueue them in 390 * case a widget does get added. 391 * 392 * @since 4.8.0 393 */ 394 public function enqueue_preview_scripts() {} 395 396 /** 397 * Loads the required scripts and styles for the widget control. 398 * 399 * @since 4.8.0 400 */ 401 public function enqueue_admin_scripts() { 402 wp_enqueue_media(); 403 wp_enqueue_script( 'media-widgets' ); 404 } 405 406 /** 407 * Render form template scripts. 408 * 409 * @since 4.8.0 410 */ 411 public function render_control_template_scripts() { 412 ?> 413 <script type="text/html" id="tmpl-widget-media-<?php echo esc_attr( $this->id_base ); ?>-control"> 414 <# var elementIdPrefix = 'el' + String( Math.random() ) + '_' #> 415 <p> 416 <label for="{{ elementIdPrefix }}title"><?php esc_html_e( 'Title:' ); ?></label> 417 <input id="{{ elementIdPrefix }}title" type="text" class="widefat title"> 418 </p> 419 <div class="media-widget-preview <?php echo esc_attr( $this->id_base ); ?>"> 420 <div class="attachment-media-view"> 421 <button type="button" class="select-media button-add-media not-selected"> 422 <?php echo esc_html( $this->l10n['add_media'] ); ?> 423 </button> 424 </div> 425 </div> 426 <p class="media-widget-buttons"> 427 <button type="button" class="button edit-media selected"> 428 <?php echo esc_html( $this->l10n['edit_media'] ); ?> 429 </button> 430 <?php if ( ! empty( $this->l10n['replace_media'] ) ) : ?> 431 <button type="button" class="button change-media select-media selected"> 432 <?php echo esc_html( $this->l10n['replace_media'] ); ?> 433 </button> 434 <?php endif; ?> 435 </p> 436 <div class="media-widget-fields"> 437 </div> 438 </script> 439 <?php 440 } 441 442 /** 443 * Whether the widget has content to show. 444 * 445 * @since 4.8.0 446 * 447 * @param array $instance Widget instance props. 448 * @return bool Whether widget has content. 449 */ 450 protected function has_content( $instance ) { 451 return ( $instance['attachment_id'] && 'attachment' === get_post_type( $instance['attachment_id'] ) ) || $instance['url']; 452 } 453 }