class-wp-widget-media.php 15 KB

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