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

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