[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/widgets/ -> class-wp-widget-custom-html.php (source)

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


Generated : Tue Mar 19 08:20:01 2024 Cross-referenced by PHPXref