From 037f6efda336e52de1d77cdfe46fa661ac5f30a8 Mon Sep 17 00:00:00 2001 From: Ryan Kienstra Date: Thu, 1 Mar 2018 15:00:50 -0600 Subject: [PATCH] Issue #864: Allow 'data-amp-layout' in wp_kses() for 'post.' Add this attribute to the allowed list for . The sanitizer now converts this to 'layout.' --- includes/class-amp-theme-support.php | 1 + includes/utils/class-amp-wp-utils.php | 24 ++++++++++++++++++++++++ tests/test-amp-wp-utils.php | 22 ++++++++++++++++++++++ 3 files changed, 47 insertions(+) diff --git a/includes/class-amp-theme-support.php b/includes/class-amp-theme-support.php index acda180917f..22eb7f85579 100644 --- a/includes/class-amp-theme-support.php +++ b/includes/class-amp-theme-support.php @@ -183,6 +183,7 @@ public static function register_hooks() { add_filter( 'comment_reply_link', array( __CLASS__, 'filter_comment_reply_link' ), 10, 4 ); add_filter( 'cancel_comment_reply_link', array( __CLASS__, 'filter_cancel_comment_reply_link' ), 10, 3 ); add_action( 'comment_form', array( __CLASS__, 'add_amp_comment_form_templates' ), 100 ); + add_filter( 'wp_kses_allowed_html', 'AMP_WP_Utils::add_layout', 10, 2 ); // @todo Add character conversion. } diff --git a/includes/utils/class-amp-wp-utils.php b/includes/utils/class-amp-wp-utils.php index bacb72458af..014dabab1d5 100644 --- a/includes/utils/class-amp-wp-utils.php +++ b/includes/utils/class-amp-wp-utils.php @@ -58,4 +58,28 @@ protected static function _wp_translate_php_url_constant_to_key( $constant ) { return false; } + + /** + * Adds 'data-amp-layout' to the allowed attributes for wp_kses() in a 'post' context. + * + * @since 0.7 + * + * @param array $context Allowed tags and their allowed attributes. + * @param string $context_type Type of context. + * @return array $context Filtered allowed tags and attributes. + */ + public static function add_layout( $context, $context_type ) { + if ( 'post' !== $context_type ) { + return $context; + } + $img = isset( $context['img'] ) ? $context['img'] : array(); + $context['img'] = array_merge( + $img, + array( + 'data-amp-layout' => true, + ) + ); + return $context; + } + } diff --git a/tests/test-amp-wp-utils.php b/tests/test-amp-wp-utils.php index 43f3b3a572e..93e0faa4fc7 100644 --- a/tests/test-amp-wp-utils.php +++ b/tests/test-amp-wp-utils.php @@ -44,4 +44,26 @@ function test__method( $url, $expected, $component ) { $this->assertEquals( $expected, $actual ); } + + /** + * Test AMP_WP_Utils::add_layout(). + * + * @see AMP_WP_Utils::add_layout() + */ + public function test_add_layout() { + $this->assertEquals( array(), AMP_WP_Utils::add_layout( array(), 'explicit' ) ); + $this->assertEquals( + array( + 'img' => array( + 'data-amp-layout' => true, + ), + ), + AMP_WP_Utils::add_layout( array(), 'post' ) + ); + + add_filter( 'wp_kses_allowed_html', 'AMP_WP_Utils::add_layout', 10, 2 ); + $image = ''; + $this->assertEquals( $image, wp_kses_post( $image ) ); + } + }