From 2bae741d03cc475d076c531df2512e301dd5fbab Mon Sep 17 00:00:00 2001 From: selul Date: Fri, 22 Mar 2019 10:37:37 +0200 Subject: [PATCH] fix: image replacement on json strings with html entities encoded, conflicting with variation form Woocommerce fixes #81 --- inc/manager.php | 7 +++---- tests/test-replacer.php | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/inc/manager.php b/inc/manager.php index 2fc2952f..c680f799 100644 --- a/inc/manager.php +++ b/inc/manager.php @@ -262,13 +262,13 @@ public function extract_urls_from_json( $content ) { * @return array Normalized array. */ private function normalize_urls( $urls ) { + $urls = array_map( function ( $value ) { - return rtrim( html_entity_decode( $value ), '\\' ); + return rtrim( html_entity_decode( $value ), '\\";\'' ); }, $urls ); - $urls = array_unique( $urls ); return array_values( $urls ); @@ -434,13 +434,12 @@ public function process_urls_from_content( $html ) { * @return array */ public function extract_image_urls_from_content( $content ) { - $regex = '/(?:http(?:s?):)(?:[\/\\\\|.|\w|\s|-])*\.(?:' . implode( '|', array_keys( Optml_Config::$extensions ) ) . ')(?:\??[\w|=|&|\-|\.|:]*)/'; + $regex = '/(?:http(?:s?):)(?:[\/\\\\|.|\w|\s|-])*\.(?:' . implode( '|', array_keys( Optml_Config::$extensions ) ) . ')(?:\?{1}[\w|=|&|\-|\.|:]*)?/'; preg_match_all( $regex, $content, $urls ); - return $this->normalize_urls( $urls[0] ); } diff --git a/tests/test-replacer.php b/tests/test-replacer.php index f0554d81..24ed1e39 100644 --- a/tests/test-replacer.php +++ b/tests/test-replacer.php @@ -79,6 +79,27 @@ public function setUp() { } + public function test_wc_json_replacement() { + $html = [ + 'image' => "https://www.example.org/wp-content/uploads/2018/05/brands.png", + 'image2' => "https://www.example.org/wp-content/uploads/2018/05/brands.png?test=123", + 'image3' => "https://www.example.org/wp-content/uploads/2018/05/brands.png?test=123&anther=test", + ]; + + + $html = wp_json_encode( $html ); + $html = _wp_specialchars( $html, ENT_QUOTES, 'UTF-8', true ); + + $replaced_content = Optml_Manager::instance()->process_urls_from_content( $html ); + $this->assertEquals( 3, substr_count( $replaced_content, 'i.optimole.com' ) ); + + $replaced_content = wp_specialchars_decode( $replaced_content, ENT_QUOTES ); + $replaced_content = json_decode( $replaced_content, true ); + + $this->assertArrayHasKey( 'image', $replaced_content ); + + } + public function test_image_tags() { $found_images = Optml_Manager::parse_images_from_html( self::IMG_TAGS );