This commit is contained in:
2026-10-06 18:51:23 -06:00
parent 8424dacd03
commit e2c26b7f21
4223 changed files with 737986 additions and 53 deletions
@@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\GoogleFonts;
/**
* Abstract Optimization Parent Class for Google Fonts Optimizers.
*
* @since 3.8
*/
abstract class AbstractGFOptimization {
/**
* Allowed display values.
*
* @since 3.8
*
* @var array
*/
protected $display_values = [
'auto' => 1,
'block' => 1,
'swap' => 1,
'fallback' => 1,
'optional' => 1,
];
/**
* Flag for whether google fonts have been detected (Default: true)
*
* @since 3.8.8
*
* @var bool
*/
protected $has_google_fonts = true;
/**
* Optimize Google Fonts
*
* @param string $html HTML content.
*
* @return string
*/
abstract public function optimize( $html ): string;
/**
* Check whether the optimizer has found google fonts on the page.
*
* @since 3.8.8
*
* @return bool Will default to true when extending classes have not set via the optimize() method.
*/
public function has_google_fonts() {
return $this->has_google_fonts;
}
/**
* Returns font with display value.
*
* @since 3.8 Moved here from GoogleFonts\Combine::class
* @since 3.5.1
*
* @param array $font Array containing font tag and matches.
*
* @return string Google Font tag with display param.
*/
protected function get_font_with_display( array $font ) {
$font_url = html_entity_decode( $font['url'] );
$query = wp_parse_url( $font_url, PHP_URL_QUERY );
if ( empty( $query ) ) {
return $font[0];
}
$parsed_font = wp_parse_args( $query );
$font_url = ! empty( $parsed_font['display'] )
? str_replace( "&display={$parsed_font['display']}", '&display=swap', $font_url )
: "{$font_url}&display=swap";
return str_replace( $font['url'], esc_url( $font_url ), $font[0] );
}
/**
* Get the font display value.
*
* @since 3.8 Moved here from GoogleFonts\Combine::class
* @since 3.5.1
*
* @return string font display value.
*/
protected function get_font_display_value(): string {
/**
* Filters the combined Google Fonts display parameter value
*
* @since 3.8 Moved here from GoogleFonts\Combine::class
* @since 3.3.5
*
* @param string $display Display value. Can be either auto, block, swap, fallback or optional.
*/
$display = apply_filters( 'rocket_combined_google_fonts_display', 'swap' );
if ( ! is_string( $display ) ) {
return 'swap';
}
return isset( $this->display_values[ $display ] ) ? $display : 'swap';
}
/**
* Returns the optimized markup for Google Fonts
*
* @since 3.9.1
*
* @param string $url Google Fonts URL.
*
* @return string
*/
protected function get_optimized_markup( string $url ): string {
return sprintf(
'<link rel="preload" as="style" href="%1$s" /><link rel="stylesheet" href="%1$s" media="print" onload="this.media=\'all\'" /><noscript><link rel="stylesheet" href="%1$s" /></noscript>', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
$url
);
}
}
@@ -0,0 +1,85 @@
<?php
namespace WP_Rocket\Engine\Optimization\GoogleFonts\Admin;
use WP_Rocket\Abstract_Render;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Engine\Admin\Beacon\Beacon;
class Settings extends Abstract_Render {
/**
* WP Rocket options instance
*
* @var Options_Data
*/
private $options;
/**
* Beacon instance
*
* @var Beacon
*/
private $beacon;
/**
* Instantiate the class
*
* @param Options_Data $options WP Rocket options instance.
* @param Beacon $beacon Beacon instance.
* @param string $template_path Path to template files.
*/
public function __construct( Options_Data $options, Beacon $beacon, $template_path ) {
parent::__construct( $template_path );
$this->options = $options;
$this->beacon = $beacon;
}
/**
* Displays the Google Fonts Optimization section in the tools tab
*
* @since 3.7
*
* @return void
*/
public function display_google_fonts_enabler() {
if ( ! current_user_can( 'rocket_manage_options' ) ) {
return;
}
if ( ! apply_filters( 'pre_get_rocket_option_minify_google_fonts', true ) ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
return;
}
if ( $this->options->get( 'minify_google_fonts', 0 ) ) {
return;
}
$data = [
'beacon' => $this->beacon->get_suggest( 'google_fonts' ),
];
echo $this->generate( 'settings/enable-google-fonts', $data ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Callback method for the AJAX request to enable Google Fonts Optimization
*
* @since 3.7
*
* @return void
*/
public function enable_google_fonts() {
check_ajax_referer( 'rocket-ajax', 'nonce', true );
if ( ! current_user_can( 'rocket_manage_options' ) ) {
wp_send_json_error();
return;
}
$this->options->set( 'minify_google_fonts', 1 );
update_option( rocket_get_constant( 'WP_ROCKET_SLUG', 'wp_rocket_settings' ), $this->options->get_options() );
wp_send_json_success();
}
}
@@ -0,0 +1,59 @@
<?php
namespace WP_Rocket\Engine\Optimization\GoogleFonts\Admin;
use WP_Rocket\Event_Management\Subscriber_Interface;
class Subscriber implements Subscriber_Interface {
/**
* Google Fonts Settings instance
*
* @var Settings
*/
private $settings;
/**
* Instantiate the class
*
* @param Settings $settings Google Fonts Settings instance.
*/
public function __construct( Settings $settings ) {
$this->settings = $settings;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @since 3.7
*
* @return array
*/
public static function get_subscribed_events() {
return [
'rocket_settings_tools_content' => 'display_google_fonts_enabler',
'wp_ajax_rocket_enable_google_fonts' => 'enable_google_fonts',
];
}
/**
* Displays the Google Fonts Optimization section in the tools tab
*
* @since 3.7
*
* @return void
*/
public function display_google_fonts_enabler() {
$this->settings->display_google_fonts_enabler();
}
/**
* Callback method for the AJAX request to enable Google Fonts Optimization
*
* @since 3.7
*
* @return void
*/
public function enable_google_fonts() {
$this->settings->enable_google_fonts();
}
}
@@ -0,0 +1,146 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\GoogleFonts;
use WP_Rocket\Engine\Optimization\RegexTrait;
use WP_Rocket\Logger\Logger;
/**
* Combine Google Fonts
*
* @since 3.1
*/
class Combine extends AbstractGFOptimization {
use RegexTrait;
/**
* Found fonts
*
* @since 3.1
*
* @var string
*/
protected $fonts = '';
/**
* Found subsets
*
* @since 3.1
*
* @var string
*/
protected $subsets = '';
/**
* Combines multiple Google Fonts links into one
*
* @since 3.1
*
* @param string $html HTML content.
*
* @return string
*/
public function optimize( $html ): string {
Logger::info( 'GOOGLE FONTS COMBINE PROCESS STARTED.', [ 'GF combine process' ] );
$html_nocomments = $this->hide_comments( $html );
$fonts = $this->find( '<link(?:\s+(?:(?!href\s*=\s*)[^>])+)?(?:\s+href\s*=\s*([\'"])(?<url>(?:https?:)?\/\/fonts\.googleapis\.com\/css[^\d](?:(?!\1).)+)\1)(?:\s+[^>]*)?>', $html_nocomments );
if ( ! $fonts ) {
Logger::debug( 'No Google Fonts found.', [ 'GF combine process' ] );
$this->has_google_fonts = false;
return $html;
}
$this->has_google_fonts = true;
$num_fonts = count( $fonts );
Logger::debug(
"Found {$num_fonts} Google Fonts.",
[
'GF combine process',
'tags' => $fonts,
]
);
$this->parse( $fonts );
if ( empty( $this->fonts ) ) {
Logger::debug( 'No Google Fonts left to combine.', [ 'GF combine process' ] );
return $html;
}
$html = preg_replace( '@<\/title>@i', '$0' . $this->get_optimized_markup( $this->get_combined_url() ), $html, 1 );
foreach ( $fonts as $font ) {
$html = str_replace( $font[0], '', $html );
}
Logger::info(
'Google Fonts successfully combined.',
[
'GF combine process',
'url' => $this->fonts . $this->subsets,
]
);
return $html;
}
/**
* Parses found matches to extract fonts and subsets.
*
* @since 3.1
*
* @param array $matches Found matches for the pattern.
*
* @return void
*/
private function parse( array $matches ) {
$fonts_array = [];
$subsets_array = [];
foreach ( $matches as $match ) {
$url = html_entity_decode( $match[2] );
$query = wp_parse_url( $url, PHP_URL_QUERY );
if ( empty( $query ) ) {
return;
}
$font = wp_parse_args( $query );
if ( isset( $font['family'] ) ) {
$font_family = $font['family'];
$font_family = rtrim( $font_family, '%7C' );
$font_family = rtrim( $font_family, '|' );
// Add font to the collection.
$fonts_array[] = rawurlencode( htmlentities( $font_family ) );
}
// Add subset to collection.
if ( isset( $font['subset'] ) ) {
$subsets_array[] = rawurlencode( htmlentities( $font['subset'] ) );
}
}
// Concatenate fonts tag.
$this->subsets = ! empty( $subsets_array ) ? '&subset=' . implode( ',', array_filter( array_unique( $subsets_array ) ) ) : '';
$this->fonts = ! empty( $fonts_array ) ? implode( '%7C', array_filter( array_unique( $fonts_array ) ) ) : '';
}
/**
* Returns the combined Google fonts URL
*
* @since 3.9.1
*
* @return string
*/
private function get_combined_url(): string {
$display = $this->get_font_display_value();
return esc_url( "https://fonts.googleapis.com/css?family={$this->fonts}{$this->subsets}&display={$display}" );
}
}
@@ -0,0 +1,155 @@
<?php
declare(strict_types=1);
namespace WP_Rocket\Engine\Optimization\GoogleFonts;
use WP_Rocket\Engine\Optimization\RegexTrait;
use WP_Rocket\Logger\Logger;
/**
* Combine v2 Google Fonts
*
* @since 3.8
*/
class CombineV2 extends AbstractGFOptimization {
use RegexTrait;
/**
* Combines multiple Google Fonts (API v2) links into one
*
* @since 3.8
*
* @param string $html HTML content.
*
* @return string
*/
public function optimize( $html ): string {
Logger::info( 'GOOGLE FONTS COMBINE-V2 PROCESS STARTED.', [ 'GF combine process' ] );
$processed_tags = [];
$html_nocomments = $this->hide_comments( $html );
$font_tags = $this->find( '<link(?:\s+(?:(?!href\s*=\s*)[^>])+)?(?:\s+href\s*=\s*([\'"])(?<url>(?:https?:)?\/\/fonts\.googleapis\.com\/css2(?:(?!\1).)+)\1)(?:\s+[^>]*)?>', $html_nocomments );
if ( ! $font_tags ) {
Logger::debug( 'No v2 Google Fonts found.', [ 'GF combine process' ] );
$this->has_google_fonts = false;
return $html;
}
$this->has_google_fonts = true;
$num_tags = count( $font_tags );
Logger::debug(
"Found {$num_tags} v2 Google Fonts.",
[
'GF combine process',
'tags' => $font_tags,
]
);
$families = [];
foreach ( $font_tags as $tag ) {
$parsed_families = $this->parse( $tag );
if ( ! empty( $parsed_families ) ) {
$processed_tags[] = $tag;
$families = array_merge( $families, $parsed_families );
}
}
if ( empty( $families ) ) {
Logger::debug( 'No v2 Google Fonts left to combine.', [ 'GF combine process' ] );
return $html;
}
$families = array_unique( $families );
$combined_tag = $this->get_optimized_markup( $this->get_combined_url( $families ) );
$html = preg_replace( '@<\/title>@i', '$0' . $combined_tag, $html, 1 );
foreach ( $processed_tags as $font ) {
$html = str_replace( $font[0], '', $html );
}
Logger::info(
'V2 Google Fonts successfully combined.',
[
'GF combine process',
'url' => $combined_tag,
]
);
return $html;
}
/**
* Parses found matches to extract fonts and subsets.
*
* @since 3.8
*
* @param array $tag A Google Font v2 url.
*
* @return array
*/
private function parse( array $tag ): array {
if ( false !== strpos( $tag['url'], 'text=' ) ) {
Logger::debug( 'GOOGLEFONTS V2 COMBINE: ' . $tag['url'] . ' SKIPPED TO PRESERVE "text" ATTRIBUTE.' );
return [];
}
$url_pattern = '#(family=[A-Za-z0-9;:,=%&\+\@\.]+)$#';
$display_pattern = '#&display=(?:swap|auto|block|fallback|optional)#';
$decoded_url = html_entity_decode( $tag['url'] );
$query = wp_parse_url( $decoded_url, PHP_URL_QUERY );
if ( empty( $query ) ) {
return [];
}
if ( ! preg_match_all( $url_pattern, $query, $matches, PREG_PATTERN_ORDER ) ) {
return [];
}
$families = [];
foreach ( $matches[1] as $family ) {
$families[] = preg_replace( $display_pattern, '', $family );
}
return $families;
}
/**
* Returns the combined Google fonts URL
*
* @since 3.9.1
*
* @param array $families Array with all Google V2 families.
*
* @return string
*/
private function get_combined_url( array $families ): string {
$display = $this->get_font_display_value();
return esc_url( "https://fonts.googleapis.com/css2{$this->get_concatenated_families( $families )}&display={$display}" );
}
/**
* Get a string of the concatenated font family queries.
*
* @since 3.8
*
* @param array $families Array with all Google V2 families.
*
* @return string
*/
private function get_concatenated_families( array $families ): string {
$families_string = '?';
foreach ( $families as $family ) {
$families_string .= $family . '&';
}
return rtrim( $families_string, '&?' );
}
}
@@ -0,0 +1,129 @@
<?php
namespace WP_Rocket\Engine\Optimization\GoogleFonts;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Combine Google Fonts subscriber
*
* @since 3.1
*/
class Subscriber implements Subscriber_Interface {
/**
* Plugin options.
*
* @var Options_Data
*/
private $options;
/**
* Combine instance.
*
* @var AbstractGFOptimization
*/
private $combine;
/**
* CombineV2 instance.
*
* @var AbstractGFOptimization
*/
private $combine_v2;
/**
* Instantiate the subscriber.
*
* @param AbstractGFOptimization $combine Combine instance.
* @param AbstractGFOptimization $combine_v2 Combine V2 instance.
* @param Options_Data $options Options_Data instance.
*/
public function __construct( AbstractGFOptimization $combine, AbstractGFOptimization $combine_v2, Options_Data $options ) {
$this->combine = $combine;
$this->combine_v2 = $combine_v2;
$this->options = $options;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @since 3.1
*
* @return array
*/
public static function get_subscribed_events() {
return [
'wp_resource_hints' => [ 'preconnect', 10, 2 ],
'rocket_buffer' => [ 'process', 1001 ],
];
}
/**
* Adds google fonts URL to preconnect
*
* @since 3.5.3
*
* @param array $urls URLs to print for resource hints.
* @param string $relation_type The relation type the URLs are printed for, e.g. 'preconnect' or 'prerender'.
* @return array
*/
public function preconnect( array $urls, $relation_type ) {
if ( ! $this->is_allowed() ) {
return $urls;
}
if ( 'preconnect' !== $relation_type ) {
return $urls;
}
$urls[] = [
'href' => 'https://fonts.gstatic.com',
1 => 'crossorigin',
];
return $urls;
}
/**
* Processes the HTML to combine found Google fonts.
* Handles both Google Fonts API v2 and v1.
*
* @since 3.1
*
* @param string $html HTML content.
* @return string
*/
public function process( $html ) {
if ( ! $this->is_allowed() ) {
return $html;
}
// Combine Google Font API V2.
$html = $this->combine_v2->optimize( $html );
// Combine Google Font API V1.
$html = $this->combine->optimize( $html );
if ( ! $this->combine->has_google_fonts() && ! $this->combine_v2->has_google_fonts() ) {
$html = preg_replace( '/<link\s+(?:[^>]+[\s"\'])?href\s*=\s*[\'"]https:\/\/fonts\.gstatic\.com[\'"](?:[^>]+[\s"\'])?\s?\/?>/', '', $html );
}
return $html;
}
/**
* Checks if files can combine found Google fonts.
*
* @since 3.1
*/
protected function is_allowed() {
if ( rocket_bypass() ) {
return false;
}
if ( ! $this->options->get( 'minify_google_fonts', 0 ) ) {
return false;
}
return ! is_user_logged_in() || (bool) $this->options->get( 'cache_logged_user', 0 );
}
}