class-wp-widget-media.php 13 KB

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