class-wp-widget-custom-html.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. <?php
  2. /**
  3. * Widget API: WP_Widget_Custom_HTML class
  4. *
  5. * @package WordPress
  6. * @subpackage Widgets
  7. * @since 4.8.1
  8. */
  9. /**
  10. * Core class used to implement a Custom HTML widget.
  11. *
  12. * @since 4.8.1
  13. *
  14. * @see WP_Widget
  15. */
  16. class WP_Widget_Custom_HTML extends WP_Widget {
  17. /**
  18. * Whether or not the widget has been registered yet.
  19. *
  20. * @since 4.9.0
  21. * @var bool
  22. */
  23. protected $registered = false;
  24. /**
  25. * Default instance.
  26. *
  27. * @since 4.8.1
  28. * @var array
  29. */
  30. protected $default_instance = array(
  31. 'title' => '',
  32. 'content' => '',
  33. );
  34. /**
  35. * Sets up a new Custom HTML widget instance.
  36. *
  37. * @since 4.8.1
  38. */
  39. public function __construct() {
  40. $widget_ops = array(
  41. 'classname' => 'widget_custom_html',
  42. 'description' => __( 'Arbitrary HTML code.' ),
  43. 'customize_selective_refresh' => true,
  44. 'show_instance_in_rest' => true,
  45. );
  46. $control_ops = array(
  47. 'width' => 400,
  48. 'height' => 350,
  49. );
  50. parent::__construct( 'custom_html', __( 'Custom HTML' ), $widget_ops, $control_ops );
  51. }
  52. /**
  53. * Add hooks for enqueueing assets when registering all widget instances of this widget class.
  54. *
  55. * @since 4.9.0
  56. *
  57. * @param int $number Optional. The unique order number of this widget instance
  58. * compared to other instances of the same class. Default -1.
  59. */
  60. public function _register_one( $number = -1 ) {
  61. parent::_register_one( $number );
  62. if ( $this->registered ) {
  63. return;
  64. }
  65. $this->registered = true;
  66. wp_add_inline_script( 'custom-html-widgets', sprintf( 'wp.customHtmlWidgets.idBases.push( %s );', wp_json_encode( $this->id_base ) ) );
  67. // Note that the widgets component in the customizer will also do
  68. // the 'admin_print_scripts-widgets.php' action in WP_Customize_Widgets::print_scripts().
  69. add_action( 'admin_print_scripts-widgets.php', array( $this, 'enqueue_admin_scripts' ) );
  70. // Note that the widgets component in the customizer will also do
  71. // the 'admin_footer-widgets.php' action in WP_Customize_Widgets::print_footer_scripts().
  72. add_action( 'admin_footer-widgets.php', array( 'WP_Widget_Custom_HTML', 'render_control_template_scripts' ) );
  73. // Note this action is used to ensure the help text is added to the end.
  74. add_action( 'admin_head-widgets.php', array( 'WP_Widget_Custom_HTML', 'add_help_text' ) );
  75. }
  76. /**
  77. * Filters gallery shortcode attributes.
  78. *
  79. * Prevents all of a site's attachments from being shown in a gallery displayed on a
  80. * non-singular template where a $post context is not available.
  81. *
  82. * @since 4.9.0
  83. *
  84. * @param array $attrs Attributes.
  85. * @return array Attributes.
  86. */
  87. public function _filter_gallery_shortcode_attrs( $attrs ) {
  88. if ( ! is_singular() && empty( $attrs['id'] ) && empty( $attrs['include'] ) ) {
  89. $attrs['id'] = -1;
  90. }
  91. return $attrs;
  92. }
  93. /**
  94. * Outputs the content for the current Custom HTML widget instance.
  95. *
  96. * @since 4.8.1
  97. *
  98. * @global WP_Post $post Global post object.
  99. *
  100. * @param array $args Display arguments including 'before_title', 'after_title',
  101. * 'before_widget', and 'after_widget'.
  102. * @param array $instance Settings for the current Custom HTML widget instance.
  103. */
  104. public function widget( $args, $instance ) {
  105. global $post;
  106. // Override global $post so filters (and shortcodes) apply in a consistent context.
  107. $original_post = $post;
  108. if ( is_singular() ) {
  109. // Make sure post is always the queried object on singular queries (not from another sub-query that failed to clean up the global $post).
  110. $post = get_queried_object();
  111. } else {
  112. // Nullify the $post global during widget rendering to prevent shortcodes from running with the unexpected context on archive queries.
  113. $post = null;
  114. }
  115. // Prevent dumping out all attachments from the media library.
  116. add_filter( 'shortcode_atts_gallery', array( $this, '_filter_gallery_shortcode_attrs' ) );
  117. $instance = array_merge( $this->default_instance, $instance );
  118. /** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
  119. $title = apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base );
  120. // Prepare instance data that looks like a normal Text widget.
  121. $simulated_text_widget_instance = array_merge(
  122. $instance,
  123. array(
  124. 'text' => isset( $instance['content'] ) ? $instance['content'] : '',
  125. 'filter' => false, // Because wpautop is not applied.
  126. 'visual' => false, // Because it wasn't created in TinyMCE.
  127. )
  128. );
  129. unset( $simulated_text_widget_instance['content'] ); // Was moved to 'text' prop.
  130. /** This filter is documented in wp-includes/widgets/class-wp-widget-text.php */
  131. $content = apply_filters( 'widget_text', $instance['content'], $simulated_text_widget_instance, $this );
  132. // Adds 'noopener' relationship, without duplicating values, to all HTML A elements that have a target.
  133. $content = wp_targeted_link_rel( $content );
  134. /**
  135. * Filters the content of the Custom HTML widget.
  136. *
  137. * @since 4.8.1
  138. *
  139. * @param string $content The widget content.
  140. * @param array $instance Array of settings for the current widget.
  141. * @param WP_Widget_Custom_HTML $widget Current Custom HTML widget instance.
  142. */
  143. $content = apply_filters( 'widget_custom_html_content', $content, $instance, $this );
  144. // Restore post global.
  145. $post = $original_post;
  146. remove_filter( 'shortcode_atts_gallery', array( $this, '_filter_gallery_shortcode_attrs' ) );
  147. // Inject the Text widget's container class name alongside this widget's class name for theme styling compatibility.
  148. $args['before_widget'] = preg_replace( '/(?<=\sclass=["\'])/', 'widget_text ', $args['before_widget'] );
  149. echo $args['before_widget'];
  150. if ( ! empty( $title ) ) {
  151. echo $args['before_title'] . $title . $args['after_title'];
  152. }
  153. echo '<div class="textwidget custom-html-widget">'; // The textwidget class is for theme styling compatibility.
  154. echo $content;
  155. echo '</div>';
  156. echo $args['after_widget'];
  157. }
  158. /**
  159. * Handles updating settings for the current Custom HTML widget instance.
  160. *
  161. * @since 4.8.1
  162. *
  163. * @param array $new_instance New settings for this instance as input by the user via
  164. * WP_Widget::form().
  165. * @param array $old_instance Old settings for this instance.
  166. * @return array Settings to save or bool false to cancel saving.
  167. */
  168. public function update( $new_instance, $old_instance ) {
  169. $instance = array_merge( $this->default_instance, $old_instance );
  170. $instance['title'] = sanitize_text_field( $new_instance['title'] );
  171. if ( current_user_can( 'unfiltered_html' ) ) {
  172. $instance['content'] = $new_instance['content'];
  173. } else {
  174. $instance['content'] = wp_kses_post( $new_instance['content'] );
  175. }
  176. return $instance;
  177. }
  178. /**
  179. * Loads the required scripts and styles for the widget control.
  180. *
  181. * @since 4.9.0
  182. */
  183. public function enqueue_admin_scripts() {
  184. $settings = wp_enqueue_code_editor(
  185. array(
  186. 'type' => 'text/html',
  187. 'codemirror' => array(
  188. 'indentUnit' => 2,
  189. 'tabSize' => 2,
  190. ),
  191. )
  192. );
  193. wp_enqueue_script( 'custom-html-widgets' );
  194. if ( empty( $settings ) ) {
  195. $settings = array(
  196. 'disabled' => true,
  197. );
  198. }
  199. wp_add_inline_script( 'custom-html-widgets', sprintf( 'wp.customHtmlWidgets.init( %s );', wp_json_encode( $settings ) ), 'after' );
  200. $l10n = array(
  201. 'errorNotice' => array(
  202. /* translators: %d: Error count. */
  203. 'singular' => _n( 'There is %d error which must be fixed before you can save.', 'There are %d errors which must be fixed before you can save.', 1 ),
  204. /* translators: %d: Error count. */
  205. 'plural' => _n( 'There is %d error which must be fixed before you can save.', 'There are %d errors which must be fixed before you can save.', 2 ),
  206. // @todo This is lacking, as some languages have a dedicated dual form. For proper handling of plurals in JS, see #20491.
  207. ),
  208. );
  209. wp_add_inline_script( 'custom-html-widgets', sprintf( 'jQuery.extend( wp.customHtmlWidgets.l10n, %s );', wp_json_encode( $l10n ) ), 'after' );
  210. }
  211. /**
  212. * Outputs the Custom HTML widget settings form.
  213. *
  214. * @since 4.8.1
  215. * @since 4.9.0 The form contains only hidden sync inputs. For the control UI, see `WP_Widget_Custom_HTML::render_control_template_scripts()`.
  216. *
  217. * @see WP_Widget_Custom_HTML::render_control_template_scripts()
  218. *
  219. * @param array $instance Current instance.
  220. */
  221. public function form( $instance ) {
  222. $instance = wp_parse_args( (array) $instance, $this->default_instance );
  223. ?>
  224. <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" class="title sync-input" type="hidden" value="<?php echo esc_attr( $instance['title'] ); ?>" />
  225. <textarea id="<?php echo $this->get_field_id( 'content' ); ?>" name="<?php echo $this->get_field_name( 'content' ); ?>" class="content sync-input" hidden><?php echo esc_textarea( $instance['content'] ); ?></textarea>
  226. <?php
  227. }
  228. /**
  229. * Render form template scripts.
  230. *
  231. * @since 4.9.0
  232. */
  233. public static function render_control_template_scripts() {
  234. ?>
  235. <script type="text/html" id="tmpl-widget-custom-html-control-fields">
  236. <# var elementIdPrefix = 'el' + String( Math.random() ).replace( /\D/g, '' ) + '_' #>
  237. <p>
  238. <label for="{{ elementIdPrefix }}title"><?php esc_html_e( 'Title:' ); ?></label>
  239. <input id="{{ elementIdPrefix }}title" type="text" class="widefat title">
  240. </p>
  241. <p>
  242. <label for="{{ elementIdPrefix }}content" id="{{ elementIdPrefix }}content-label"><?php esc_html_e( 'Content:' ); ?></label>
  243. <textarea id="{{ elementIdPrefix }}content" class="widefat code content" rows="16" cols="20"></textarea>
  244. </p>
  245. <?php if ( ! current_user_can( 'unfiltered_html' ) ) : ?>
  246. <?php
  247. $probably_unsafe_html = array( 'script', 'iframe', 'form', 'input', 'style' );
  248. $allowed_html = wp_kses_allowed_html( 'post' );
  249. $disallowed_html = array_diff( $probably_unsafe_html, array_keys( $allowed_html ) );
  250. ?>
  251. <?php if ( ! empty( $disallowed_html ) ) : ?>
  252. <# if ( data.codeEditorDisabled ) { #>
  253. <p>
  254. <?php _e( 'Some HTML tags are not permitted, including:' ); ?>
  255. <code><?php echo implode( '</code>, <code>', $disallowed_html ); ?></code>
  256. </p>
  257. <# } #>
  258. <?php endif; ?>
  259. <?php endif; ?>
  260. <div class="code-editor-error-container"></div>
  261. </script>
  262. <?php
  263. }
  264. /**
  265. * Add help text to widgets admin screen.
  266. *
  267. * @since 4.9.0
  268. */
  269. public static function add_help_text() {
  270. $screen = get_current_screen();
  271. $content = '<p>';
  272. $content .= __( 'Use the Custom HTML widget to add arbitrary HTML code to your widget areas.' );
  273. $content .= '</p>';
  274. if ( 'false' !== wp_get_current_user()->syntax_highlighting ) {
  275. $content .= '<p>';
  276. $content .= sprintf(
  277. /* translators: 1: Link to user profile, 2: Additional link attributes, 3: Accessibility text. */
  278. __( 'The edit field automatically highlights code syntax. You can disable this in your <a href="%1$s" %2$s>user profile%3$s</a> to work in plain text mode.' ),
  279. esc_url( get_edit_profile_url() ),
  280. 'class="external-link" target="_blank"',
  281. sprintf(
  282. '<span class="screen-reader-text"> %s</span>',
  283. /* translators: Accessibility text. */
  284. __( '(opens in a new tab)' )
  285. )
  286. );
  287. $content .= '</p>';
  288. $content .= '<p id="editor-keyboard-trap-help-1">' . __( 'When using a keyboard to navigate:' ) . '</p>';
  289. $content .= '<ul>';
  290. $content .= '<li id="editor-keyboard-trap-help-2">' . __( 'In the editing area, the Tab key enters a tab character.' ) . '</li>';
  291. $content .= '<li id="editor-keyboard-trap-help-3">' . __( 'To move away from this area, press the Esc key followed by the Tab key.' ) . '</li>';
  292. $content .= '<li id="editor-keyboard-trap-help-4">' . __( 'Screen reader users: when in forms mode, you may need to press the Esc key twice.' ) . '</li>';
  293. $content .= '</ul>';
  294. }
  295. $screen->add_help_tab(
  296. array(
  297. 'id' => 'custom_html_widget',
  298. 'title' => __( 'Custom HTML Widget' ),
  299. 'content' => $content,
  300. )
  301. );
  302. }
  303. }