| | 38 | |
| | 39 | function test_wp_localize_script_escaping() { |
| | 40 | $handle = rand_str(); |
| | 41 | $src = 'example.com'; |
| | 42 | $object = rand_str(); |
| | 43 | $key = rand_str(); |
| | 44 | $key2 = rand_str(); |
| | 45 | |
| | 46 | wp_enqueue_script( $handle, $src ); |
| | 47 | wp_localize_script( $handle, $object, array( |
| | 48 | $key => 'abcdef\'s value', |
| | 49 | $key2 => '1', |
| | 50 | ) ); |
| | 51 | |
| | 52 | $value = $this->_get_localized_value( $key, $key2 ); |
| | 53 | $this->assertEquals( '"abcdef\\\'s value"', $value ); |
| | 54 | } |
| | 55 | |
| | 56 | function _get_localized_value( $key, $key2 ) { |
| | 57 | $result = strip_ws( get_echo( 'wp_print_scripts' ) ); |
| | 58 | |
| | 59 | // old esc_js() looks like this: |
| | 60 | // $key: "abcdef\'s value", |
| | 61 | |
| | 62 | // json_encode() looks like this: |
| | 63 | // var $handle = {"$key":"abcdef's value","$key2":"1"}; |
| | 64 | |
| | 65 | foreach ( explode( "\n", $result ) as $line ) { |
| | 66 | if ( false === $pos = strpos( $line, $key ) ) |
| | 67 | continue; |
| | 68 | $line = substr( $line, $pos + strlen( $key ) ); |
| | 69 | if ( 0 === strpos( $line, '"' ) ) |
| | 70 | $line = substr( $line, 1 ); |
| | 71 | if ( 0 === strpos( $line, ':' ) ) |
| | 72 | $line = substr( $line, 1 ); |
| | 73 | $line = ltrim( $line ); |
| | 74 | $line = rtrim( $line, ',' ); |
| | 75 | if ( false !== strpos( $line, $key2 ) ) { |
| | 76 | list( $line ) = explode( $key2, $line ); |
| | 77 | if ( ',"' === substr( $line, -2 ) ) |
| | 78 | $line = substr( $line, 0, -2 ); |
| | 79 | } |
| | 80 | return $line; |
| | 81 | } |
| | 82 | } |
| | 83 | |