home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress / wp-includes / widgets / class-wp-widget-custom-html.php < prev    next >
Encoding:
PHP Script  |  2017-11-14  |  11.6 KB  |  324 lines

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