vg_tags( $result ); $replaced_html = preg_replace_callback( '/<\s*script(?\s*[^>]*?)?>(?.*?)?<\s*\/\s*script\s*>/ims', [ $this, 'replace_scripts', ], $result ); if ( empty( $replaced_html ) ) { return $html; } $replaced_html = $this->restore_xmp_tags( $replaced_html ); return $this->restore_svg_tags( $replaced_html ); } /** * Callback method for preg_replace_callback that is used to adjust attributes for scripts. * * @since 3.9 Use exclusions list & fake type attribute. * @since 3.7 * * @param array $matches Matches array for scripts regex. * * @return string */ public function replace_scripts( $matches ): string { foreach ( $this->excluded as $pattern ) { if ( preg_match( "#{$pattern}#i", $matches[0] ) ) { $this->logger->debug( "DelayJS: Script {$matches[0]} excluded by $pattern" ); return $matches[0]; } } if ( empty( $matches['attr'] ) ) { return ''; } $type_regex = '/type\s*=\s*(["\'])(?.*)\1/i'; preg_match( $type_regex . 'U', $matches['attr'], $type_matches ); if ( ! empty( $type_matches ) && ! empty( trim( $type_matches['type'] ) ) && ! in_array( trim( $type_matches['type'] ), $this->allowed_types, true ) ) { return $matches[0]; } $matches['attr'] = preg_replace( $type_regex, 'data-rocket-type=$1$2$1', $matches['attr'] ); // To remove type attribute without any value. $matches['attr'] = preg_replace( '/(\s+type\s+)|(^type\s+)|(\s+type$)/i', '', $matches['attr'] ); // Checks if script has src attribute so then treat as external script and replace src with data-rocket-src. $src_regex = '/src\s*=\s*(["\'])(.*)\1/i'; $matches['attr'] = preg_replace( $src_regex, 'data-rocket-src=$1$2$1', $matches['attr'] ); return ''; } /** * Move meta charset to head if not found to the top of page content. * * @since 3.9.4 * * @param string $html Html content. * * @return string */ public function move_meta_charset_to_head( $html ): string { $meta_pattern = "#]*|)(charset[^=]*=[ ]*[\'\" ]*[^\'\"> ][^\'\">]+[^\'\"> ][\'\" ]*|charset[^=]*=*[^\'\"> ][^\'\">]+[^\'\"> ])([^>]*|)>(?=.*)#Usmi"; if ( ! preg_match( $meta_pattern, $html, $matches ) ) { return $html; } $replaced_html = preg_replace( "$meta_pattern", '', $html ); if ( empty( $replaced_html ) ) { return $html; } if ( preg_match( '/]*?>)/i', "\${1}{$matches[0]}", $replaced_html, 1 ); if ( empty( $replaced_html ) ) { return $html; } return $replaced_html; } if ( preg_match( '/]*?>)/i', "\${1}{$matches[0]}", $replaced_html, 1 ); if ( empty( $replaced_html ) ) { return $html; } return $replaced_html; } $replaced_html = preg_replace( '/(<\w+)/', "{$matches[0]}\${1}", $replaced_html, 1 ); if ( empty( $replaced_html ) ) { return $html; } return $replaced_html; } /** * Get exclusions * * @return void */ private function set_exclusions() { $lists = $this->data_manager->get_lists(); $this->excluded = isset( $lists->delay_js_exclusions ) ? $lists->delay_js_exclusions : []; } }