Brak opisu

class-wp-widget-media.php 14KB

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