class-wp-widget-media.php 14 KB

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