filename
stringlengths
11
137
content
stringlengths
6
292k
projects/plugins/boost/app/features/setup-prompt/_inc/banner.php
<?php /** * Boost Setup Prompt * DEPRECATED - this prompt has been removed as of version 2.3.1 */ ?> <div class="jb-setup-banner"> <div class="jb-setup-banner__content-top-text"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect x="0" fill="none" width="24" height="24"></rect><g><path d="M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2zm1 15h-2v-2h2v2zm0-4h-2l-.5-6h3l-.5 6z"></path></g></svg> <span><?php esc_html_e( "You're almost done. Set up Jetpack Boost and generate your site's Critical CSS to see the impact on your PageSpeed scores.", 'jetpack-boost' ); ?></span> </div> <span class="notice-dismiss jb-setup-banner__dismiss" title="Dismiss this notice"></span> <div class="jb-setup-banner__inner"> <div class="jb-setup-banner__content"> <img class="jb-setup-banner__logo" src="<?php echo esc_url( JETPACK_BOOST_PLUGINS_DIR_URL . 'app/assets/static/images/jetpack-logo.svg' ); ?>" /> <h2 class="jb-setup-banner__title"> <?php esc_html_e( 'The easiest speed optimization plugin for WordPress', 'jetpack-boost' ); ?> </h2> <p class="jb-setup-banner__text"> <?php esc_html_e( "You're almost done. Set up Jetpack Boost and generate your site's Critical CSS to see the impact on your PageSpeed scores.", 'jetpack-boost' ); ?> </p> <footer class="jb-setup-banner__footer"> <a href="<?php echo esc_url( admin_url( 'admin.php?page=jetpack-boost' ) ); ?>" class="jb-setup-banner__cta-button"> <?php esc_html_e( 'Set up Jetpack Boost', 'jetpack-boost' ); ?> </a> </footer> </div> <div class="jb-setup-banner__image-container"> <img src="<?php echo esc_url( JETPACK_BOOST_PLUGINS_DIR_URL . 'app/assets/static/images/boost-performance.png' ); ?>" title="<?php esc_attr_e( 'Check how your web site performance scores for desktop and mobile.', 'jetpack-boost' ); ?>" alt="<?php esc_attr_e( 'An image showing a web site with a photo of a time-lapsed watch face. In the foreground is a graph showing a speed score for mobile and desktop in yellow and green with an overall score of B', 'jetpack-boost' ); ?>" srcset="<?php echo esc_url( JETPACK_BOOST_PLUGINS_DIR_URL . '/app/assets/static/images/boost-performance.png' ); ?> 650w <?php echo esc_url( plugin_dir_url( __FILE__ ) . '/assets/boost-performance-2x.png' ); ?> 1306w" sizes="(max-width: 782px) 654px, 1306px" > </div> </div> </div>
projects/plugins/boost/app/features/setup-prompt/_inc/dismiss-script.php
<script> jQuery( '.jb-setup-banner__dismiss' ).on( 'click', function() { jQuery( '.jb-setup-banner' ).fadeOut( 'slow' ); jQuery.post( ajaxurl, { action: <?php echo wp_json_encode( Automattic\Jetpack_Boost\Features\Setup_Prompt\Setup_Prompt::AJAX_ACTION ); ?>, nonce: <?php echo wp_json_encode( wp_create_nonce( Automattic\Jetpack_Boost\Features\Setup_Prompt\Setup_Prompt::NONCE_ACTION ) ); ?>, } ); } ); </script>
projects/plugins/boost/app/admin/index.php
<?php //phpcs:ignoreFile /** * Empty file. */ // Silence is golden.
projects/plugins/boost/app/admin/class-admin.php
<?php /** * The admin-specific functionality of the plugin. * * @since 1.0.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Admin; use Automattic\Jetpack\Admin_UI\Admin_Menu; use Automattic\Jetpack\Boost_Speed_Score\Speed_Score; use Automattic\Jetpack_Boost\Lib\Analytics; use Automattic\Jetpack_Boost\Lib\Environment_Change_Detector; use Automattic\Jetpack_Boost\Lib\Premium_Features; use Automattic\Jetpack_Boost\Modules\Modules_Setup; class Admin { /** * Menu slug. */ const MENU_SLUG = 'jetpack-boost'; public function init( Modules_Setup $modules ) { Environment_Change_Detector::init(); // Initiate speed scores. new Speed_Score( $modules, 'boost-plugin' ); add_action( 'init', array( new Analytics(), 'init' ) ); add_filter( 'plugin_action_links_' . JETPACK_BOOST_PLUGIN_BASE, array( $this, 'plugin_page_settings_link' ) ); add_action( 'admin_menu', array( $this, 'handle_admin_menu' ) ); } public function handle_admin_menu() { $total_problems = apply_filters( 'jetpack_boost_total_problem_count', 0 ); $menu_label = _x( 'Boost', 'The Jetpack Boost product name, without the Jetpack prefix', 'jetpack-boost' ); if ( $total_problems ) { $menu_label .= sprintf( ' <span class="update-plugins">%d</span>', $total_problems ); } $page_suffix = Admin_Menu::add_menu( __( 'Jetpack Boost - Settings', 'jetpack-boost' ), $menu_label, 'manage_options', JETPACK_BOOST_SLUG, array( $this, 'render_settings' ) ); add_action( 'load-' . $page_suffix, array( $this, 'admin_init' ) ); } /** * Enqueue scripts and styles for the admin page. */ public function admin_init() { // Clear premium features cache when the plugin settings page is loaded. Premium_Features::clear_cache(); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_styles' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); } /** * Register the stylesheets for the admin area. * * @since 1.0.0 */ public function enqueue_styles() { $internal_path = apply_filters( 'jetpack_boost_asset_internal_path', 'app/assets/dist/' ); wp_enqueue_style( 'jetpack-boost-css', plugins_url( $internal_path . 'jetpack-boost.css', JETPACK_BOOST_PATH ), array( 'wp-components' ), JETPACK_BOOST_VERSION ); } /** * Register the JavaScript for the admin area. * * @since 1.0.0 */ public function enqueue_scripts() { $internal_path = apply_filters( 'jetpack_boost_asset_internal_path', 'app/assets/dist/' ); $admin_js_handle = 'jetpack-boost-admin'; wp_register_script( $admin_js_handle, plugins_url( $internal_path . 'jetpack-boost.js', JETPACK_BOOST_PATH ), array( 'wp-i18n', 'wp-components' ), JETPACK_BOOST_VERSION, true ); wp_localize_script( $admin_js_handle, 'Jetpack_Boost', ( new Config() )->constants() ); wp_set_script_translations( $admin_js_handle, 'jetpack-boost' ); wp_enqueue_script( $admin_js_handle ); } /** * Get settings link. * * @param array $links the array of links. */ public function plugin_page_settings_link( $links ) { $settings_link = '<a href="' . admin_url( 'admin.php?page=jetpack-boost' ) . '">' . esc_html__( 'Settings', 'jetpack-boost' ) . '</a>'; array_unshift( $links, $settings_link ); return $links; } /** * Generate the settings page. */ public function render_settings() { wp_localize_script( 'jetpack-boost-admin', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ), ) ); ?> <div id="jb-admin-settings"></div> <?php } }
projects/plugins/boost/app/admin/class-config.php
<?php namespace Automattic\Jetpack_Boost\Admin; use Automattic\Jetpack\Status; use Automattic\Jetpack\Status\Host; /** * Handle the configuration constants. * * This is a global state of Jetpack Boost and passed on to the front-end. */ class Config { public function constants() { $internal_path = apply_filters( 'jetpack_boost_asset_internal_path', 'app/assets/dist/' ); $constants = array( 'version' => JETPACK_BOOST_VERSION, 'pluginDirUrl' => untrailingslashit( JETPACK_BOOST_PLUGINS_DIR_URL ), 'assetPath' => plugins_url( $internal_path, JETPACK_BOOST_PATH ), 'canResizeImages' => wp_image_editor_supports( array( 'methods' => array( 'resize' ) ) ), 'site' => array( 'url' => get_home_url(), 'domain' => ( new Status() )->get_site_suffix(), 'online' => ! ( new Status() )->is_offline_mode(), 'isAtomic' => ( new Host() )->is_woa_site(), ), 'api' => array( 'namespace' => JETPACK_BOOST_REST_NAMESPACE, 'prefix' => JETPACK_BOOST_REST_PREFIX, ), 'postTypes' => (object) $this->get_custom_post_types(), ); // Give each module an opportunity to define extra constants. return apply_filters( 'jetpack_boost_js_constants', $constants ); } /** * Retrieves custom post types. * * @return array Associative array of custom post types * with their labels as keys and names as values. */ private static function get_custom_post_types() { $post_types = get_post_types( array( 'public' => true, '_builtin' => false, ), false ); unset( $post_types['attachment'] ); $post_types = array_filter( $post_types, 'is_post_type_viewable' ); return wp_list_pluck( $post_types, 'label', 'name' ); } }
projects/plugins/boost/app/admin/class-regenerate-admin-notice.php
<?php /** * Admin notice base class. Override this to implement each admin notice Jetpack Boost may show. * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Admin; use Automattic\Jetpack\Boost_Core\Lib\Transient; /** * Admin notice for letting users know they need to regenerate their Critical CSS. */ class Regenerate_Admin_Notice { private static $dismissal_key = 'dismiss-critical-css-notice'; public static function enable() { Transient::set( 'regenerate_admin_notice', true ); } public static function dismiss() { Transient::delete( 'regenerate_admin_notice' ); } public static function is_enabled() { return Transient::get( 'regenerate_admin_notice', false ); } /** * Helper method to generate a dismissal link for this message. */ private static function get_dismiss_url() { return add_query_arg( array( self::$dismissal_key => '', 'nonce' => wp_create_nonce( 'jb_dismiss_notice' ), ) ); } public static function maybe_handle_dismissal() { if ( ! is_admin() || ! current_user_can( 'manage_options' ) || ! isset( $_GET[ self::$dismissal_key ] ) || ! isset( $_GET['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['nonce'] ) ), 'jb_dismiss_notice' ) ) { return; } // Dismiss the notice that shows up for major changes. static::dismiss(); wp_safe_redirect( remove_query_arg( array( self::$dismissal_key, 'nonce' ) ) ); } public static function init() { add_action( 'admin_notices', array( static::class, 'maybe_render' ) ); if ( static::is_enabled() ) { static::maybe_handle_dismissal(); } } public static function maybe_render() { // We're not actually using the GET parameter here, it's only used to find out what page we're on. // phpcs:disable WordPress.Security.NonceVerification.Recommended $on_settings_page = is_admin() && isset( $_GET['page'] ) && Admin::MENU_SLUG === $_GET['page']; if ( $on_settings_page || ! current_user_can( 'manage_options' ) ) { return; } if ( static::is_enabled() ) { static::render(); } } public static function render() { ?> <div id="jetpack-boost-notice-critical-css-regenerate" class="notice notice-warning is-dismissible"> <h3> <?php esc_html_e( 'Jetpack Boost - Action Required', 'jetpack-boost' ); ?> </h3> <p> <?php esc_html_e( 'The Critical CSS generated by Jetpack Boost was cleared due to a change in the site theme.', 'jetpack-boost' ); ?> </p> <p> <?php esc_html_e( 'Please head to the Jetpack Boost dashboard to regenerate your Critical CSS.', 'jetpack-boost' ); ?> </p> <p> <a class='button button-primary' href="<?php echo esc_url( admin_url( 'admin.php?page=' . Admin::MENU_SLUG ) ); ?>"> <strong> <?php esc_html_e( 'Go to Jetpack Boost', 'jetpack-boost' ); ?> </strong> </a> <a class="jb-dismiss-notice" href="<?php echo esc_url( static::get_dismiss_url() ); ?>"> <strong> <?php esc_html_e( 'Dismiss notice', 'jetpack-boost' ); ?> </strong> </a> </p> </div> <?php } }
projects/plugins/boost/app/admin/deactivation-dialog.php
<?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } ?> <main class="jp-plugin-deactivation__dialog__content"> <h1><?php esc_html_e( 'Are you sure you want to deactivate?', 'jetpack-boost' ); ?></h1> <p class="big"><?php esc_html_e( 'Before you go...', 'jetpack-boost' ); ?></p> <p><?php esc_html_e( "Thank you for trying Jetpack Boost. Before you go, we'd really love your feedback on our plugin.", 'jetpack-boost' ); ?></p> <p><?php esc_html_e( "Just temporarily deactivating or don't fancy giving feedback? No problem.", 'jetpack-boost' ); ?></p> </main> <footer class="jp-plugin-deactivation__dialog__actions"> <button type="button" class="jp-plugin-deactivation__button" data-jp-plugin-deactivation-action="close" ><?php esc_html_e( 'Cancel', 'jetpack-boost' ); ?></button> <button type="button" class="jp-plugin-deactivation__button jp-plugin-deactivation__button--outline jp-plugin-deactivation__button--destructive" data-jp-plugin-deactivation-action="deactivate" ><?php esc_html_e( 'Just Deactivate', 'jetpack-boost' ); ?></button> <!-- Using an anchor instead of a button for the Deactivate & Give Feedback may trigger browser's popup blocker as it is navigating to two URLs at once. --> <button type="button" class="jp-plugin-deactivation__button jp-plugin-deactivation__button--destructive" data-jp-plugin-deactivation-action="deactivate" onclick="window.open( 'https://jetpack.com/redirect/?source=jetpack-boost-deactivation-feedback', '_blank' )" ><?php esc_html_e( 'Deactivate & Give Feedback', 'jetpack-boost' ); ?></button> </footer> <style> #jp-plugin-deactivation-jetpack-boost p.big { font-size: 1.7em; } #jp-plugin-deactivation-jetpack-boost footer { text-align: center; } </style>
projects/plugins/boost/app/lib/Premium_Features.php
<?php namespace Automattic\Jetpack_Boost\Lib; use Automattic\Jetpack\Boost_Core\Lib\Boost_API; use Automattic\Jetpack\Boost_Core\Lib\Transient; class Premium_Features { const CLOUD_CSS = 'cloud-critical-css'; const IMAGE_SIZE_ANALYSIS = 'image-size-analysis'; const PERFORMANCE_HISTORY = 'performance-history'; const IMAGE_CDN_QUALITY = 'image-cdn-quality'; const PRIORITY_SUPPORT = 'support'; const PAGE_CACHE = 'page-cache'; const TRANSIENT_KEY = 'premium_features'; public static function has_feature( $feature ) { $features = self::get_features(); if ( is_array( $features ) ) { return in_array( $feature, $features, true ); } return false; } public static function get_features() { $available_features = Transient::get( self::TRANSIENT_KEY, false ); $all_features = array( self::CLOUD_CSS, self::IMAGE_SIZE_ANALYSIS, self::IMAGE_CDN_QUALITY, self::PERFORMANCE_HISTORY, self::PRIORITY_SUPPORT, ); if ( ! is_array( $available_features ) ) { $available_features = Boost_API::get( 'features' ); if ( ! is_array( $available_features ) ) { $available_features = array(); } Transient::set( self::TRANSIENT_KEY, $available_features, 3 * DAY_IN_SECONDS ); } $features = array(); // Prepare a list of features after applying jetpack_boost_has_feature_* filter for each feature. foreach ( $all_features as $feature ) { if ( apply_filters( "jetpack_boost_has_feature_{$feature}", in_array( $feature, $available_features, true ) ) ) { $features[] = $feature; } } return $features; } public static function has_any() { return count( self::get_features() ) > 0; } public static function clear_cache() { Transient::delete( self::TRANSIENT_KEY ); } }
projects/plugins/boost/app/lib/Boost_Health.php
<?php namespace Automattic\Jetpack_Boost\Lib; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State; use Automattic\Jetpack_Boost\Modules\Optimizations\Cloud_CSS\Cloud_CSS; use Automattic\Jetpack_Boost\Modules\Optimizations\Critical_CSS\Critical_CSS; /** * Class Boost_Health * * Represents the health of the Jetpack Boost plugin. */ class Boost_Health { /** * @var array List of issues affecting the health of the plugin. */ private $issues = array(); /** * Boost_Health constructor. * * Initializes the Boost_Health object and checks for any health issues. */ public function __construct() { if ( self::critical_css_needs_regeneration() ) { $this->issues[] = __( 'Outdated Critical CSS', 'jetpack-boost' ); } if ( self::critical_css_has_errors() ) { $this->issues[] = __( 'Failed to generate Critical CSS', 'jetpack-boost' ); } } /** * Get the total number of issues affecting the health of the plugin. * * @return int Total number of issues. */ public function get_total_issues() { return count( $this->issues ); } /** * Get all the issues affecting the health of the plugin. * * @return array List of issues. */ public function get_all_issues() { return $this->issues; } private static function is_critical_css_enabled() { return ( new Status( Critical_CSS::get_slug() ) )->is_enabled(); } /** * Check if Critical CSS needs regeneration. * * @return bool True if regeneration is needed, false otherwise. */ public static function critical_css_needs_regeneration() { if ( Cloud_CSS::is_available() || ! self::is_critical_css_enabled() ) { return false; } $suggest_regenerate = jetpack_boost_ds_get( 'critical_css_suggest_regenerate' ); return in_array( $suggest_regenerate, Environment_Change_Detector::get_available_env_change_statuses(), true ); } /** * Check if Critical CSS generation has errors. * * @return bool True if errors are present, false otherwise. */ public static function critical_css_has_errors() { if ( ! self::is_critical_css_enabled() ) { return false; } return ( new Critical_CSS_State() )->has_errors(); } }
projects/plugins/boost/app/lib/class-assets.php
<?php /** * Asset Manager for Jetpack Boost. * * @link https://automattic.com * @since 1.0.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib; /** * Class Assets */ class Assets { /** * Given a minified path, and a non-minified path, will return * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy. * * Both `$min_base` and `$non_min_base` are expected to be relative to the * root Jetpack directory. * * @param string $min_path minified path. * @param string $non_min_path non-minified path. * * @return string The URL to the file * @since 1.0.0 */ public static function get_file_url_for_environment( $min_path, $non_min_path ) { $internal_path = apply_filters( 'jetpack_boost_asset_internal_path', 'app/assets/dist/' ); $url = plugins_url( $internal_path . trim( $non_min_path, '/' ), JETPACK_BOOST_PATH ); /** * Filters the URL for a file passed through the get_file_url_for_environment function. * * @param string $url The URL to the file. * @param string $min_path The minified path. * @param string $non_min_path The non-minified path. * * @since 1.0.0 */ return apply_filters( 'jetpack_boost_asset_url', $url, $min_path, $non_min_path ); } }
projects/plugins/boost/app/lib/class-connection.php
<?php /** * Jetpack connection client. * * @link https://automattic.com * @since 1.0.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib; use Automattic\Jetpack\Config as Jetpack_Config; use Automattic\Jetpack\Connection\Manager; use Automattic\Jetpack\Terms_Of_Service; /** * Class Connection * * Manages the Jetpack connection on behalf of Jetpack Boost. */ class Connection { /** * Jetpack Connection Manager. * * @var Manager $manager The connection manager. */ private $manager; public function __construct() { $this->manager = new Manager( 'jetpack-boost' ); } public function init() { add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) ); $this->initialize_deactivate_disconnect(); } /** * Initialize the plugin deactivation hook. */ public function initialize_deactivate_disconnect() { require_once ABSPATH . '/wp-admin/includes/plugin.php'; if ( is_plugin_active_for_network( JETPACK_BOOST_PATH ) ) { register_deactivation_hook( JETPACK_BOOST_PATH, array( $this, 'deactivate_disconnect_network' ) ); } else { register_deactivation_hook( JETPACK_BOOST_PATH, array( $this, 'deactivate_disconnect' ) ); } } /** * Deactivate the connection on plugin disconnect. */ public function deactivate_disconnect() { $this->manager->remove_connection(); } /** * Deactivate the connection on plugin disconnect for network-activated plugins. */ public function deactivate_disconnect_network() { if ( ! is_network_admin() ) { return; } foreach ( get_sites() as $s ) { switch_to_blog( $s->blog_id ); $active_plugins = get_option( 'active_plugins' ); /* * If this plugin was activated in the subsite individually * we do not want to call disconnect. Plugins activated * individually (before network activation) stay activated * when the network deactivation occurs */ if ( ! in_array( JETPACK_BOOST_PATH, $active_plugins, true ) ) { $this->deactivate_disconnect(); } restore_current_blog(); } } /** * Connection Lifecycle methods. */ /** * Get the WordPress.com blog ID of this site, if it's connected */ public static function wpcom_blog_id() { return defined( 'IS_WPCOM' ) && IS_WPCOM ? get_current_blog_id() : (int) \Jetpack_Options::get_option( 'id' ); } /** * True if the site is connected to WP.com. * * @return boolean */ public function is_connected() { if ( true === apply_filters( 'jetpack_boost_connection_bypass', false ) ) { return true; } return $this->manager->is_connected(); } /** * Register site using connection manager. * * @return true|\WP_Error The error object. */ public function register() { if ( $this->is_connected() ) { Analytics::record_user_event( 'using_existing_connection' ); return true; } $result = $this->manager->register(); if ( ! is_wp_error( $result ) ) { Analytics::record_user_event( 'established_connection' ); Premium_Features::clear_cache(); } return $result; } /** * Disconnect from Jetpack account. * * @return bool */ public function disconnect() { // @todo implement check for Jetpack::validate_sync_error_idc_option() so we don't disconnect production site from staging etc. Analytics::record_user_event( 'disconnect_site' ); $this->manager->remove_connection(); return true; } /** * REST endpoint methods. */ public function register_rest_routes() { register_rest_route( JETPACK_BOOST_REST_NAMESPACE, JETPACK_BOOST_REST_PREFIX . '/connection', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => array( $this, 'get_connection_endpoint' ), 'permission_callback' => array( $this, 'can_manage_connection' ), ) ); register_rest_route( JETPACK_BOOST_REST_NAMESPACE, JETPACK_BOOST_REST_PREFIX . '/connection', array( 'methods' => \WP_REST_Server::EDITABLE, 'callback' => array( $this, 'create_connection_endpoint' ), 'permission_callback' => array( $this, 'can_manage_connection' ), ) ); } /** * Register site using connection manager. * * @param \WP_REST_Request $request The request object. * * @return \WP_REST_Response|\WP_Error */ public function create_connection_endpoint( \WP_REST_Request $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable ( new Terms_Of_Service() )->agree(); $response = $this->register(); // Clear premium features cache to force a refresh. Premium_Features::clear_cache(); if ( is_wp_error( $response ) ) { return $response; } do_action( 'jetpack_boost_connection_established' ); return rest_ensure_response( $this->get_connection_api_response() ); } /** * Fetch connection info. * * @param \WP_REST_Request $request The request object. * * @return \WP_REST_Response|\WP_Error */ public function get_connection_endpoint( \WP_REST_Request $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable return rest_ensure_response( $this->get_connection_api_response() ); } /** * Connection state sent to client on initialization and after updates. * * @return array */ public function get_connection_api_response() { $force_connected = apply_filters( 'jetpack_boost_connection_bypass', false ); $response = array( 'connected' => $force_connected || $this->is_connected(), 'wpcomBlogId' => ( $force_connected || $this->is_connected() ) ? self::wpcom_blog_id() : null, 'userConnected' => $this->manager->is_user_connected(), ); return $response; } /** * Can user manage the connection? * * @return boolean | \WP_Error */ public function can_manage_connection() { if ( current_user_can( 'manage_options' ) ) { return true; } $user_permissions_error_msg = __( 'You do not have the correct user permissions to perform this action. Please contact your site admin if you think this is a mistake.', 'jetpack-boost' ); return new \WP_Error( 'invalid_user_permission_jetpack_connect', $user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) ); } /** * Contextual HTTP error code for authorization failure. * * Taken from rest_authorization_required_code() in WP-API plugin until is added to core. * * @see https://github.com/WP-API/WP-API/commit/7ba0ae6fe4f605d5ffe4ee85b1cd5f9fb46900a6 * * @since 4.3.0 * * @return int */ public static function rest_authorization_required_code() { return is_user_logged_in() ? 403 : 401; } public function ensure_connection() { if ( ! apply_filters( 'jetpack_boost_connection_bypass', false ) ) { $jetpack_config = new Jetpack_Config(); $jetpack_config->ensure( 'connection', array( 'slug' => 'jetpack-boost', 'name' => 'Jetpack Boost', 'url_info' => '', // Optional, URL of the plugin. ) ); } } }
projects/plugins/boost/app/lib/class-output-filter.php
<?php /** * Uses standard output buffering implemented to PHP * to allow for manipulating the output stream. * * The implementation allows for seamless text search and manipulation by * always taking into account two subsequent chunks of data. * * Example sequence of chunks sent to output (chunk size 4): * * ABCD EFGH IJKL MNOP QRST * * A standard output buffer callback handler would always receive only one * of those chunks, e.g. 'ABCD' and would be unable to match strings on * seams of individual chunks, e.g. 'DEF', because 'D' appears in chunk #1, * whereas 'EF' in chunk #2. * * This class solves this issue by utilizing a sliding window of size 2 chunks. * That means the callback receives: * * ABCDEFGH EFEGHIJKL IJKLMNOP MNOPQRST * * That allows for more advanced string manipulation even across chunk seams. * It is assumed any string searches are much shorter than a chunk size. * * @link https://automattic.com * @since 0.2.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib; /** * Class Output_Filter */ class Output_Filter { /** * Output chunk size. */ const CHUNK_SIZE = 4096; /** * List of callbacks. * * @var array */ private $callbacks = array(); /** * One chunk always remains in the buffer to allow for cross-seam matching. * * @var string */ private $buffered_chunk = ''; /** * Whether we allow the callbacks to filter incoming chunks of output. * * @var boolean */ private $is_filtering = false; /** * Add an output filtering callback. * * @param callable $callback Output filtering callback. * * @return void */ public function add_callback( $callback ) { $this->callbacks[] = $callback; if ( 1 === count( $this->callbacks ) ) { // Start filtering output now that we have some callbacks. $this->is_filtering = true; ob_start( array( $this, 'tick' ), self::CHUNK_SIZE ); } } /** * Processing a full output buffer. * * @param string $buffer Output buffer. * @param int $phase Bitmask of PHP_OUTPUT_HANDLER_* constants. * * @return string Buffer data to be flushed to browser. */ public function tick( $buffer, $phase ) { // Bail early if not filtering. if ( ! $this->is_filtering ) { return $buffer; } // Check if this the first or last buffer. Use the $phase bitmask to figure it out. // $phase can contain multiple PHP_OUTPUT_HANDLER_* constants. // e.g.: PHP_OUTPUT_HANDLER_END = 8 (binary 1000), PHP_OUTPUT_HANDLER_START = 1 (binary 0001). Both = 9 (binary 1001). // Use bitwise AND to read individual flags from $phase. $is_first_chunk = ( $phase & PHP_OUTPUT_HANDLER_START ) > 0; $is_last_chunk = ( $phase & PHP_OUTPUT_HANDLER_END ) > 0; // Don't handle the first chunk (unless it's also the last) - we want to output // one chunk behind the latest to allow for cross-seam matching. if ( $is_first_chunk && ! $is_last_chunk ) { $this->buffered_chunk = $buffer; return ''; } $buffer_start = $this->buffered_chunk; $buffer_end = $buffer; foreach ( $this->callbacks as $callback ) { list( $buffer_start, $buffer_end ) = call_user_func( $callback, $buffer_start, $buffer_end ); } $this->buffered_chunk = $buffer_end; $joint_buffer = $buffer_start . $buffer_end; // If the second part of the buffer is the last chunk, // merge the buffer back together to ensure whole output. if ( $is_last_chunk ) { // If more buffer chunks arrive, don't apply callbacks to them. $this->is_filtering = false; // Join remaining buffers and allow plugin to append anything to them. return apply_filters( 'jetpack_boost_output_filtering_last_buffer', $joint_buffer, $buffer_start, $buffer_end ); } // Send the first part of the whole buffer to the browser only, // because buffer_end will be manipulated in the next tick. return $buffer_start; } }
projects/plugins/boost/app/lib/class-minify.php
<?php /** * Implement the minify class. * * @link https://automattic.com * @since 0.2 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib; use JShrink\Minifier as JSMinifier; use tubalmartin\CssMin\Minifier as CSSMinifier; /** * Class Minify */ class Minify { /** * @var Minify - Holds the CssMin\Minifier instance, for reuse on subsequent calls. */ private static $css_minifier; /** * Strips whitespace from JavaScript scripts. * * @param string $js Input JS string. * * @return string String with whitespace stripped. */ public static function js( $js ) { require_once JETPACK_BOOST_DIR_PATH . '/vendor/tedivm/jshrink/src/JShrink/Minifier.php'; try { $minified_js = JSMinifier::minify( $js ); } catch ( \Exception $e ) { return $js; } return $minified_js; } /** * Minifies the supplied CSS code, returning its minified form. */ public static function css( $css ) { if ( ! self::$css_minifier ) { self::$css_minifier = new CSSMinifier(); } return self::$css_minifier->run( $css ); } }
projects/plugins/boost/app/lib/class-cli.php
<?php /** * CLI commands for Jetpack Boost. * * @link https://automattic.com * @since 1.0.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib; use Automattic\Jetpack_Boost\Data_Sync\Getting_Started_Entry; use Automattic\Jetpack_Boost\Jetpack_Boost; /** * Control your local Jetpack Boost installation. */ class CLI { /** * Jetpack Boost plugin. * * @var \Automattic\Jetpack_Boost\Jetpack_Boost $jetpack_boost */ private $jetpack_boost; const MAKE_E2E_TESTS_WORK_MODULES = array( 'critical_css', 'render_blocking_js' ); /** * CLI constructor. * * @param \Automattic\Jetpack_Boost\Jetpack_Boost $jetpack_boost Jetpack Boost plugin. */ public function __construct( $jetpack_boost ) { $this->jetpack_boost = $jetpack_boost; } /** * Manage Jetpack Boost Modules * * ## OPTIONS * * <activate|deactivate> * : The action to take. * --- * options: * - activate * - deactivate * --- * * [<module_slug>] * : The slug of the module to perform an action on. * * ## EXAMPLES * * wp jetpack-boost module activate critical_css * wp jetpack-boost module deactivate critical_css * * @param array $args Command arguments. */ public function module( $args ) { $action = isset( $args[0] ) ? $args[0] : null; $module_slug = null; if ( isset( $args[1] ) ) { $module_slug = $args[1]; if ( ! in_array( $module_slug, self::MAKE_E2E_TESTS_WORK_MODULES, true ) ) { \WP_CLI::error( /* translators: %s refers to the module slug like 'critical-css' */ sprintf( __( "The '%s' module slug is invalid", 'jetpack-boost' ), $module_slug ) ); } } else { /* translators: Placeholder is list of available modules. */ \WP_CLI::error( sprintf( __( 'Please specify a valid module. It should be one of %s', 'jetpack-boost' ), wp_json_encode( Jetpack_Boost::AVAILABLE_MODULES_DEFAULT ) ) ); } switch ( $action ) { case 'activate': $this->set_module_status( $module_slug, true ); break; case 'deactivate': $this->set_module_status( $module_slug, false ); break; } } public function getting_started( $args ) { $status = isset( $args[0] ) ? $args[0] : null; if ( ! in_array( $status, array( 'true', 'false' ), true ) ) { \WP_CLI::error( /* translators: %s refers to the module slug like 'critical-css' */ sprintf( __( "The '%s' status is invalid", 'jetpack-boost' ), $status ) ); } ( new Getting_Started_Entry() )->set( 'true' === $status ); \WP_CLI::success( /* translators: %s refers to 'true' or 'false' */ sprintf( __( 'Getting started is set to %s', 'jetpack-boost' ), $status ) ); } /** * Set a module status. * * @param string $module_slug Module slug. * @param string $status Module status. */ private function set_module_status( $module_slug, $status ) { ( new Status( $module_slug ) )->update( $status ); $status_label = $status ? __( 'activated', 'jetpack-boost' ) : __( 'deactivated', 'jetpack-boost' ); /* translators: The %1$s refers to the module slug, %2$s refers to the module state (either activated or deactivated)*/ \WP_CLI::success( sprintf( __( "'%1\$s' has been %2\$s.", 'jetpack-boost' ), $module_slug, $status_label ) ); } /** * Manage Jetpack Boost connection * * ## OPTIONS * * <activate|deactivate|status> * : The action to take. * --- * options: * - activate * - deactivate * - status * --- * * ## EXAMPLES * * wp jetpack-boost connection activate * wp jetpack-boost connection deactivate * wp jetpack-boost connection status * * @param array $args Command arguments. */ public function connection( $args ) { $action = isset( $args[0] ) ? $args[0] : null; switch ( $action ) { case 'activate': $result = $this->jetpack_boost->connection->register(); if ( true === $result ) { \WP_CLI::success( __( 'Boost is connected to WP.com', 'jetpack-boost' ) ); } else { \WP_CLI::error( __( 'Boost could not be connected to WP.com', 'jetpack-boost' ) ); } break; case 'deactivate': require_once ABSPATH . '/wp-admin/includes/plugin.php'; if ( is_plugin_active_for_network( JETPACK_BOOST_PATH ) ) { $this->jetpack_boost->connection->deactivate_disconnect_network(); } else { $this->jetpack_boost->connection->disconnect(); } \WP_CLI::success( __( 'Boost is disconnected from WP.com', 'jetpack-boost' ) ); break; case 'status': $is_connected = $this->jetpack_boost->connection->is_connected(); if ( $is_connected ) { \WP_CLI::line( 'connected' ); } else { \WP_CLI::line( 'disconnected' ); } break; } } /** * Reset Jetpack Boost * * ## EXAMPLE * * wp jetpack-boost reset */ public function reset() { $this->jetpack_boost->deactivate(); $this->jetpack_boost->uninstall(); \WP_CLI::success( 'Reset successfully' ); } }
projects/plugins/boost/app/lib/class-site-urls.php
<?php namespace Automattic\Jetpack_Boost\Lib; class Site_Urls { public static function get( $limit = 100 ) { $core_urls = self::get_wp_core_urls(); $post_urls = self::cleanup_post_urls( self::get_post_urls( $limit ), wp_list_pluck( $core_urls, 'url' ) ); return array_slice( array_merge( $core_urls, $post_urls ), 0, $limit ); } private static function get_wp_core_urls() { $urls = array(); $front_page = get_option( 'page_on_front' ); if ( ! empty( $front_page ) ) { $urls['core_front_page'] = array( 'url' => get_permalink( $front_page ), 'modified' => get_post_modified_time( 'Y-m-d H:i:s', false, $front_page ), 'group' => 'core_front_page', ); } $posts_page = get_option( 'page_for_posts' ); if ( ! empty( $posts_page ) ) { $urls['core_posts_page'] = array( 'url' => get_permalink( $posts_page ), 'modified' => get_post_modified_time( 'Y-m-d H:i:s', false, $posts_page ), 'group' => 'other', ); } if ( empty( $front_page ) && empty( $posts_page ) ) { $urls['core_posts_page'] = array( 'url' => home_url( '/' ), 'modified' => current_time( 'Y-m-d H:i:s' ), 'group' => 'core_front_page', ); } return $urls; } private static function get_post_urls( $limit ) { global $wpdb; $public_post_types = self::get_public_post_types(); $post_types_placeholders = implode( ',', array_fill( 0, count( $public_post_types ), '%s' ) ); $prepare_values = $public_post_types; $prepare_values[] = $limit; // phpcs:ignore WordPress.DB.DirectDatabaseQuery $results = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared "SELECT ID, post_modified FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type IN ({$post_types_placeholders}) ORDER BY post_modified DESC LIMIT 0, %d", $prepare_values ) ); $urls = array(); foreach ( $results as $result ) { $urls[ 'post_id_' . $result->ID ] = array( 'url' => get_permalink( $result->ID ), 'modified' => get_post_modified_time( 'Y-m-d H:i:s', false, $result ), 'group' => self::get_post_group( $result ), ); } return $urls; } /** * Removes duplicate URLs from the $post_urls list * based on the additional URLs. * * @param $post_urls List of URLs to cleanup. * @param $additional_urls List of URLs to lookup while cleaning. * * @return array */ private static function cleanup_post_urls( $post_urls, $additional_urls ) { $clean = array(); foreach ( $post_urls as $key => $item ) { if ( in_array( $item['url'], $additional_urls, true ) ) { continue; } $clean[ $key ] = $item; } return $clean; } private static function get_public_post_types() { $post_types = get_post_types( array( 'public' => true, ) ); unset( $post_types['attachment'] ); return array_values( array_filter( $post_types, 'is_post_type_viewable' ) ); } /** * Returns the group for the post. * * @param $p Post object. * * @return string */ private static function get_post_group( $p ) { $post_type = get_post_type( $p->ID ); if ( 'post' === $post_type || 'page' === $post_type ) { return 'singular_' . $post_type; } return 'other'; } }
projects/plugins/boost/app/lib/Super_Cache_Info.php
<?php /** * Information for Super Cache users * * @link https://automattic.com * @since 1.0.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib; /** * Class Super_Cache_Info */ class Super_Cache_Info { private static function is_super_cache_enabled() { return self::is_super_cache_plugin_active() && \wp_cache_is_enabled(); } private static function is_super_cache_plugin_active() { return \function_exists( 'wp_cache_is_enabled' ); } public static function get_info() { global $cache_page_secret; $constants = array( 'pluginActive' => self::is_super_cache_plugin_active(), 'cacheEnabled' => self::is_super_cache_enabled(), ); if ( isset( $cache_page_secret ) ) { $constants['cachePageSecret'] = $cache_page_secret; } return $constants; } }
projects/plugins/boost/app/lib/Environment_Change_Detector.php
<?php /** * Environment Change Detector class. * * @link https://automattic.com * @since 1.0.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib; /** * Class Environment_Change_Detector */ class Environment_Change_Detector { const ENV_CHANGE_LEGACY = '1'; const ENV_CHANGE_PAGE_SAVED = 'page_saved'; const ENV_CHANGE_POST_SAVED = 'post_saved'; const ENV_CHANGE_SWITCHED_THEME = 'switched_theme'; const ENV_CHANGE_PLUGIN_CHANGE = 'plugin_change'; /** * Initialize the change detection hooks. */ public static function init() { $object = new self(); $object->register_hooks(); } public function register_hooks() { add_action( 'after_switch_theme', array( $this, 'handle_theme_change' ) ); add_action( 'save_post', array( $this, 'handle_post_change' ), 10, 2 ); add_action( 'activated_plugin', array( $this, 'handle_plugin_change' ) ); add_action( 'deactivated_plugin', array( $this, 'handle_plugin_change' ) ); } public function handle_post_change( $post_id, $post ) { // Ignore changes to any post which is not published. if ( 'publish' !== $post->post_status ) { return; } // Ignore changes to post types which do not affect the front-end UI if ( ! $this->is_post_type_invalidating( $post->post_type ) ) { return; } if ( 'page' === $post->post_type ) { $change_type = $this::ENV_CHANGE_PAGE_SAVED; } else { $change_type = $this::ENV_CHANGE_POST_SAVED; } $this->do_action( false, $change_type ); } public function handle_theme_change() { $this->do_action( true, $this::ENV_CHANGE_SWITCHED_THEME ); } public function handle_plugin_change() { $this->do_action( false, $this::ENV_CHANGE_PLUGIN_CHANGE ); } /** * Fire the environment change action. * * @param string $change_type The change type. * @param bool $is_major_change Whether the change is major. */ public function do_action( $is_major_change, $change_type ) { do_action( 'handle_environment_change', $is_major_change, $change_type ); } public static function get_available_env_change_statuses() { return array( self::ENV_CHANGE_PAGE_SAVED, self::ENV_CHANGE_POST_SAVED, self::ENV_CHANGE_SWITCHED_THEME, self::ENV_CHANGE_PLUGIN_CHANGE, ); } /** * Given a post_type, return true if this post type affects the front end of * the site - i.e.: should cause cached optimizations to be invalidated. * * @param string $post_type The post type to check * @return bool True if this post type affects the front end of the site. */ private function is_post_type_invalidating( $post_type ) { // Special cases: items which are not viewable, but affect the UI. if ( in_array( $post_type, array( 'wp_template', 'wp_template_part' ), true ) ) { return true; } if ( is_post_type_viewable( $post_type ) ) { return true; } } }
projects/plugins/boost/app/lib/Premium_Pricing.php
<?php namespace Automattic\Jetpack_Boost\Lib; use Automattic\Jetpack\My_Jetpack\Wpcom_Products; use Automattic\Jetpack\Status; class Premium_Pricing { const PRODUCT_SLUG_BASE = 'jetpack_boost'; /** * Get an object containing the yearly pricing information for Jetpack Boost. * * Used by Jetpack_Boost js constants and data sync. */ public static function get_yearly_pricing() { $yearly_pricing_slug = self::PRODUCT_SLUG_BASE . '_yearly'; $yearly_pricing = Wpcom_Products::get_product_pricing( $yearly_pricing_slug ); if ( empty( $yearly_pricing ) ) { // In offline mode, we don't have access to the pricing data and it's not an error. if ( ! ( new Status() )->is_offline_mode() ) { Analytics::record_user_event( 'upgrade_price_missing', array( 'error_message' => 'Missing pricing information on benefits interstitial page.' ) ); } return null; } return array( 'priceBefore' => $yearly_pricing['full_price'], 'priceAfter' => $yearly_pricing['discount_price'], 'currencyCode' => $yearly_pricing['currency_code'], 'isIntroductoryOffer' => $yearly_pricing['is_introductory_offer'] === true, ); } }
projects/plugins/boost/app/lib/class-debug.php
<?php /** * Implement debug helper methods. * * @link https://automattic.com * @since 1.0.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib; /** * Class Debug */ class Debug { /** * Returns whether the debug mode has been triggered. */ public static function is_debug_mode() { $script_debug = defined( 'SCRIPT_DEBUG' ) && \SCRIPT_DEBUG; $manual_debug_mode = filter_input( INPUT_GET, 'jetpack-boost-debug' ); $debug = $script_debug || $manual_debug_mode; return apply_filters( 'jetpack_boost_debug', $debug ); } }
projects/plugins/boost/app/lib/class-nonce.php
<?php /** * Implement nonce helper methods. * * @link https://automattic.com * @since 1.0.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib; /** * Class Nonce */ class Nonce { /** * This is a light clone of wp_create_nonce and wp_verify_nonce which skips the UID and cookie token parts, * so it can be used in anonymous HTTP callbacks. It is therefore not as secure, so be careful. * * @param string $action The action. */ public static function create( $action ) { return substr( wp_hash( wp_nonce_tick() . '|' . $action, 'nonce' ), -12, 10 ); } /** * Verify the nonce. * * @param string $nonce The nonce. * @param string $action The action. */ public static function verify( $nonce, $action ) { $i = wp_nonce_tick(); // Current nonce. $expected = substr( wp_hash( $i . '|' . $action, 'nonce' ), -12, 10 ); if ( hash_equals( $expected, $nonce ) ) { return 1; } // Nonce generated 12-24 hours ago. $expected = substr( wp_hash( ( $i - 1 ) . '|' . $action, 'nonce' ), -12, 10 ); if ( hash_equals( $expected, $nonce ) ) { return 2; } return false; } }
projects/plugins/boost/app/lib/Status.php
<?php namespace Automattic\Jetpack_Boost\Lib; use Automattic\Jetpack_Boost\Modules\Modules_Setup; use Automattic\Jetpack_Boost\Modules\Optimizations\Cloud_CSS\Cloud_CSS; use Automattic\Jetpack_Boost\Modules\Optimizations\Critical_CSS\Critical_CSS; class Status { /** * Slug of the optimization module which is currently being toggled * * @var string $slug */ protected $slug; /** * A map of modules whose status are synced. * * @var array[] $status_sync_map */ protected $status_sync_map; public function __construct( $slug ) { $this->slug = $slug; $this->status_sync_map = array( Cloud_CSS::get_slug() => array( Critical_CSS::get_slug(), ), ); } public function update( $new_status ) { $entry = jetpack_boost_ds_get( 'modules_state' ); $entry[ $this->slug ]['active'] = $new_status; jetpack_boost_ds_set( 'modules_state', $entry ); } public function is_enabled() { $modules_state = jetpack_boost_ds_get( 'modules_state' ); return $modules_state[ $this->slug ]['active']; } /** * Called when the module is toggled. * * Called by Modules and triggered by the `jetpack_ds_set` action. */ public function on_update( $new_status ) { $this->update_mapped_modules( $new_status ); $this->track_module_status( (bool) $new_status ); } /** * Update modules which are to follow the status of the current module. * * For example: critical-css module status should be synced with cloud-css module. * * @param $new_status * @return void */ protected function update_mapped_modules( $new_status ) { if ( ! isset( $this->status_sync_map[ $this->slug ] ) ) { return; } $modules_instance = Setup::get_instance_of( Modules_Setup::class ); // The moduleInstance will be there. But check just in case. if ( $modules_instance !== null ) { // Remove the action temporarily to avoid infinite loop. remove_action( 'jetpack_boost_module_status_updated', array( $modules_instance, 'on_module_status_update' ) ); } foreach ( $this->status_sync_map[ $this->slug ] as $mapped_module ) { $mapped_status = new Status( $mapped_module ); $mapped_status->update( $new_status ); } // The moduleInstance will be there. But check just in case. if ( $modules_instance !== null ) { add_action( 'jetpack_boost_module_status_updated', array( $modules_instance, 'on_module_status_update' ), 10, 2 ); } } protected function track_module_status( $status ) { Analytics::record_user_event( 'set_module_status', array( 'module' => $this->slug, 'status' => $status, ) ); } }
projects/plugins/boost/app/lib/class-analytics.php
<?php /** * Simple wrapper for Tracks library * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib; use Automattic\Jetpack\Connection\Manager; use Automattic\Jetpack\Tracking; use Jetpack_Options; use Jetpack_Tracks_Client; /** * Class Analytics */ class Analytics { /** * Initialize tracking. */ public function init() { $tracks = self::get_tracking(); // For tracking events via js/ajax. add_action( 'admin_enqueue_scripts', array( $tracks, 'enqueue_tracks_scripts' ) ); } /** * Get the tracking and manager objects for Boost. */ public static function get_tracking() { return new Tracking( 'jetpack_boost', new Manager( 'jetpack-boost' ) ); } /** * Record a user event. * * @param string $slug The event slug. * @param array $data Optional event data. */ public static function record_user_event( $slug, $data = array() ) { if ( ! isset( $data['boost_version'] ) && defined( 'JETPACK_BOOST_VERSION' ) ) { $data['boost_version'] = JETPACK_BOOST_VERSION; } return self::get_tracking()->record_user_event( $slug, $data ); } public static function init_tracks_scripts() { $tracks = self::get_tracking(); $tracks::register_tracks_functions_scripts(); wp_enqueue_script( 'jp-tracks' ); } public static function get_tracking_data() { if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) { $user = wp_get_current_user(); $user_data = array( 'userid' => $user->ID, 'username' => $user->user_login, ); $blog_id = get_current_blog_id(); } else { $user_data = Jetpack_Tracks_Client::get_connected_user_tracks_identity(); $blog_id = Jetpack_Options::get_option( 'id', 0 ); } return array( 'userData' => $user_data, 'blogId' => $blog_id, ); } }
projects/plugins/boost/app/lib/Setup.php
<?php namespace Automattic\Jetpack_Boost\Lib; use Automattic\Jetpack_Boost\Contracts\Has_Setup; class Setup { protected static $instances = array(); /** * This method takes a `Has_Setup` instance and registers the setup action. * In addition, it will keep track of all the instances passed to it, * * This is useful if a plugin needs the instance * to modify the behavior at a certain hook that * Jetpack Boost is using. * * The use case would be something like this: * ``` * $instance = my_get_instance_method( Setup::get_instances() ); * remove_action( 'wp_footer', array( $instance, 'foobar' ) ); * ``` * * @param Has_Setup $instance * * @return void */ public static function add( Has_Setup $instance ) { $instance->setup(); self::$instances[] = $instance; } public static function get_instances() { return self::$instances; } public static function get_instance_of( $class_name ) { foreach ( self::get_instances() as $instance ) { if ( $instance instanceof $class_name ) { return $instance; } } return null; } }
projects/plugins/boost/app/lib/class-viewport.php
<?php /** * Implements the Viewport functionality. * * @link https://automattic.com * @since 1.0.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib; use Automattic\Jetpack\Device_Detection; /** * Class Viewport */ class Viewport { /** * Viewport cookie name. */ const VIEWPORT_COOKIE = 'jetpack_boost_w'; /** * Mobile device identifier. */ const DEVICE_MOBILE = 'mobile'; /** * Desktop identifier. */ const DEVICE_DESKTOP = 'desktop'; /** * Default viewport sizes. */ const DEFAULT_VIEWPORT_SIZES = array( 0 => array( 'type' => 'phone', 'width' => 640, 'height' => 480, ), 1 => array( 'type' => 'tablet', 'width' => 1200, 'height' => 800, ), 2 => array( 'type' => 'desktop', 'width' => 1600, 'height' => 1050, ), ); /** * Default viewports. */ const DEFAULT_VIEWPORTS = array( array( 'device_type' => 'mobile', 'viewport_id' => 0, ), array( 'device_type' => 'desktop', 'viewport_id' => 2, ), ); /** * Runs the module. */ public static function init() { if ( ! is_admin() ) { add_action( 'wp_footer', array( __CLASS__, 'viewport_tracker' ) ); } } /** * Prints JS viewport dimensions tracker to the page. * * The purpose of the tracker is to measure the actual device viewport and store that value * in a cookie that is then consumed by `get_viewport_size`. The dimensions are updated * whenever the page is loaded, viewport resized or document shown (using Page Visibility API). * * This allows site admins to define and target more granular real-world viewports. * * First page load from a new device will result in a viewport size guessed based on the device * type (mobile vs. desktop). See `get_default_viewport_size_for_device` for more context. */ public static function viewport_tracker() { $domain = wp_parse_url( site_url(), PHP_URL_HOST ); $path = wp_parse_url( site_url(), PHP_URL_PATH ); if ( ! $path ) { $path = '/'; } $max_age = 10 * \YEAR_IN_SECONDS; $script_source = <<<SCRIPT_SOURCE ( function(doc) { var debouncer; var measure = function() { var cookieValue = Math.ceil( window.innerWidth / 10 ) + 'x' + Math.ceil( window.innerHeight / 10 ); doc.cookie = "%s=" + cookieValue + "; domain=%s; path=%s; Max-Age=%s"; } window.addEventListener( 'resize', function() { clearTimeout( debouncer ); debouncer = setTimeout( measure, 500 ); } ); doc.addEventListener( 'visibilitychange', function() { if ( ! doc.hidden ) { measure(); } } ); measure(); } )(document); SCRIPT_SOURCE; $script_source = sprintf( $script_source, esc_js( self::VIEWPORT_COOKIE ), esc_js( $domain ), esc_js( $path ), esc_js( $max_age ) ); if ( ! Debug::is_debug_mode() ) { $script_source = Minify::js( $script_source ); } printf( '<script>%s</script>', $script_source ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } /** * Gets the size of the current viewport. */ public static function get_viewport_size() { $data = null; $cookie_value = filter_input( INPUT_COOKIE, self::VIEWPORT_COOKIE ); if ( $cookie_value ) { $raw_data = explode( 'x', $cookie_value ); if ( 2 === count( $raw_data ) ) { $data = array( 'width' => intval( $raw_data[0] ) * 10, 'height' => intval( $raw_data[1] ) * 10, ); } } else { $device_type = Device_Detection::is_phone() ? self::DEVICE_MOBILE : self::DEVICE_DESKTOP; $data = self::get_default_viewport_size_for_device( $device_type ); } return apply_filters( 'jetpack_boost_viewport_size', $data, self::VIEWPORT_COOKIE, $cookie_value ); } /** * Get all the configured viewport sizes. * * @return array Viewport widths and heights */ public static function get_default_viewport_sizes() { return apply_filters( 'jetpack_boost_critical_css_viewport_sizes', self::DEFAULT_VIEWPORT_SIZES ); } /** * Get the default viewport size. * * @param string $device_type Device type. * * @return array Viewport width and height. */ public static function get_default_viewport_size_for_device( $device_type ) { $viewport_sizes = apply_filters( 'jetpack_boost_critical_css_viewport_sizes', self::DEFAULT_VIEWPORT_SIZES ); $default_viewports = apply_filters( 'jetpack_boost_critical_css_default_viewports', self::DEFAULT_VIEWPORTS ); foreach ( $default_viewports as $default ) { if ( $device_type === $default['device_type'] ) { if ( isset( $viewport_sizes[ $default['viewport_id'] ] ) ) { return $viewport_sizes[ $default['viewport_id'] ]; } } } return self::get_max_viewport( $viewport_sizes ); } /** * Picks the narrowest defined viewport that is equal or wider than the passed width. * * When there are multiple defined viewports of identical width, picks the smallest * height that's equal or taller than the passed height. * * Example for w:550 h:400 and defined viewport sizes: 400x300, 640x400, 640x480, 1050x900, 1900x1200 * * - The smallest viewports that are wider than the current one are: 640x400, 640x480 * - The one with the smallest height that is equal or taller than the passed dimensions: 640x400 * - Returned [ 640, 480 ] * * @param int $width Width. * @param int $height Height. * * @return array Viewport dimensions. */ public static function pick_viewport( $width, $height ) { // Get defined viewport sizes. $viewport_sizes = apply_filters( 'jetpack_boost_critical_css_viewport_sizes', self::DEFAULT_VIEWPORT_SIZES ); // Default to the widest viewport in case we don't match anything. $best_size = self::get_max_viewport( $viewport_sizes ); foreach ( $viewport_sizes as $viewport_size ) { // Skip viewports that are too narrow. if ( $viewport_size['width'] < $width ) { continue; } // Skip viewports that are wider than our best match. if ( $viewport_size['width'] > $best_size['width'] ) { continue; } // Pick viewports that are narrower than our best match. if ( $viewport_size['width'] < $best_size['width'] ) { $best_size = $viewport_size; continue; } // Current viewport and the best match have the same width, let's decide based on height. $current_is_tall_enough = $viewport_size['height'] >= $height; $best_is_tall_enough = $best_size['height'] >= $height; if ( $current_is_tall_enough && ! $best_is_tall_enough ) { $best_size = $viewport_size; // Best match isn't tall enough, but the current match is. continue; } if ( $current_is_tall_enough && $best_is_tall_enough && $viewport_size['height'] < $best_size['height'] ) { $best_size = $viewport_size; // Both ARE tall enough, but the current match is shorter. continue; } if ( ! $current_is_tall_enough && ! $best_is_tall_enough && $viewport_size['height'] > $best_size['height'] ) { $best_size = $viewport_size; // Both ARE NOT tall enough, but the current match is taller. continue; } } return apply_filters( 'jetpack_boost_pick_viewport', $best_size, $width, $height, $viewport_sizes ); } /** * Reduce the viewports array and return the widest one. * * When there are multiple widest viewports, pick the tallest one from those. * * @param array $viewport_sizes Array of defined viewport sizes. * * @return array Viewport dimensions. */ public static function get_max_viewport( array $viewport_sizes ) { $max_viewport = array_reduce( $viewport_sizes, function ( $carry, $item ) { if ( $item['width'] > $carry['width'] ) { $carry = $item; } elseif ( $item['width'] === $carry['width'] ) { if ( $item['height'] > $carry['height'] ) { $carry = $item; } } return $carry; }, array( 'width' => 0, 'height' => 0, ) ); return $max_viewport; } }
projects/plugins/boost/app/lib/Site_Health.php
<?php namespace Automattic\Jetpack_Boost\Lib; /** * Site_Health. * * Displays performance issues in WordPress site health page. */ class Site_Health { /** * Initialize hooks * * @access public * @return void */ public static function init() { if ( ! has_filter( 'site_status_tests', array( __CLASS__, 'add_check' ) ) ) { add_filter( 'site_status_tests', array( __CLASS__, 'add_check' ), 99 ); } } /** * Add site-health page tests. * * @param array $checks Core checks. * * @access public * @return array */ public static function add_check( $checks ) { $checks['direct']['jetpack_boost_checks'] = array( 'label' => __( 'Jetpack Boost checks', 'jetpack-boost' ), 'test' => array( __CLASS__, 'do_checks' ), ); return $checks; } /** * Do site-health page checks * * @access public * @return array */ public static function do_checks() { $health = new Boost_Health(); $total_issues = $health->get_total_issues(); $issues = $health->get_all_issues(); /** * Default, no issues found */ $result = array( 'label' => __( 'No issues found', 'jetpack-boost' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance', 'jetpack-boost' ), 'color' => 'gray', ), 'description' => sprintf( '<p>%s</p>', __( 'Jetpack Boost did not find any known performance issues with your site.', 'jetpack-boost' ) ), 'actions' => '', 'test' => 'jetpack_boost_checks', ); /** * If issues found. */ if ( $total_issues ) { $result['status'] = 'critical'; /* translators: $d is the number of performance issues found. */ $result['label'] = sprintf( _n( 'Your site is affected by %d performance issue', 'Your site is affected by %d performance issues', $total_issues, 'jetpack-boost' ), $total_issues ); $result['description'] = __( 'Jetpack Boost detected the following performance issues with your site:', 'jetpack-boost' ); foreach ( $issues as $issue ) { $result['description'] .= '<p>'; $result['description'] .= "<span class='dashicons dashicons-warning' style='color: crimson;'></span> &nbsp"; $result['description'] .= wp_kses( $issue, array( 'a' => array( 'href' => array() ) ) ); // Only allow a href HTML tags. $result['description'] .= '</p>'; } $result['description'] .= '<p>'; $result['description'] .= sprintf( wp_kses( /* translators: Link to Jetpack Boost. */ __( 'Visit <a href="%s">Boost settings page</a> for more information.', 'jetpack-boost' ), array( 'a' => array( 'href' => array() ), ) ), esc_url( admin_url( 'admin.php?page=jetpack-boost' ) ) ); $result['description'] .= '</p>'; } return $result; } }
projects/plugins/boost/app/lib/class-storage-post-type.php
<?php /** * Cache for Jetpack Boost that uses CPTs to store the data. * * @link https://automattic.com * @since 1.0.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib; /** * Class Storage_Post_type */ class Storage_Post_Type { /** * The name. * * @var string */ private $name; /** * Storage_Post_type constructor. * * @param string $name The name. */ public function __construct( $name ) { $this->name = sanitize_title( $name ); $this->init(); } /** * Get the post type slug. */ public function post_type_slug() { return 'jb_store_' . $this->name; } /** * Static initialization. */ private function init() { // Check if post type already registered. if ( post_type_exists( $this->post_type_slug() ) ) { return; } register_post_type( $this->post_type_slug(), array( 'description' => 'Cache entries for the Jetpack Boost plugin.', 'public' => false, 'show_in_rest' => true, 'rewrite' => false, 'can_export' => false, 'delete_with_user' => false, ) ); } /** * Sets the cache entry using a CPT. * * @param string $key Cache key name. * @param mixed $value Cache value. * @param int $expiry Cache expiration in seconds. * * @return void */ public function set( $key, $value, $expiry = 0 ) { $data_post_data = array( 'post_type' => $this->post_type_slug(), 'post_title' => $key, 'post_name' => $key, 'post_status' => 'publish', ); $data_post = $this->get_post_by_name( $key ); $expiry_timestamp = 0; if ( $expiry ) { $expiry_timestamp = time() + $expiry; } $value = array( 'data' => $value, 'expiry' => $expiry_timestamp, ); $data_post_data['post_content'] = base64_encode( maybe_serialize( $value ) ); // phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode // Update an existing data post if we have one or create a new one. if ( $data_post ) { $data_post_data['ID'] = $data_post->ID; wp_update_post( $data_post_data ); } else { wp_insert_post( $data_post_data ); } } /** * Gets a cache entry using a CPT. * * @param string $key Cache key name. * @param mixed $default Default value. * * @return mixed */ public function get( $key, $default ) { $cached = wp_cache_get( $key, $this->post_type_slug() ); if ( $cached ) { return $cached; } $data_post = $this->get_post_by_name( $key ); if ( ! $data_post ) { return $default; } /** * Array( * 'data' => mixed, * 'expiry' => int, * ) */ // phpcs:disable $value = maybe_unserialize( base64_decode( $data_post->post_content ) ); // phpcs:enable if ( isset( $value['expiry'] ) && intval( $value['expiry'] ) > 0 ) { if ( time() > intval( $value['expiry'] ) ) { // The cache entry expired. Clear it. $this->delete( $key ); return $default; } } if ( ! isset( $value['data'] ) ) { return $default; } wp_cache_set( $key, $value['data'], $this->post_type_slug(), HOUR_IN_SECONDS ); return $value['data']; } /** * Delete a cache entry from a CPT. * * @param string $key Cache key name. * * @return void */ public function delete( $key ) { $data_post = $this->get_post_by_name( $key ); // Delete the post. if ( $data_post ) { wp_delete_post( $data_post->ID, true ); } } /** * Returns a single WP post based on the `post_name` property. * * Note: `post_name` is indexed in the DB. * * @see https://codex.wordpress.org/Database_Description#Indexes_6 * * @param string $post_name Post name. * * @return bool|\WP_Post */ public function get_post_by_name( $post_name ) { $post_query = new \WP_Query( array( 'name' => $post_name, 'post_type' => $this->post_type_slug(), 'post_status' => 'publish', 'posts_per_page' => 1, 'ignore_sticky_posts' => true, 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ) ); if ( ! $post_query->have_posts() ) { return false; } if ( ! $post_query->posts[0] instanceof \WP_Post ) { return false; } return $post_query->posts[0]; } /** * Clear all data stored in post types. On systems which support it, this * will use wp_cache_flush_group and a db query to efficiently flush the * cache. Otherwise, it will fall back to deleting each item. */ public function clear() { if ( function_exists( 'wp_cache_flush_group' ) && function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_group' ) ) { $this->clear_bulk(); } else { $this->clear_manually(); } } /** * Clear all data stored in post types using wp_cache_flush_group and a db * query. This is more efficient than deleting each item individually. * Make sure that wp_cache_supports( 'flush_group' ) returns true before * calling this method. */ private function clear_bulk() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->delete( $wpdb->posts, array( 'post_type' => $this->post_type_slug() ), array( '%s' ) ); wp_cache_flush_group( $this->post_type_slug() ); } /** * Clear all data stored in post types by deleting each item individually. * This is less efficient than using wp_cache_flush_group and a db query, * but works on all systems. */ private function clear_manually() { $posts = get_posts( array( 'post_type' => $this->post_type_slug(), 'posts_per_page' => -1, ) ); foreach ( $posts as $post ) { wp_delete_post( $post->ID, true ); wp_cache_delete( $post->post_name, $this->post_type_slug() ); } } }
projects/plugins/boost/app/lib/class-collection.php
<?php namespace Automattic\Jetpack_Boost\Lib; /** * A collection of WordPress options that's stored as a single ar */ class Collection { private $key; /** * Collections imply that they may carry more data than regular options, * This might unnecessarily slow down sites. * Disable autoloading by default. * * @see autoload() to enable autoloading. */ private $autoload = false; /** * @param string $key Collection key. */ public function __construct( $key ) { $this->key = $key; } /* * Allow autoloading collections */ public function autoload() { $this->autoload = true; return $this; } /** * Get the whole collection * * @return array */ public function get() { $result = get_option( $this->key, array() ); if ( is_array( $result ) ) { return $result; } return array(); } /** * Append a single item to the collection * * @param $item * * @return bool */ public function append( $item ) { $items = $this->get(); if ( ! in_array( $item, $items, true ) ) { $items[] = $item; return update_option( $this->key, $items, $this->autoload ); } return false; } /** * Delete the whole collection * * @return bool */ public function delete() { return delete_option( $this->key ); } }
projects/plugins/boost/app/lib/minify/functions-helpers.php
<?php use Automattic\Jetpack_Boost\Lib\Minify\Config; use Automattic\Jetpack_Boost\Lib\Minify\Dependency_Path_Mapping; /** * Get an extra cache key for requests. We can manually bump this when we want * to ensure a new version of Jetpack Boost never reuses old cached URLs. */ function jetpack_boost_minify_cache_buster() { return 1; } /** * Cleanup the given cache folder, removing all files older than $file_age seconds. * * @param string $cache_folder The path to the cache folder to cleanup. * @param int $file_age The age of files to purge, in seconds. */ function jetpack_boost_page_optimize_cache_cleanup( $cache_folder = false, $file_age = DAY_IN_SECONDS ) { if ( ! is_dir( $cache_folder ) ) { return; } $defined_cache_dir = Config::get_cache_dir_path(); // If cache is disabled when the cleanup runs, purge it $using_cache = ! empty( $defined_cache_dir ); if ( ! $using_cache ) { $file_age = 0; } // If the cache folder changed since queueing, purge it if ( $using_cache && $cache_folder !== $defined_cache_dir ) { $file_age = 0; } // Grab all files in the cache directory $cache_files = glob( $cache_folder . '/page-optimize-cache-*' ); // Cleanup all files older than $file_age foreach ( $cache_files as $cache_file ) { if ( ! is_file( $cache_file ) ) { continue; } if ( ( time() - $file_age ) > filemtime( $cache_file ) ) { wp_delete_file( $cache_file ); } } } /** * Plugin deactivation hook - unschedule cronjobs and purge cache. */ function jetpack_boost_page_optimize_deactivate() { $cache_folder = Config::get_cache_dir_path(); jetpack_boost_page_optimize_cache_cleanup( $cache_folder, 0 /* max file age in seconds */ ); wp_clear_scheduled_hook( 'jetpack_boost_minify_cron_cache_cleanup', array( $cache_folder ) ); } /** * Plugin uninstall hook - cleanup options. */ function jetpack_boost_page_optimize_uninstall() { // Run cleanup on uninstall. You can uninstall an active plugin w/o deactivation. jetpack_boost_page_optimize_deactivate(); // JS delete_option( 'page_optimize-js' ); delete_option( 'page_optimize-load-mode' ); delete_option( 'page_optimize-js-exclude' ); // CSS delete_option( 'page_optimize-css' ); delete_option( 'page_optimize-css-exclude' ); } /** * Convert enqueued home-relative URLs to absolute ones. * * Enqueued script URLs which start with / are relative to WordPress' home URL. * i.e.: "/wp-includes/x.js" should be "WP_HOME/wp-includes/x.js". * * Note: this method uses home_url, so should only be used plugin-side when * generating concatenated URLs. */ function jetpack_boost_enqueued_to_absolute_url( $url ) { if ( str_starts_with( $url, '/' ) ) { return home_url( $url ); } return $url; } /** * Get the list of JS slugs to exclude from minification. */ function jetpack_boost_page_optimize_js_exclude_list() { return jetpack_boost_ds_get( 'minify_js_excludes' ); } /** * Get the list of CSS slugs to exclude from minification. */ function jetpack_boost_page_optimize_css_exclude_list() { return jetpack_boost_ds_get( 'minify_css_excludes' ); } /** * Determines whether a string starts with another string. */ function jetpack_boost_page_optimize_starts_with( $prefix, $str ) { $prefix_length = strlen( $prefix ); if ( strlen( $str ) < $prefix_length ) { return false; } return substr( $str, 0, $prefix_length ) === $prefix; } /** * Answers whether the plugin should provide concat resource URIs * that are relative to a common ancestor directory. Assuming a common ancestor * allows us to skip resolving resource URIs to filesystem paths later on. */ function jetpack_boost_page_optimize_use_concat_base_dir() { return defined( 'PAGE_OPTIMIZE_CONCAT_BASE_DIR' ) && file_exists( PAGE_OPTIMIZE_CONCAT_BASE_DIR ); } /** * Get a filesystem path relative to a configured base path for resources * that will be concatenated. Assuming a common ancestor allows us to skip * resolving resource URIs to filesystem paths later on. */ function jetpack_boost_page_optimize_remove_concat_base_prefix( $original_fs_path ) { $abspath = Config::get_abspath(); // Always check longer path first if ( strlen( $abspath ) > strlen( PAGE_OPTIMIZE_CONCAT_BASE_DIR ) ) { $longer_path = $abspath; $shorter_path = PAGE_OPTIMIZE_CONCAT_BASE_DIR; } else { $longer_path = PAGE_OPTIMIZE_CONCAT_BASE_DIR; $shorter_path = $abspath; } $prefix_abspath = trailingslashit( $longer_path ); if ( jetpack_boost_page_optimize_starts_with( $prefix_abspath, $original_fs_path ) ) { return substr( $original_fs_path, strlen( $prefix_abspath ) ); } $prefix_basedir = trailingslashit( $shorter_path ); if ( jetpack_boost_page_optimize_starts_with( $prefix_basedir, $original_fs_path ) ) { return substr( $original_fs_path, strlen( $prefix_basedir ) ); } // If we end up here, this is a resource we shouldn't have tried to concat in the first place return '/page-optimize-resource-outside-base-path/' . basename( $original_fs_path ); } /** * Schedule a cronjob for cache cleanup, if one isn't already scheduled. */ function jetpack_boost_page_optimize_schedule_cache_cleanup() { $cache_folder = Config::get_cache_dir_path(); $args = array( $cache_folder ); // If caching is on, and job isn't queued for current cache folder if ( false !== $cache_folder && false === wp_next_scheduled( 'jetpack_boost_minify_cron_cache_cleanup', $args ) ) { wp_schedule_event( time(), 'daily', 'jetpack_boost_minify_cron_cache_cleanup', $args ); } } /** * Check whether it's safe to minify for the duration of this HTTP request. Checks * for things like page-builder editors, etc. * * @return bool True if we don't want to minify/concatenate CSS/JS for this request. */ function jetpack_boost_page_optimize_bail() { static $should_bail = null; if ( null !== $should_bail ) { return $should_bail; } $should_bail = false; // Bail if this is an admin page if ( is_admin() ) { $should_bail = true; return true; } // Bail if we're in customizer global $wp_customize; if ( isset( $wp_customize ) ) { $should_bail = true; return true; } // Bail if Divi theme is active, and we're in the Divi Front End Builder // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( ! empty( $_GET['et_fb'] ) && 'Divi' === wp_get_theme()->get_template() ) { $should_bail = true; return true; } // Bail if we're editing pages in Brizy Editor // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( class_exists( 'Brizy_Editor' ) && method_exists( 'Brizy_Editor', 'prefix' ) && ( isset( $_GET[ Brizy_Editor::prefix( '-edit-iframe' ) ] ) || isset( $_GET[ Brizy_Editor::prefix( '-edit' ) ] ) ) ) { $should_bail = true; return true; } return $should_bail; } /** * Return a URL with a cache-busting query string based on the file's mtime. */ function jetpack_boost_page_optimize_cache_bust_mtime( $path, $siteurl ) { static $dependency_path_mapping; // Absolute paths should dump the path component of siteurl. if ( str_starts_with( $path, '/' ) ) { $parts = wp_parse_url( $siteurl ); $siteurl = $parts['scheme'] . '://' . $parts['host']; } $url = $siteurl . $path; if ( strpos( $url, '?m=' ) ) { return $url; } $parts = wp_parse_url( $url ); if ( ! isset( $parts['path'] ) || empty( $parts['path'] ) ) { return $url; } if ( empty( $dependency_path_mapping ) ) { $dependency_path_mapping = new Dependency_Path_Mapping(); } $file = $dependency_path_mapping->dependency_src_to_fs_path( $url ); $mtime = false; if ( file_exists( $file ) ) { $mtime = filemtime( $file ); } if ( ! $mtime ) { return $url; } if ( ! str_contains( $url, '?' ) ) { $q = ''; } else { list( $url, $q ) = explode( '?', $url, 2 ); if ( strlen( $q ) ) { $q = '&amp;' . $q; } } return "$url?m={$mtime}{$q}"; } /** * Get the URL prefix for static minify/concat resources. Defaults to /jb_static/, but can be * overridden by defining JETPACK_BOOST_STATIC_PREFIX. */ function jetpack_boost_get_static_prefix() { $prefix = defined( 'JETPACK_BOOST_STATIC_PREFIX' ) ? JETPACK_BOOST_STATIC_PREFIX : '/_jb_static/'; if ( ! str_starts_with( $prefix, '/' ) ) { $prefix = '/' . $prefix; } return trailingslashit( $prefix ); } /** * Detects requests within the `/_jb_static/` directory, and serves minified content. * * @return void */ function jetpack_boost_minify_serve_concatenated() { // Potential improvement: Make concat URL dir configurable // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized if ( isset( $_SERVER['REQUEST_URI'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized $request_path = explode( '?', wp_unslash( $_SERVER['REQUEST_URI'] ) )[0]; $prefix = jetpack_boost_get_static_prefix(); if ( $prefix === substr( $request_path, -strlen( $prefix ), strlen( $prefix ) ) ) { require_once __DIR__ . '/functions-service.php'; jetpack_boost_page_optimize_service_request(); exit; } } } /** * Handles cache service initialization, scheduling of cache cleanup, and disabling of * Jetpack photon-cdn for static JS/CSS. Automatically ensures that we don't setup * the cache service more than once per request. * * @return void */ function jetpack_boost_minify_setup() { static $setup_done = false; if ( $setup_done ) { return; } $setup_done = true; // Hook up deactivation and uninstall cleanup paths. register_deactivation_hook( JETPACK_BOOST_PATH, 'jetpack_boost_page_optimize_deactivate' ); register_uninstall_hook( JETPACK_BOOST_PATH, 'jetpack_boost_page_optimize_uninstall' ); // Schedule cache cleanup. add_action( 'jetpack_boost_minify_cron_cache_cleanup', 'jetpack_boost_page_optimize_cache_cleanup' ); jetpack_boost_page_optimize_schedule_cache_cleanup(); if ( ! jetpack_boost_page_optimize_bail() ) { // Disable Jetpack Site Accelerator CDN for static JS/CSS, if we're minifying this page. add_filter( 'jetpack_force_disable_site_accelerator', '__return_true' ); } }
projects/plugins/boost/app/lib/minify/Concatenate_CSS.php
<?php namespace Automattic\Jetpack_Boost\Lib\Minify; use WP_Styles; // Disable complaints about enqueuing stylesheets, as this class alters the way enqueuing them works. // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet /** * Replacement for, and subclass of WP_Styles - used to control the way that styles are enqueued and output. */ class Concatenate_CSS extends WP_Styles { private $dependency_path_mapping; private $old_styles; public $allow_gzip_compression; public function __construct( $styles ) { if ( empty( $styles ) || ! ( $styles instanceof WP_Styles ) ) { $this->old_styles = new WP_Styles(); } else { $this->old_styles = $styles; } // Unset all the object properties except our private copy of the styles object. // We have to unset everything so that the overload methods talk to $this->old_styles->whatever // instead of $this->whatever. foreach ( array_keys( get_object_vars( $this ) ) as $key ) { if ( 'old_styles' === $key ) { continue; } unset( $this->$key ); } $this->dependency_path_mapping = new Dependency_Path_Mapping( apply_filters( 'page_optimize_site_url', $this->base_url ) ); } public function do_items( $handles = false, $group = false ) { $handles = false === $handles ? $this->queue : (array) $handles; $stylesheets = array(); $siteurl = apply_filters( 'page_optimize_site_url', $this->base_url ); $this->all_deps( $handles ); $stylesheet_group_index = 0; // Merge CSS into a single file $concat_group = 'concat'; // Concat group on top (first array element gets processed earlier) $stylesheets[ $concat_group ] = array(); foreach ( $this->to_do as $key => $handle ) { $obj = $this->registered[ $handle ]; $obj->src = apply_filters( 'style_loader_src', $obj->src, $obj->handle ); // Core is kind of broken and returns "true" for src of "colors" handle // http://core.trac.wordpress.org/attachment/ticket/16827/colors-hacked-fixed.diff // http://core.trac.wordpress.org/ticket/20729 $css_url = $obj->src; if ( 'colors' === $obj->handle && true === $css_url ) { $css_url = wp_style_loader_src( $css_url, $obj->handle ); } $css_url = jetpack_boost_enqueued_to_absolute_url( $css_url ); $css_url_parsed = wp_parse_url( $css_url ); $extra = $obj->extra; // Don't concat by default $do_concat = false; // Only try to concat static css files if ( str_contains( $css_url_parsed['path'], '.css' ) ) { $do_concat = true; } elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat CSS %s => Maybe Not Static File %s -->\n", esc_html( $handle ), esc_html( $obj->src ) ); } // Don't try to concat styles which are loaded conditionally (like IE stuff) if ( isset( $extra['conditional'] ) ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat CSS %s => Has Conditional -->\n", esc_html( $handle ) ); } $do_concat = false; } // Don't concat rtl stuff for now until concat supports it correctly if ( $do_concat && 'rtl' === $this->text_direction && ! empty( $extra['rtl'] ) ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat CSS %s => Is RTL -->\n", esc_html( $handle ) ); } $do_concat = false; } // Don't try to concat externally hosted scripts $is_internal_uri = $this->dependency_path_mapping->is_internal_uri( $css_url ); if ( $do_concat && ! $is_internal_uri ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat CSS %s => External URL: %s -->\n", esc_html( $handle ), esc_url( $css_url ) ); } $do_concat = false; } if ( $do_concat ) { // Resolve paths and concat styles that exist in the filesystem $css_realpath = $this->dependency_path_mapping->dependency_src_to_fs_path( $css_url ); if ( false === $css_realpath ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat CSS %s => Invalid Path %s -->\n", esc_html( $handle ), esc_html( $css_realpath ) ); } $do_concat = false; } } // Skip concating CSS from exclusion list $exclude_list = jetpack_boost_page_optimize_css_exclude_list(); foreach ( $exclude_list as $exclude ) { if ( $do_concat && $handle === $exclude ) { $do_concat = false; if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat CSS %s => Excluded option -->\n", esc_html( $handle ) ); } } } // Allow plugins to disable concatenation of certain stylesheets. if ( $do_concat && ! apply_filters( 'css_do_concat', $do_concat, $handle ) ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat CSS %s => Filtered `false` -->\n", esc_html( $handle ) ); } } $do_concat = apply_filters( 'css_do_concat', $do_concat, $handle ); if ( true === $do_concat ) { $media = $obj->args; if ( empty( $media ) ) { $media = 'all'; } $stylesheets[ $concat_group ][ $media ][ $handle ] = $css_url_parsed['path']; $this->done[] = $handle; } else { ++$stylesheet_group_index; $stylesheets[ $stylesheet_group_index ]['noconcat'][] = $handle; ++$stylesheet_group_index; } unset( $this->to_do[ $key ] ); } foreach ( $stylesheets as $_idx => $stylesheets_group ) { foreach ( $stylesheets_group as $media => $css ) { if ( 'noconcat' === $media ) { foreach ( $css as $handle ) { if ( $this->do_item( $handle, $group ) ) { $this->done[] = $handle; } } continue; } elseif ( count( $css ) > 1 ) { $fs_paths = array(); foreach ( $css as $css_uri_path ) { $fs_paths[] = $this->dependency_path_mapping->uri_path_to_fs_path( $css_uri_path ); } $mtime = max( array_map( 'filemtime', $fs_paths ) ); if ( jetpack_boost_page_optimize_use_concat_base_dir() ) { $path_str = implode( ',', array_map( 'jetpack_boost_page_optimize_remove_concat_base_prefix', $fs_paths ) ); } else { $path_str = implode( ',', $css ); } $path_str = "$path_str?m=$mtime&cb=" . jetpack_boost_minify_cache_buster(); if ( $this->allow_gzip_compression ) { // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode $path_64 = base64_encode( gzcompress( $path_str ) ); if ( strlen( $path_str ) > ( strlen( $path_64 ) + 1 ) ) { $path_str = '-' . $path_64; } } $href = $siteurl . jetpack_boost_get_static_prefix() . '??' . $path_str; } else { $href = jetpack_boost_page_optimize_cache_bust_mtime( current( $css ), $siteurl ); } $handles = array_keys( $css ); $css_id = sanitize_title_with_dashes( $media ) . '-css-' . md5( $href ); if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { $style_tag = "<link data-handles='" . esc_attr( implode( ',', $handles ) ) . "' rel='stylesheet' id='$css_id' href='$href' type='text/css' media='$media' />"; } else { $style_tag = "<link rel='stylesheet' id='$css_id' href='$href' type='text/css' media='$media' />"; } $style_tag = apply_filters( 'page_optimize_style_loader_tag', $style_tag, $handles, $href, $media ); // Allow manipulation of the stylesheet tag. // For example - making it deferred when using with Critical CSS. $style_tag = apply_filters( 'style_loader_tag', $style_tag, implode( ',', $handles ), $href, $media ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo $style_tag . "\n"; array_map( array( $this, 'print_inline_style' ), array_keys( $css ) ); } } return $this->done; } public function __isset( $key ) { return isset( $this->old_styles->$key ); } public function __unset( $key ) { unset( $this->old_styles->$key ); } public function &__get( $key ) { return $this->old_styles->$key; } public function __set( $key, $value ) { $this->old_styles->$key = $value; } }
projects/plugins/boost/app/lib/minify/Config.php
<?php namespace Automattic\Jetpack_Boost\Lib\Minify; class Config { public static function get_cache_dir_path() { if ( defined( 'PAGE_OPTIMIZE_CACHE_DIR' ) ) { if ( empty( PAGE_OPTIMIZE_CACHE_DIR ) ) { $path = false; } else { $path = PAGE_OPTIMIZE_CACHE_DIR; } } else { $path = WP_CONTENT_DIR . '/cache/page_optimize'; } return $path; } public static function get_abspath() { if ( defined( 'PAGE_OPTIMIZE_ABSPATH' ) ) { $path = PAGE_OPTIMIZE_ABSPATH; } else { $path = ABSPATH; } return $path; } }
projects/plugins/boost/app/lib/minify/functions-service.php
<?php use Automattic\Jetpack_Boost\Lib\Minify; use Automattic\Jetpack_Boost\Lib\Minify\Config; use Automattic\Jetpack_Boost\Lib\Minify\Dependency_Path_Mapping; use Automattic\Jetpack_Boost\Lib\Minify\Utils; function jetpack_boost_page_optimize_types() { return array( 'css' => 'text/css', 'js' => 'application/javascript', ); } /** * Handle serving a minified / concatenated file from the virtual _jb_static dir. */ function jetpack_boost_page_optimize_service_request() { $use_wp = defined( 'JETPACK_BOOST_CONCAT_USE_WP' ) && JETPACK_BOOST_CONCAT_USE_WP; $utils = new Utils( $use_wp ); $cache_dir = Config::get_cache_dir_path(); $use_cache = ! empty( $cache_dir ); // We handle the cache here, tell other caches not to. if ( ! defined( 'DONOTCACHEPAGE' ) ) { define( 'DONOTCACHEPAGE', true ); } // Ensure the cache directory exists. // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir if ( $use_cache && ! is_dir( $cache_dir ) && ! mkdir( $cache_dir, 0775, true ) ) { $use_cache = false; if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log( sprintf( /* translators: a filesystem path to a directory */ __( "Disabling page-optimize cache. Unable to create cache directory '%s'.", 'jetpack-boost' ), $cache_dir ) ); } } // Ensure the cache directory is writable. // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable if ( $use_cache && ( ! is_dir( $cache_dir ) || ! is_writable( $cache_dir ) || ! is_executable( $cache_dir ) ) ) { $use_cache = false; if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log( sprintf( /* translators: a filesystem path to a directory */ __( "Disabling page-optimize cache. Unable to write to cache directory '%s'.", 'jetpack-boost' ), $cache_dir ) ); } } if ( $use_cache ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? $utils->unslash( $_SERVER['REQUEST_URI'] ) : ''; $request_uri_hash = md5( $request_uri ); $cache_file = $cache_dir . "/page-optimize-cache-$request_uri_hash"; $cache_file_meta = $cache_dir . "/page-optimize-cache-meta-$request_uri_hash"; // Serve an existing file. if ( file_exists( $cache_file ) ) { if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash if ( strtotime( $utils->unslash( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) < filemtime( $cache_file ) ) { header( 'HTTP/1.1 304 Not Modified' ); exit; } } if ( file_exists( $cache_file_meta ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents $meta = json_decode( file_get_contents( $cache_file_meta ), ARRAY_A ); if ( ! empty( $meta ) && ! empty( $meta['headers'] ) ) { foreach ( $meta['headers'] as $header ) { header( $header ); } } } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents $etag = '"' . md5( file_get_contents( $cache_file ) ) . '"'; header( 'X-Page-Optimize: cached' ); header( 'Cache-Control: max-age=' . 31536000 ); header( 'ETag: ' . $etag ); echo file_get_contents( $cache_file ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped, WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- We need to trust this unfortunately. die(); } } // Existing file not available; generate new content. $output = jetpack_boost_page_optimize_build_output(); $content = $output['content']; $headers = $output['headers']; foreach ( $headers as $header ) { header( $header ); } header( 'X-Page-Optimize: uncached' ); header( 'Cache-Control: max-age=' . 31536000 ); header( 'ETag: "' . md5( $content ) . '"' ); echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- We need to trust this unfortunately. // Cache the generated data, if available. if ( $use_cache ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents file_put_contents( $cache_file, $content ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents file_put_contents( $cache_file_meta, wp_json_encode( array( 'headers' => $headers ) ) ); } die(); } /** * Strip matching parent paths off a string. Returns $path without $parent_path. */ function jetpack_boost_strip_parent_path( $parent_path, $path ) { $trimmed_parent = ltrim( $parent_path, '/' ); $trimmed_path = ltrim( $path, '/' ); if ( substr( $trimmed_path, 0, strlen( $trimmed_parent ) === $trimmed_parent ) ) { $trimmed_path = substr( $trimmed_path, strlen( $trimmed_parent ) ); } return str_starts_with( $trimmed_path, '/' ) ? $trimmed_path : '/' . $trimmed_path; } /** * Generate a combined and minified output for the current request. This is run regardless of the * type of content being fetched; JavaScript or CSS, so it must handle either. */ function jetpack_boost_page_optimize_build_output() { $use_wp = defined( 'JETPACK_BOOST_CONCAT_USE_WP' ) && JETPACK_BOOST_CONCAT_USE_WP; $utils = new Utils( $use_wp ); $jetpack_boost_page_optimize_types = jetpack_boost_page_optimize_types(); // Config $concat_max_files = 150; $concat_unique = true; // Main // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash $method = isset( $_SERVER['REQUEST_METHOD'] ) ? $utils->unslash( $_SERVER['REQUEST_METHOD'] ) : 'GET'; if ( ! in_array( $method, array( 'GET', 'HEAD' ), true ) ) { jetpack_boost_page_optimize_status_exit( 400 ); } // Ensure the path follows one of these forms: // /_jb_static/??/foo/bar.css,/foo1/bar/baz.css?m=293847g // -- or -- // /_jb_static/??-eJzTT8vP109KLNJLLi7W0QdyDEE8IK4CiVjn2hpZGluYmKcDABRMDPM= // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? $utils->unslash( $_SERVER['REQUEST_URI'] ) : ''; $args = $utils->parse_url( $request_uri, PHP_URL_QUERY ); if ( ! $args || ! str_contains( $args, '?' ) ) { jetpack_boost_page_optimize_status_exit( 400 ); } $args = substr( $args, strpos( $args, '?' ) + 1 ); // Detect paths with - in their filename - this implies a base64 encoded gzipped string for the file list. // e.g.: /_jb_static/??-eJzTT8vP109KLNJLLi7W0QdyDEE8IK4CiVjn2hpZGluYmKcDABRMDPM= if ( '-' === $args[0] ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode $args = @gzuncompress( base64_decode( substr( $args, 1 ) ) ); // Invalid data, abort! if ( false === $args ) { jetpack_boost_page_optimize_status_exit( 400 ); } } // Handle comma separated list of files. e.g.: // /foo/bar.css,/foo1/bar/baz.css?m=293847g $version_string_pos = strpos( $args, '?' ); if ( false !== $version_string_pos ) { $args = substr( $args, 0, $version_string_pos ); } // /foo/bar.css,/foo1/bar/baz.css $args = explode( ',', $args ); if ( ! $args ) { jetpack_boost_page_optimize_status_exit( 400 ); } // args contain something like array( '/foo/bar.css', '/foo1/bar/baz.css' ) if ( 0 === count( $args ) || count( $args ) > $concat_max_files ) { jetpack_boost_page_optimize_status_exit( 400 ); } // If we're in a subdirectory context, use that as the root. // We can't assume that the root serves the same content as the subdir. $subdir_path_prefix = ''; $request_path = $utils->parse_url( $request_uri, PHP_URL_PATH ); $_static_index = strpos( $request_path, jetpack_boost_get_static_prefix() ); if ( $_static_index > 0 ) { $subdir_path_prefix = substr( $request_path, 0, $_static_index ); } unset( $request_path, $_static_index ); $last_modified = 0; $pre_output = ''; $output = ''; foreach ( $args as $uri ) { $fullpath = jetpack_boost_page_optimize_get_path( $uri ); if ( ! file_exists( $fullpath ) ) { jetpack_boost_page_optimize_status_exit( 404 ); } $mime_type = jetpack_boost_page_optimize_get_mime_type( $fullpath ); if ( ! in_array( $mime_type, $jetpack_boost_page_optimize_types, true ) ) { jetpack_boost_page_optimize_status_exit( 400 ); } if ( $concat_unique ) { if ( ! isset( $last_mime_type ) ) { $last_mime_type = $mime_type; } if ( $last_mime_type !== $mime_type ) { jetpack_boost_page_optimize_status_exit( 400 ); } } $stat = stat( $fullpath ); if ( false === $stat ) { jetpack_boost_page_optimize_status_exit( 500 ); } if ( $stat['mtime'] > $last_modified ) { $last_modified = $stat['mtime']; } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents $buf = file_get_contents( $fullpath ); if ( false === $buf ) { jetpack_boost_page_optimize_status_exit( 500 ); } if ( 'text/css' === $mime_type ) { $dirpath = jetpack_boost_strip_parent_path( $subdir_path_prefix, dirname( $uri ) ); // url(relative/path/to/file) -> url(/absolute/and/not/relative/path/to/file) $buf = jetpack_boost_page_optimize_relative_path_replace( $buf, $dirpath ); // phpcs:ignore Squiz.PHP.CommentedOutCode.Found // This regex changes things like AlphaImageLoader(...src='relative/path/to/file'...) to AlphaImageLoader(...src='/absolute/path/to/file'...) $buf = preg_replace( '/(Microsoft.AlphaImageLoader\s*\([^\)]*src=(?:\'|")?)([^\/\'"\s\)](?:(?<!http:|https:).)*)\)/isU', '$1' . ( $dirpath === '/' ? '/' : $dirpath . '/' ) . '$2)', $buf ); // The @charset rules must be on top of the output if ( str_starts_with( $buf, '@charset' ) ) { preg_replace_callback( '/(?P<charset_rule>@charset\s+[\'"][^\'"]+[\'"];)/i', function ( $match ) use ( &$pre_output ) { if ( str_starts_with( $pre_output, '@charset' ) ) { return ''; } $pre_output = $match[0] . "\n" . $pre_output; return ''; }, $buf ); } // Move the @import rules on top of the concatenated output. // Only @charset rule are allowed before them. if ( str_contains( $buf, '@import' ) ) { $buf = preg_replace_callback( '/(?P<pre_path>@import\s+(?:url\s*\()?[\'"\s]*)(?P<path>[^\'"\s](?:https?:\/\/.+\/?)?.+?)(?P<post_path>[\'"\s\)]*;)/i', function ( $match ) use ( $dirpath, &$pre_output ) { if ( ! str_starts_with( $match['path'], 'http' ) && '/' !== $match['path'][0] ) { $pre_output .= $match['pre_path'] . ( $dirpath === '/' ? '/' : $dirpath . '/' ) . $match['path'] . $match['post_path'] . "\n"; } else { $pre_output .= $match[0] . "\n"; } return ''; }, $buf ); } // Minify CSS. $buf = Minify::css( $buf ); $output .= "$buf"; } else { // Minify JS $buf = Minify::js( $buf ); $output .= "$buf;\n"; } } // Don't let trailing whitespace ruin everyone's day. Seems to get stripped by batcache // resulting in ns_error_net_partial_transfer errors. $output = rtrim( $output ); $headers = array( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', $last_modified ) . ' GMT', "Content-Type: $mime_type", ); return array( 'headers' => $headers, 'content' => $pre_output . $output, ); } function jetpack_boost_page_optimize_status_exit( $status ) { http_response_code( $status ); exit; } function jetpack_boost_page_optimize_get_mime_type( $file ) { $jetpack_boost_page_optimize_types = jetpack_boost_page_optimize_types(); $lastdot_pos = strrpos( $file, '.' ); if ( false === $lastdot_pos ) { return false; } $ext = substr( $file, $lastdot_pos + 1 ); return isset( $jetpack_boost_page_optimize_types[ $ext ] ) ? $jetpack_boost_page_optimize_types[ $ext ] : false; } function jetpack_boost_page_optimize_relative_path_replace( $buf, $dirpath ) { // url(relative/path/to/file) -> url(/absolute/and/not/relative/path/to/file) $buf = preg_replace( '/(:?\s*url\s*\()\s*(?:\'|")?\s*([^\/\'"\s\)](?:(?<!data:|http:|https:|[\(\'"]#|%23).)*)[\'"\s]*\)/isU', '$1' . ( $dirpath === '/' ? '/' : $dirpath . '/' ) . '$2)', $buf ); return $buf; } function jetpack_boost_page_optimize_get_path( $uri ) { static $dependency_path_mapping; if ( ! strlen( $uri ) ) { jetpack_boost_page_optimize_status_exit( 400 ); } if ( str_contains( $uri, '..' ) || str_contains( $uri, "\0" ) ) { jetpack_boost_page_optimize_status_exit( 400 ); } if ( defined( 'PAGE_OPTIMIZE_CONCAT_BASE_DIR' ) ) { $path = realpath( PAGE_OPTIMIZE_CONCAT_BASE_DIR . "/$uri" ); if ( false === $path ) { $path = realpath( Config::get_abspath() . "/$uri" ); } } else { if ( empty( $dependency_path_mapping ) ) { $dependency_path_mapping = new Dependency_Path_Mapping(); } $path = $dependency_path_mapping->uri_path_to_fs_path( $uri ); } if ( false === $path ) { jetpack_boost_page_optimize_status_exit( 404 ); } return $path; }
projects/plugins/boost/app/lib/minify/Concatenate_JS.php
<?php namespace Automattic\Jetpack_Boost\Lib\Minify; use WP_Scripts; // Disable complaints about enqueuing scripts, as this class alters the way enqueuing them works. // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedScript /** * Replacement for, and subclass of WP_Scripts - used to control the way that scripts are enqueued and output. */ class Concatenate_JS extends WP_Scripts { private $dependency_path_mapping; private $old_scripts; public $allow_gzip_compression; public function __construct( $scripts ) { if ( empty( $scripts ) || ! ( $scripts instanceof WP_Scripts ) ) { $this->old_scripts = new WP_Scripts(); } else { $this->old_scripts = $scripts; } // Unset all the object properties except our private copy of the scripts object. // We have to unset everything so that the overload methods talk to $this->old_scripts->whatever // instead of $this->whatever. foreach ( array_keys( get_object_vars( $this ) ) as $key ) { if ( 'old_scripts' === $key ) { continue; } unset( $this->$key ); } $this->dependency_path_mapping = new Dependency_Path_Mapping( apply_filters( 'page_optimize_site_url', $this->base_url ) ); } protected function has_inline_content( $handle ) { $before_output = $this->get_data( $handle, 'before' ); if ( ! empty( $before_output ) ) { return true; } $after_output = $this->get_data( $handle, 'after' ); if ( ! empty( $after_output ) ) { return true; } // JavaScript translations $has_translations = ! empty( $this->registered[ $handle ]->textdomain ); if ( $has_translations ) { return true; } return false; } /** * Override for WP_Scripts::do_item() - this is the method that actually outputs the scripts. */ public function do_items( $handles = false, $group = false ) { $handles = false === $handles ? $this->queue : (array) $handles; $javascripts = array(); $siteurl = apply_filters( 'page_optimize_site_url', $this->base_url ); $this->all_deps( $handles ); $level = 0; $using_strict = false; foreach ( $this->to_do as $key => $handle ) { $script_is_strict = false; if ( in_array( $handle, $this->done, true ) || ! isset( $this->registered[ $handle ] ) ) { continue; } if ( 0 === $group && $this->groups[ $handle ] > 0 ) { $this->in_footer[] = $handle; unset( $this->to_do[ $key ] ); continue; } if ( ! $this->registered[ $handle ]->src ) { // Defines a group. if ( $this->has_inline_content( $handle ) ) { ++$level; $javascripts[ $level ]['type'] = 'do_item'; $javascripts[ $level ]['handle'] = $handle; ++$level; unset( $this->to_do[ $key ] ); } else { // if there are localized items, echo them $this->print_extra_script( $handle ); $this->done[] = $handle; } continue; } if ( false === $group && in_array( $handle, $this->in_footer, true ) ) { $this->in_footer = array_diff( $this->in_footer, (array) $handle ); } $obj = $this->registered[ $handle ]; $js_url = jetpack_boost_enqueued_to_absolute_url( $obj->src ); $js_url_parsed = wp_parse_url( $js_url ); // Don't concat by default $do_concat = false; // Only try to concat static js files if ( str_contains( $js_url_parsed['path'], '.js' ) ) { // Previously, the value of this variable was determined by a function. // Now, since concatenation is always enabled when the module is active, // the value will always be true for static files. $do_concat = true; } elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat JS %s => Maybe Not Static File %s -->\n", esc_html( $handle ), esc_html( $obj->src ) ); } // Don't try to concat externally hosted scripts $is_internal_uri = $this->dependency_path_mapping->is_internal_uri( $js_url ); if ( $do_concat && ! $is_internal_uri ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat JS %s => External URL: %s -->\n", esc_html( $handle ), esc_url( $js_url ) ); } $do_concat = false; } if ( $do_concat ) { // Resolve paths and concat scripts that exist in the filesystem $js_realpath = $this->dependency_path_mapping->dependency_src_to_fs_path( $js_url ); if ( false === $js_realpath ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat JS %s => Invalid Path %s -->\n", esc_html( $handle ), esc_html( $js_realpath ) ); } $do_concat = false; } } if ( $do_concat && $this->has_inline_content( $handle ) ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat JS %s => Has Inline Content -->\n", esc_html( $handle ) ); } $do_concat = false; } // Skip core scripts that use Strict Mode if ( $do_concat && ( 'react' === $handle || 'react-dom' === $handle ) ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat JS %s => Has Strict Mode (Core) -->\n", esc_html( $handle ) ); } $do_concat = false; $script_is_strict = true; // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents } elseif ( $do_concat && preg_match_all( '/^[\',"]use strict[\',"];/Uims', file_get_contents( $js_realpath ), $matches ) ) { // Skip third-party scripts that use Strict Mode if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat JS %s => Has Strict Mode (Third-Party) -->\n", esc_html( $handle ) ); } $do_concat = false; $script_is_strict = true; } else { $script_is_strict = false; } // Skip concating scripts from exclusion list $exclude_list = jetpack_boost_page_optimize_js_exclude_list(); foreach ( $exclude_list as $exclude ) { if ( $do_concat && $handle === $exclude ) { $do_concat = false; if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat JS %s => Excluded option -->\n", esc_html( $handle ) ); } } } // Allow plugins to disable concatenation of certain scripts. if ( $do_concat && ! apply_filters( 'js_do_concat', $do_concat, $handle ) ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { printf( "\n<!-- No Concat JS %s => Filtered `false` -->\n", esc_html( $handle ) ); } } $do_concat = apply_filters( 'js_do_concat', $do_concat, $handle ); if ( true === $do_concat ) { if ( ! isset( $javascripts[ $level ] ) ) { $javascripts[ $level ]['type'] = 'concat'; } $javascripts[ $level ]['paths'][] = $js_url_parsed['path']; $javascripts[ $level ]['handles'][] = $handle; } else { ++$level; $javascripts[ $level ]['type'] = 'do_item'; $javascripts[ $level ]['handle'] = $handle; ++$level; } unset( $this->to_do[ $key ] ); if ( $using_strict !== $script_is_strict ) { if ( $script_is_strict ) { $using_strict = true; $strict_count = 0; } else { $using_strict = false; } } if ( $script_is_strict ) { ++$strict_count; } } if ( empty( $javascripts ) ) { return $this->done; } foreach ( $javascripts as $js_array ) { if ( 'do_item' === $js_array['type'] ) { if ( $this->do_item( $js_array['handle'], $group ) ) { $this->done[] = $js_array['handle']; } } elseif ( 'concat' === $js_array['type'] ) { array_map( array( $this, 'print_extra_script' ), $js_array['handles'] ); if ( isset( $js_array['paths'] ) && count( $js_array['paths'] ) > 1 ) { $fs_paths = array(); foreach ( $js_array['paths'] as $js_url ) { $fs_paths[] = $this->dependency_path_mapping->uri_path_to_fs_path( $js_url ); } $mtime = max( array_map( 'filemtime', $fs_paths ) ); if ( jetpack_boost_page_optimize_use_concat_base_dir() ) { $path_str = implode( ',', array_map( 'jetpack_boost_page_optimize_remove_concat_base_prefix', $fs_paths ) ); } else { $path_str = implode( ',', $js_array['paths'] ); } $path_str = "$path_str?m=$mtime&cb=" . jetpack_boost_minify_cache_buster(); if ( $this->allow_gzip_compression ) { // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode $path_64 = base64_encode( gzcompress( $path_str ) ); if ( strlen( $path_str ) > ( strlen( $path_64 ) + 1 ) ) { $path_str = '-' . $path_64; } } $href = $siteurl . jetpack_boost_get_static_prefix() . '??' . $path_str; } elseif ( isset( $js_array['paths'] ) && is_array( $js_array['paths'] ) ) { $href = jetpack_boost_page_optimize_cache_bust_mtime( $js_array['paths'][0], $siteurl ); } $this->done = array_merge( $this->done, $js_array['handles'] ); // Print before/after scripts from wp_inline_scripts() and concatenated script tag if ( isset( $js_array['extras']['before'] ) ) { foreach ( $js_array['extras']['before'] as $inline_before ) { // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo $inline_before; } } if ( isset( $href ) ) { $handles = implode( ',', $js_array['handles'] ); if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { $tag = "<script data-handles='" . esc_attr( $handles ) . "' type='text/javascript' src='" . esc_url( $href ) . "'></script>\n"; } else { $tag = "<script type='text/javascript' src='" . esc_url( $href ) . "'></script>\n"; } if ( is_array( $js_array['handles'] ) && count( $js_array['handles'] ) === 1 ) { // Because we have a single script, let's apply the `script_loader_tag` filter as core does in `do_item()`. // That way, we interfere less with plugin and theme script filtering. For example, without this filter, // there is a case where we block the TwentyTwenty theme from adding async/defer attributes. // https://github.com/Automattic/page-optimize/pull/44 $tag = apply_filters( 'script_loader_tag', $tag, $js_array['handles'][0], $href ); } // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo $tag; } if ( isset( $js_array['extras']['after'] ) ) { foreach ( $js_array['extras']['after'] as $inline_after ) { // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo $inline_after; } } } } do_action( 'js_concat_did_items', $javascripts ); return $this->done; } public function __isset( $key ) { return isset( $this->old_scripts->$key ); } public function __unset( $key ) { unset( $this->old_scripts->$key ); } public function &__get( $key ) { return $this->old_scripts->$key; } public function __set( $key, $value ) { $this->old_scripts->$key = $value; } }
projects/plugins/boost/app/lib/minify/Utils.php
<?php namespace Automattic\Jetpack_Boost\Lib\Minify; class Utils { /** * Indicates whether to use the WordPress functions. * * @var bool $use_wp Whether to use WordPress functions. */ private $use_wp; /** * Utils constructor. * * @param bool $use_wp Whether to use WordPress functions. Default is true. */ public function __construct( $use_wp = true ) { $this->use_wp = $use_wp; } /** * Encodes a value to JSON. * * @param mixed $value The value to encode. * * @return string The JSON-encoded string. */ public function json_encode( $value ) { if ( $this->use_wp ) { return wp_json_encode( $value ); } // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode return json_encode( $value ); } /** * Removes slashes from a string or an array of strings. * * @param mixed $value The string or array of strings to remove slashes from. * * @return mixed The string or array of strings with slashes removed. */ public function unslash( $value ) { if ( $this->use_wp ) { return wp_unslash( $value ); } return is_string( $value ) ? stripslashes( $value ) : $value; } /** * Parses a URL and returns its components. * * @param string $url The URL to parse. * @param int $component Optional. The specific component to retrieve. * Use one of the PHP_URL_* constants. Default is -1 (all components). * * @return mixed|array|string|null The parsed URL component(s), or the entire URL string if $component is -1. */ public function parse_url( $url, $component = -1 ) { if ( $this->use_wp ) { return wp_parse_url( $url, $component ); } // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url return parse_url( $url, $component ); } }
projects/plugins/boost/app/lib/minify/Dependency_Path_Mapping.php
<?php namespace Automattic\Jetpack_Boost\Lib\Minify; /** * This is a class to map script and style URLs to local filesystem paths. * This is necessary when we are deciding what we can concatenate and when * actually building the concatenation. */ class Dependency_Path_Mapping { // Save entire site URL so we can check whether other URLs are based on it (internal URLs) public $site_url; // Save URI path and dir for mapping URIs to filesystem paths public $site_uri_path = null; public $site_dir = null; public $content_uri_path = null; public $content_dir = null; public $plugin_uri_path = null; public $plugin_dir = null; public function __construct( // Expose URLs and DIRs for unit test $site_url = null, // default site URL is determined dynamically $site_dir = null, $content_url = WP_CONTENT_URL, $content_dir = WP_CONTENT_DIR, $plugin_url = WP_PLUGIN_URL, $plugin_dir = WP_PLUGIN_DIR ) { if ( null === $site_dir ) { $site_dir = Config::get_abspath(); } if ( null === $site_url ) { $site_url = is_multisite() ? get_site_url( get_current_blog_id() ) : get_site_url(); } $site_url = trailingslashit( $site_url ); $this->site_url = $site_url; $this->site_uri_path = wp_parse_url( $site_url, PHP_URL_PATH ); $this->site_dir = trailingslashit( $site_dir ); // Only resolve content URLs if they are under the site URL if ( $this->is_internal_uri( $content_url ) ) { $this->content_uri_path = wp_parse_url( trailingslashit( $content_url ), PHP_URL_PATH ); $this->content_dir = trailingslashit( $content_dir ); } // Only resolve plugin URLs if they are under the site URL if ( $this->is_internal_uri( $plugin_url ) ) { $this->plugin_uri_path = wp_parse_url( trailingslashit( $plugin_url ), PHP_URL_PATH ); $this->plugin_dir = trailingslashit( $plugin_dir ); } } /** * Given the full URL of a script/style dependency, return its local filesystem path. */ public function dependency_src_to_fs_path( $src ) { if ( ! $this->is_internal_uri( $src ) ) { // If a URI is not internal, we can have no confidence // we are resolving to the correct file. return false; } $src_parts = wp_parse_url( $src ); if ( false === $src_parts ) { return false; } if ( empty( $src_parts['path'] ) ) { // We can't find anything to resolve return false; } $path = $src_parts['path']; if ( empty( $src_parts['host'] ) ) { // With no host, this is a path relative to the WordPress root $fs_path = "{$this->site_dir}{$path}"; return file_exists( $fs_path ) ? $fs_path : false; } return $this->uri_path_to_fs_path( $path ); } /** * Given a URI path of a script/style resource, return its local filesystem path. */ public function uri_path_to_fs_path( $uri_path ) { if ( 1 === preg_match( '#(?:^|/)\.\.?(?:/|$)#', $uri_path ) ) { // Reject relative paths return false; } // The plugin URI path may be contained within the content URI path, so we check it before the content URI. // And both the plugin and content URI paths must be contained within the site URI path, // so we check them before checking the site URI. if ( isset( $this->plugin_uri_path ) && static::is_descendant_uri( $this->plugin_uri_path, $uri_path ) ) { $file_path = $this->plugin_dir . substr( $uri_path, strlen( $this->plugin_uri_path ) ); } elseif ( isset( $this->content_uri_path ) && static::is_descendant_uri( $this->content_uri_path, $uri_path ) ) { $file_path = $this->content_dir . substr( $uri_path, strlen( $this->content_uri_path ) ); } elseif ( static::is_descendant_uri( $this->site_uri_path, $uri_path ) ) { $file_path = $this->site_dir . substr( $uri_path, strlen( $this->site_uri_path ) ); } if ( isset( $file_path ) && file_exists( $file_path ) ) { return $file_path; } else { return false; } } /** * Determine whether a URI is internal, contained by this site. * * This method helps ensure we only resolve to local FS paths. */ public function is_internal_uri( $uri ) { if ( jetpack_boost_page_optimize_starts_with( '/', $uri ) && ! jetpack_boost_page_optimize_starts_with( '//', $uri ) ) { // Absolute paths are internal because they are based on the site dir (typically ABSPATH), // and this looks like an absolute path. return true; } // To be internal, a URL must have the same scheme, host, and port as the site URL // and start with the same path as the site URL. return static::is_descendant_uri( $this->site_url, $uri ); } /** * Check whether a path is descended from the given directory path. * * Does not handle relative paths. */ public static function is_descendant_uri( $dir_path, $candidate ) { // Ensure a trailing slash to avoid false matches like // "/wp-content/resource" being judged a descendant of "/wp". $dir_path = trailingslashit( $dir_path ); return jetpack_boost_page_optimize_starts_with( $dir_path, $candidate ); } }
projects/plugins/boost/app/lib/critical-css/Display_Critical_CSS.php
<?php /** * Class that's responsible for rendering * Critical CSS on the site front-end. */ namespace Automattic\Jetpack_Boost\Lib\Critical_CSS; class Display_Critical_CSS { /** * @var string The Critical CSS to display. */ protected $css; /** * @param $css */ public function __construct( $css ) { $this->css = $css; } /** * Converts existing screen CSS to be asynchronously loaded. * * @param string $html The link tag for the enqueued style. * @param string $handle The style's registered handle. * @param string $href The stylesheet's source URL. * @param string $media The stylesheet's media attribute. * * @return string * @see style_loader_tag */ public function asynchronize_stylesheets( $html, $handle, $href, $media ) { // If there is no critical CSS, do not alter the stylesheet loading. if ( false === $this->css ) { return $html; } $available_methods = array( 'async' => 'media="not all" data-media="' . $media . '" onload="this.media=this.dataset.media; delete this.dataset.media; this.removeAttribute( \'onload\' );"', 'deferred' => 'media="not all" data-media="' . $media . '"', ); /** * Loading method for stylesheets. * * Filter the loading method for each stylesheet for the screen with following values: * async - Stylesheets are loaded asynchronously. * Styles are applied once the stylesheet is loaded completely without render blocking. * deferred - Loading of stylesheets are deferred until the window load event. * Styles from all the stylesheets are applied at once after the page load. * * Stylesheet loading behaviour is not altered for any other value such as false or 'default'. * Stylesheet loading is instant and the process blocks the page rendering. * Eg: add_filter( 'jetpack_boost_async_style', '__return_false' ); * * @param string $handle The style's registered handle. * @param string $media The stylesheet's media attribute. * * @see onload_flip_stylesheets for how stylesheets loading is deferred. * * @todo Retrieve settings from database, either via auto-configuration or UI option. */ $method = apply_filters( 'jetpack_boost_async_style', 'async', $handle, $media ); // If the loading method is not allowed, do not alter the stylesheet loading. if ( ! isset( $available_methods[ $method ] ) ) { return $html; } $html_no_script = '<noscript>' . $html . '</noscript>'; // Update the stylesheet markup for allowed methods. $html = preg_replace( '~media=(\'[^\']+\')|("[^"]+")~', $available_methods[ $method ], $html ); // Append to the HTML stylesheet tag the same untouched HTML stylesheet tag within the noscript tag // to support the rendering of the stylesheet when JavaScript is disabled. return $html_no_script . $html; } /** * Prints the critical CSS to the page. */ public function display_critical_css() { $critical_css = $this->css; if ( false === $critical_css ) { // phpcs:ignore Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound -- This is not a PHP 4 constructor, that only applies to non-namespaced classes. return false; } echo '<style id="jetpack-boost-critical-css">'; // Ensure no </style> tag (or any HTML tags) in output. // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo wp_strip_all_tags( $critical_css ); echo '</style>'; } /** * Add a small piece of JavaScript to the footer, which on load flips all * linked stylesheets from media="not all" to "all", and switches the * Critical CSS <style> block to media="not all" to deactivate it. */ public function onload_flip_stylesheets() { /* Unminified version of footer script. ?> <script> window.addEventListener( 'load', function() { // Flip all media="not all" links to media="all". document.querySelectorAll( 'link' ).forEach( function( link ) { if ( link.media === 'not all' && link.dataset.media ) { link.media = link.dataset.media; delete link.dataset.media; } } ); // Turn off Critical CSS style block with media="not all". var element = document.getElementById( 'jetpack-boost-critical-css' ); if ( element ) { element.media = 'not all'; } } ); </script> <?php */ // Minified version of footer script. See above comment for unminified version. ?> <script>window.addEventListener( 'load', function() { document.querySelectorAll( 'link' ).forEach( function( e ) {'not all' === e.media && e.dataset.media && ( e.media = e.dataset.media, delete e.dataset.media );} ); var e = document.getElementById( 'jetpack-boost-critical-css' ); e && ( e.media = 'not all' ); } );</script> <?php } }
projects/plugins/boost/app/lib/critical-css/Critical_CSS_State.php
<?php namespace Automattic\Jetpack_Boost\Lib\Critical_CSS; class Critical_CSS_State { const GENERATION_STATES = array( 'not_generated' => 'not_generated', 'pending' => 'pending', 'generated' => 'generated', 'error' => 'error', ); const PROVIDER_STATES = array( 'pending' => 'pending', 'success' => 'success', 'error' => 'error', ); public $state; public function __construct() { $this->state = jetpack_boost_ds_get( 'critical_css_state' ); } public function clear() { jetpack_boost_ds_delete( 'critical_css_state' ); } public function save() { $this->state['updated'] = microtime( true ); jetpack_boost_ds_set( 'critical_css_state', $this->state ); } public function set_error( $message ) { if ( empty( $message ) ) { error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log 'Critical CSS: set_error() called with empty message' ); return $this; } $this->state['status_error'] = $message; $this->state['status'] = self::GENERATION_STATES['error']; return $this; } public function set_provider_error_dismissed( $provider_key, $dismissed ) { if ( empty( $this->state['providers'] ) ) { return new \WP_Error( 'invalid_provider_key', 'No providers exist' ); } $provider_index = array_search( $provider_key, array_column( $this->state['providers'], 'key' ), true ); if ( $provider_index === false ) { return new \WP_Error( 'invalid_provider_key', 'Invalid provider key' ); } $this->state['providers'][ $provider_index ]['error_status'] = $dismissed ? 'dismissed' : 'active'; return true; } /** * Update a provider's state. The provider must already exist in the state to be updated. * * @param string $provider_key The provider key. * @param array $state An array to overlay over the current state. * @return bool|WP_Error True on success, WP_Error on failure. */ private function update_provider_state( $provider_key, $state ) { if ( empty( $this->state['providers'] ) ) { return new \WP_Error( 'invalid_provider_key', 'No providers exist' ); } $provider_index = array_search( $provider_key, array_column( $this->state['providers'], 'key' ), true ); if ( $provider_index === false ) { return new \WP_Error( 'invalid_provider_key', 'Invalid provider key' ); } $this->state['providers'][ $provider_index ] = array_merge( $this->state['providers'][ $provider_index ], $state ); $this->maybe_set_generated(); return true; } /** * Set a provider's state to error. * * @param string $provider_key The provider key. * @param array $errors A list of errors to store with this provider. * @return bool|WP_Error True on success, WP_Error on failure. */ public function set_provider_errors( $provider_key, $errors ) { return $this->update_provider_state( $provider_key, array( 'status' => self::PROVIDER_STATES['error'], 'errors' => $errors, ) ); } /** * Set a provider's state to success. * * @param string $provider_key The provider key. * @return bool|WP_Error True on success, WP_Error on failure. */ public function set_provider_success( $provider_key ) { return $this->update_provider_state( $provider_key, array( 'status' => self::PROVIDER_STATES['success'], ) ); } /** * Set the state to generated if all providers are done. Should be called wherever * a provider's state is updated. */ private function maybe_set_generated() { if ( empty( $this->state['providers'] ) ) { return; } $provider_states = array_column( $this->state['providers'], 'status' ); $is_done = ! in_array( self::GENERATION_STATES['pending'], $provider_states, true ); if ( $is_done ) { $this->state['status'] = self::GENERATION_STATES['generated']; do_action( 'jetpack_boost_critical_css_generated' ); } } public function has_errors() { // Check if any of the providers have errors as well. $any_provider_has_error = in_array( 'error', array_unique( wp_list_pluck( $this->state['providers'], 'status' ) ), true ); return self::GENERATION_STATES['error'] === $this->state['status'] || $any_provider_has_error; } public function get_error_message() { return isset( $this->state['status_error'] ) ? $this->state['status_error'] : null; } public function is_requesting() { return self::GENERATION_STATES['pending'] === $this->state['status']; } public function prepare_request() { $this->state = array( 'status' => self::GENERATION_STATES['pending'], 'providers' => array(), 'created' => microtime( true ), 'updated' => microtime( true ), ); return $this; } public function set_pending_providers( $providers ) { foreach ( $providers as $key => $provider ) { $providers[ $key ]['status'] = self::PROVIDER_STATES['pending']; } $this->state['providers'] = $providers; return $this; } /** * Get fresh state */ public function get() { $this->state = jetpack_boost_ds_get( 'critical_css_state' ); return $this->state; } public function has_pending_provider( $needles = array() ) { if ( empty( $this->state['providers'] ) ) { return false; } $providers = $this->state['providers']; foreach ( $providers as $provider ) { if ( ! empty( $provider['key'] ) && ! empty( $provider['status'] ) && self::PROVIDER_STATES['pending'] === $provider['status'] && in_array( $provider['key'], $needles, true ) ) { return true; } } return false; } }
projects/plugins/boost/app/lib/critical-css/Critical_CSS_Storage.php
<?php /** * Critical CSS storage. * * @link https://automattic.com * @since 1.0.0 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib\Critical_CSS; use Automattic\Jetpack_Boost\Lib\Storage_Post_Type; /** * Critical CSS Storage class */ class Critical_CSS_Storage { /** * Storage post type. * * @var Storage_Post_Type */ protected $storage; /** * Critical_CSS_Storage constructor. */ public function __construct() { $this->storage = new Storage_Post_Type( 'css' ); } /** * Store Critical CSS for a specific provider. * * @param string $key Provider key. * @param string $value Critical CSS. */ public function store_css( $key, $value ) { $this->storage->set( $key, array( 'css' => $value, ) ); } /** * Clear the whole Critical CSS storage. */ public function clear() { $this->storage->clear(); } /** * Get Critical CSS for specific provider keys. * * @param array $provider_keys Provider keys. * * @return array|false */ public function get_css( $provider_keys ) { foreach ( $provider_keys as $key ) { $data = $this->storage->get( $key, false ); if ( $data && $data['css'] ) { return array( 'key' => $key, 'css' => $data['css'], ); } } return false; } }
projects/plugins/boost/app/lib/critical-css/Regenerate.php
<?php namespace Automattic\Jetpack_Boost\Lib\Critical_CSS; use Automattic\Jetpack_Boost\Admin\Regenerate_Admin_Notice; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Source_Providers; use Automattic\Jetpack_Boost\Modules\Modules_Setup; use Automattic\Jetpack_Boost\Modules\Optimizations\Cloud_CSS\Cloud_CSS; use Automattic\Jetpack_Boost\Modules\Optimizations\Cloud_CSS\Cloud_CSS_Followup; class Regenerate { /** @var Critical_CSS_State */ private $state; public function is_cloud_css() { $optimizations = ( new Modules_Setup() )->get_status(); return isset( $optimizations[ Cloud_CSS::get_slug() ] ) && $optimizations[ Cloud_CSS::get_slug() ]; } public function start() { // Get Critical CSS Source URLs $source_providers = new Source_Providers(); $providers = $source_providers->get_provider_sources(); // Store those URLs in the Critical CSS State $this->state = new Critical_CSS_State(); $this->state->prepare_request() ->set_pending_providers( $providers ) ->save(); // Get the data $data = $this->state->get(); if ( $this->is_cloud_css() ) { // If this is a cloud CSS request, we need to trigger the generation // of the CSS and return the URL to the CSS file. $cloud_css = new Cloud_CSS(); $cloud_css->regenerate_cloud_css(); Cloud_CSS_Followup::schedule(); } // Clear previous Critical CSS From storage $storage = new Critical_CSS_Storage(); $storage->clear(); // Dismiss admin notices Regenerate_Admin_Notice::dismiss(); jetpack_boost_ds_delete( 'critical_css_suggest_regenerate', null ); return $data; } public function get_state() { return $this->state; } }
projects/plugins/boost/app/lib/critical-css/Admin_Bar_Compatibilty.php
<?php namespace Automattic\Jetpack_Boost\Lib\Critical_CSS; class Admin_Bar_Compatibility { /** * Enforces the admin bar stylesheet to load late and synchronously * when the admin bar is present on the page. */ public static function init() { // Force the Admin Bar to render in the footer. remove_action( 'wp_body_open', 'wp_admin_bar_render', '0' ); add_filter( 'jetpack_boost_async_style', array( __CLASS__, 'enable_asynchronous_admin_bar' ), 10, 2 ); add_action( 'wp_before_admin_bar_render', array( __CLASS__, 'force_admin_bar_stylesheet' ) ); add_action( 'wp_head', array( __CLASS__, 'dequeue_admin_bar' ), 0 ); } /** * Load the admin bar CSS synchronously. * * @param bool $is_async Whether admin bar is async. * @param string $handle Asset handle. * * @return bool */ public static function enable_asynchronous_admin_bar( $is_async, $handle ) { if ( 'admin-bar' === $handle ) { $is_async = false; } return $is_async; } /** * Dequeue the admin bar stylesheet, so that it's not printed early. * * @see wp_head */ public static function dequeue_admin_bar() { wp_dequeue_style( 'admin-bar' ); } /** * Force the admin bar stylesheet to print right before the admin bar markup. * * @see wp_before_admin_bar_render */ public static function force_admin_bar_stylesheet() { wp_print_styles( 'admin-bar' ); } }
projects/plugins/boost/app/lib/critical-css/Critical_CSS_Invalidator.php
<?php /** * Critical CSS Invalidator * * Reset critical CSS when existing critical css values are stale. */ namespace Automattic\Jetpack_Boost\Lib\Critical_CSS; use Automattic\Jetpack_Boost\Lib\Boost_Health; use Automattic\Jetpack_Boost\Modules\Optimizations\Cloud_CSS\Cloud_CSS_Followup; /** * Handler for invalidating Critical CSS; both Cloud and Local. Watches relevant * hooks and clears data when necessary. Also sends out its own action * (after_critical_css_invalidate) so that the Cloud or Local implementations of * Critical CSS can respond to the invalidation. */ class Critical_CSS_Invalidator { /** * Register hooks. */ public static function init() { add_action( 'jetpack_boost_deactivate', array( __CLASS__, 'clear_data' ) ); add_action( 'handle_environment_change', array( __CLASS__, 'handle_environment_change' ) ); add_filter( 'jetpack_boost_total_problem_count', array( __CLASS__, 'update_boost_problem_count' ) ); } /** * Clear Critical CSS data. */ public static function clear_data() { $storage = new Critical_CSS_Storage(); $storage->clear(); $state = new Critical_CSS_State(); $state->clear(); do_action( 'jetpack_boost_critical_css_invalidated' ); Cloud_CSS_Followup::unschedule(); } /** * Respond to environment changes; deciding whether or not to clear Critical CSS data. */ public static function handle_environment_change( $is_major_change ) { if ( $is_major_change ) { self::clear_data(); } } public static function update_boost_problem_count( $count ) { $css_needs_regeneration = Boost_Health::critical_css_needs_regeneration(); if ( $css_needs_regeneration ) { ++$count; } return $count; } }
projects/plugins/boost/app/lib/critical-css/Generator.php
<?php namespace Automattic\Jetpack_Boost\Lib\Critical_CSS; use Automattic\Jetpack_Boost\Modules\Optimizations\Critical_CSS\CSS_Proxy; class Generator { const GENERATE_QUERY_ACTION = 'jb-generate-critical-css'; public static function init() { $generator = new static(); if ( static::is_generating_critical_css() ) { add_action( 'wp_head', array( $generator, 'display_generate_meta' ), 0 ); $generator->force_logged_out_render(); } } /** * Force the current page to render as viewed by a logged out user. Useful when generating * Critical CSS. */ private function force_logged_out_render() { $current_user_id = get_current_user_id(); if ( 0 !== $current_user_id ) { // Force current user to 0 to ensure page is rendered as a non-logged-in user. wp_set_current_user( 0 ); // Turn off display of admin bar. add_filter( 'show_admin_bar', '__return_false', PHP_INT_MAX ); } } /** * Return true if page is loaded to generate critical CSS * * phpcs:disable WordPress.Security.NonceVerification.Recommended */ public static function is_generating_critical_css() { return isset( $_GET[ self::GENERATE_QUERY_ACTION ] ); } /** * Get a Critical CSS status block, adding in local generation nonces (if applicable). * i.e.: Call this method to supply enough Critical CSS status to kick off local generation, * such as in response to a request-generate API call or during page initialization. */ public function get_generation_metadata() { $status = array(); // Add a user-bound nonce to use when proxying CSS for Critical CSS generation. $status['proxy_nonce'] = wp_create_nonce( CSS_Proxy::NONCE_ACTION ); return $status; } /** * Renders a <meta> tag used to verify this is a valid page to generate Critical CSS with. */ public function display_generate_meta() { ?> <meta name="<?php echo esc_attr( self::GENERATE_QUERY_ACTION ); ?>" content="true"/> <?php } /** * Add the critical css generation flag to a list if it's present in the URL. * This is mainly used by filters for compatibility. * * @var $query_args array The list to add the arg to. * * @return $query_args array The updatest list with query args. */ public static function add_generate_query_action_to_list( $query_args ) { // phpcs:disable WordPress.Security.NonceVerification.Recommended if ( isset( $_GET[ self::GENERATE_QUERY_ACTION ] ) ) { $query_args[] = self::GENERATE_QUERY_ACTION; } return $query_args; } }
projects/plugins/boost/app/lib/critical-css/data-sync-actions/Set_Provider_Error_Dismissed.php
<?php namespace Automattic\Jetpack_Boost\Lib\Critical_CSS\Data_Sync_Actions; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Data_Sync_Action; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State; /** * Critical CSS Action: Update whether or not to show a provider which is in an error state. */ class Set_Provider_Error_Dismissed implements Data_Sync_Action { /** * Handles the action logic. * * @param mixed $data JSON Data passed to the action. * @param \WP_REST_Request $_request The request object. */ public function handle( $data, $_request ) { $state = new Critical_CSS_State(); foreach ( $data as $item ) { if ( empty( $item['key'] ) ) { return array( 'success' => false, 'state' => $state->get(), 'error' => 'Invalid data', ); } $provider_key = sanitize_key( $item['key'] ); $dismissed = ! empty( $item['dismissed'] ); $state->set_provider_error_dismissed( $provider_key, $dismissed ); } $state->save(); return array( 'success' => true, 'state' => $state->get(), ); } }
projects/plugins/boost/app/lib/critical-css/data-sync-actions/Set_Provider_CSS.php
<?php namespace Automattic\Jetpack_Boost\Lib\Critical_CSS\Data_Sync_Actions; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Data_Sync_Action; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_Storage; /** * Critical CSS Action: Set CSS for a provider. */ class Set_Provider_CSS implements Data_Sync_Action { /** * Handles the action logic. * * @param mixed $data JSON Data passed to the action. * @param \WP_REST_Request $_request The request object. */ public function handle( $data, $_request ) { $state = new Critical_CSS_State(); if ( empty( $data['key'] ) || empty( $data['css'] ) ) { return array( 'success' => false, 'state' => $state->get(), 'error' => 'Invalid data', ); } $provider_key = sanitize_key( $data['key'] ); $css = $data['css']; $storage = new Critical_CSS_Storage(); $storage->store_css( $provider_key, $css ); $state->set_provider_success( $provider_key ); $state->save(); return array( 'success' => true, 'state' => $state->get(), ); } }
projects/plugins/boost/app/lib/critical-css/data-sync-actions/Regenerate_CSS.php
<?php namespace Automattic\Jetpack_Boost\Lib\Critical_CSS\Data_Sync_Actions; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Data_Sync_Action; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Regenerate; /** * Critical CSS Action: request regeneration. */ class Regenerate_CSS implements Data_Sync_Action { /** * Handles the action logic. * * @param mixed $_data JSON Data passed to the action. * @param \WP_REST_Request $_request The request object. */ public function handle( $_data, $_request ) { $regenerate = new Regenerate(); $regenerate->start(); $state = $regenerate->get_state(); return array( 'success' => ! $state->has_errors(), 'state' => $state->get(), 'errors' => $state->get_error_message(), ); } }
projects/plugins/boost/app/lib/critical-css/data-sync-actions/Set_Provider_Errors.php
<?php namespace Automattic\Jetpack_Boost\Lib\Critical_CSS\Data_Sync_Actions; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Data_Sync_Action; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State; /** * Critical CSS Action: Store errors for a provider. */ class Set_Provider_Errors implements Data_Sync_Action { /** * Handles the action logic. * * @param mixed $data JSON Data passed to the action. * @param \WP_REST_Request $_request The request object. */ public function handle( $data, $_request ) { $state = new Critical_CSS_State(); if ( empty( $data['key'] ) || empty( $data['errors'] ) ) { return array( 'success' => false, 'state' => $state->get(), 'error' => 'Invalid data', ); } $provider_key = sanitize_key( $data['key'] ); $errors = $data['errors']; $state->set_provider_errors( $provider_key, $errors ); $state->save(); return array( 'success' => true, 'state' => $state->get(), ); } }
projects/plugins/boost/app/lib/critical-css/source-providers/Source_Providers.php
<?php namespace Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_Storage; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Providers\Archive_Provider; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Providers\Post_ID_Provider; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Providers\Provider; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Providers\Singular_Post_Provider; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Providers\Taxonomy_Provider; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Providers\WP_Core_Provider; class Source_Providers { /** * Variable used to cache the CSS string during the page request. * This is here because `get_critical_css` is called multiple * times in `style_loader_tag` hook (on each CSS file). * * @var null|false|string */ protected $request_cached_css; /** * Stores the Critical CSS key used for rendering the current page if any. * * @var null|string */ protected $current_critical_css_key; /** * List of all the Critical CSS Types. * * The order is important because searching for critical CSS will stop as soon as a value is found. * So finding Critical CSS by post ID is attempted before searching for a common Singular Post critical CSS. * * @var Provider[] */ protected $providers = array( Post_ID_Provider::class, WP_Core_Provider::class, Singular_Post_Provider::class, Archive_Provider::class, Taxonomy_Provider::class, ); public function get_providers() { return $this->providers; } /** * Returns the Provider which controls a given key. */ public function get_provider_for_key( $key ) { foreach ( $this->providers as $provider ) { if ( $provider::owns_key( $key ) ) { return $provider; } } return null; } /** * Get all critical CSS storage keys that are available for the current request. * Caches the result. * * @return array */ public function get_current_request_css_keys() { static $keys = null; if ( null !== $keys ) { return $keys; } $keys = array(); foreach ( $this->providers as $provider ) { $provider_keys = $provider::get_current_storage_keys(); if ( empty( $provider_keys ) ) { continue; } $keys = array_merge( $keys, $provider_keys ); } return $keys; } /** * Get critical CSS for the current request. * * @return string|false */ public function get_current_request_css() { if ( null !== $this->request_cached_css ) { return $this->request_cached_css; } $storage = new Critical_CSS_Storage(); $data = $storage->get_css( $this->get_current_request_css_keys() ); if ( false === $data ) { return false; } $this->request_cached_css = $data['css']; $this->current_critical_css_key = $data['key']; return $this->request_cached_css; } /** * Get providers sources. * * @param array $providers Providers. * * @return array */ public function get_provider_sources() { $sources = array(); foreach ( $this->get_providers() as $provider ) { $provider_name = $provider::get_provider_name(); // For each provider, // Gather a list of URLs that are going to be used as Critical CSS source. foreach ( $provider::get_critical_source_urls() as $group => $urls ) { $key = $provider_name . '_' . $group; // For each URL // Track the state and errors in a state array. $sources[] = array( 'key' => $key, 'label' => $provider::describe_key( $key ), 'urls' => apply_filters( 'jetpack_boost_critical_css_urls', $urls ), 'success_ratio' => $provider::get_success_ratio(), ); } } return $sources; } }
projects/plugins/boost/app/lib/critical-css/source-providers/providers/Taxonomy_Provider.php
<?php /** * Provides taxonomy support for critical CSS * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Providers; /** * Class Taxonomy_Provider * * @package Automattic\Jetpack_Boost\Modules\Critical_CSS\Providers */ class Taxonomy_Provider extends Provider { /** * Provider name. * * @var string */ protected static $name = 'taxonomy'; /** * Max number of posts to query. * * @var integer */ const MAX_URLS = 20; /** * Minimum number of posts to have Critical CSS generated in order for the whole process to be successful. * * @var integer */ const MIN_SUCCESS_URLS = 10; // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_critical_source_urls( $context_posts = array() ) { $results = array(); $taxonomies = self::get_available_taxonomies(); if ( ! empty( $context_posts ) ) { $context_post_types = array_unique( wp_list_pluck( $context_posts, 'post_type' ) ); $context_taxonomies = get_object_taxonomies( $context_post_types, 'names' ); $taxonomies = array_intersect( $taxonomies, $context_taxonomies ); } foreach ( $taxonomies as $taxonomy ) { $terms = self::get_terms( $taxonomy ); if ( ! $terms ) { continue; } foreach ( $terms as $term ) { $results[ $taxonomy ][] = get_term_link( $term, $taxonomy ); } } return $results; } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_current_storage_keys() { if ( ! is_category() && ! is_tax() ) { return array(); } // For example: "taxonomy_category". return array( self::$name . '_' . get_queried_object()->taxonomy ); } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_keys() { return array_keys( array_filter( self::get_available_taxonomies(), function ( $taxonomy ) { return ! empty( Taxonomy_Provider::get_terms( $taxonomy ) ); } ) ); } // phpcs:ignore /** @inheritdoc */ public static function describe_key( $provider_key ) { // phpcs:ignore Generic.Commenting.DocComment.MissingShort $taxonomy = substr( $provider_key, strlen( static::$name ) + 1 ); switch ( $taxonomy ) { case 'category': return __( 'Category view', 'jetpack-boost' ); default: return __( 'View for custom taxonomy', 'jetpack-boost' ); } } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_edit_url( $_provider_key ) { // phpcs:ignore Generic.Commenting.DocComment.MissingShort return null; } /** * Which taxonomies should Critical CSS be generated for. * * @return array */ public static function get_available_taxonomies() { $taxonomies = get_taxonomies( array( 'public' => true, 'show_in_rest' => true, ), 'names' ); return array_filter( $taxonomies, 'is_taxonomy_viewable' ); } /** * Get a couple sample terms for a taxonomy. * * @param string $taxonomy Taxonomy. * * @return array */ public static function get_terms( $taxonomy ) { $args = apply_filters( 'jetpack_boost_critical_css_terms_query', array( 'fields' => 'ids', 'taxonomy' => $taxonomy, 'orderby' => 'term_order', 'number' => static::MAX_URLS, 'hide_empty' => true, 'hierarchical' => false, 'update_term_meta_cache' => false, ) ); return ( new \WP_Term_Query( $args ) )->terms; } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_success_ratio() { return static::MIN_SUCCESS_URLS / static::MAX_URLS; } }
projects/plugins/boost/app/lib/critical-css/source-providers/providers/Singular_Post_Provider.php
<?php /** * Critical CSS Provider for singular posts. * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Providers; /** * Class Singular_Post_Provider * * @package Automattic\Jetpack_Boost\Modules\Critical_CSS\Providers */ class Singular_Post_Provider extends Provider { /** * Provider name. * * @var string */ protected static $name = 'singular'; /** * Max number of posts to query. * * @var integer */ const MAX_URLS = 20; /** * Minimum number of posts to have Critical CSS generated in order for the whole process to be successful. * * @var integer */ const MIN_SUCCESS_URLS = 10; // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_critical_source_urls( $context_posts = array() ) { $links = array(); $context_post_types = wp_list_pluck( $context_posts, 'post_type' ); $post_types = self::get_post_types(); if ( ! empty( $context_post_types ) ) { $post_types = array_intersect( $post_types, $context_post_types ); } foreach ( $post_types as $post_type ) { $query = self::post_type_query( $post_type ); foreach ( $query->posts as $post ) { $links[ $post_type ][] = get_permalink( $post ); } } return $links; } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_current_storage_keys() { if ( ! is_singular() ) { return array(); } // For example: "singular_post". return array( self::$name . '_' . get_post_type() ); } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_keys() { return array_keys( self::get_post_types() ); } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_edit_url( $_provider_key ) { // phpcs:ignore Generic.Commenting.DocComment.MissingShort return null; } // phpcs:ignore /** @inheritdoc */ public static function describe_key( $provider_key ) { // phpcs:ignore Generic.Commenting.DocComment.MissingShort $post_type = substr( $provider_key, strlen( static::$name ) + 1 ); switch ( $post_type ) { case 'post': return __( 'Single post view', 'jetpack-boost' ); case 'page': return __( 'Single page view', 'jetpack-boost' ); case 'product': return __( 'Single product view', 'jetpack-boost' ); default: return __( 'Custom post type', 'jetpack-boost' ); } } /** * Get post types that need Critical CSS. * * @return mixed|void */ public static function get_post_types() { $post_types = get_post_types( array( 'public' => true ) ); unset( $post_types['attachment'] ); $post_types = array_filter( $post_types, 'is_post_type_viewable' ); return apply_filters( 'jetpack_boost_critical_css_post_types', $post_types ); } /** * Create a new WP_Query to gather sample posts. * * @param string $post_type post type. * * @return \WP_Query */ public static function post_type_query( $post_type ) { $args = apply_filters( 'jetpack_boost_critical_css_post_type_query', array( 'orderby' => 'ID', 'post_type' => $post_type, 'posts_per_page' => static::MAX_URLS, // phpcs:disable WordPress.WP.PostsPerPage.posts_per_page_posts_per_page 'post_status' => array( 'publish' ), 'no_found_rows' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, ) ); return new \WP_Query( $args ); } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_success_ratio() { return static::MIN_SUCCESS_URLS / static::MAX_URLS; } }
projects/plugins/boost/app/lib/critical-css/source-providers/providers/WP_Core_Provider.php
<?php /** * Provides core support for critical CSS * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Providers; /** * Class WP_Core_Provider. * * @package Automattic\Jetpack_Boost\Modules\Critical_CSS\Providers */ class WP_Core_Provider extends Provider { /** * Provider name. * * @var string */ protected static $name = 'core'; // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable public static function get_critical_source_urls( $context_posts = array() ) { $urls = array(); // TODO: Limit to provided context posts. $front_page = get_option( 'page_on_front' ); if ( ! empty( $front_page ) ) { $permalink = get_permalink( $front_page ); if ( ! empty( $permalink ) ) { $urls['front_page'] = array( $permalink ); } } $posts_page = get_option( 'page_for_posts' ); if ( ! empty( $posts_page ) ) { $permalink = get_permalink( $front_page ); if ( ! empty( $permalink ) ) { $urls['posts_page'] = array( $permalink ); } } else { $urls['posts_page'] = (array) home_url( '/' ); } return $urls; } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_keys() { $keys = array( 'posts_page' ); if ( ! empty( get_option( 'page_on_front' ) ) ) { $keys[] = 'front_page'; } return $keys; } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_current_storage_keys() { if ( is_home() ) { $key = 'posts_page'; } elseif ( is_front_page() ) { $key = 'front_page'; } if ( ! isset( $key ) ) { return array(); } // For example: "core_posts_page". return array( self::$name . '_' . $key ); } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_edit_url( $provider_key ) { // phpcs:ignore Generic.Commenting.DocComment.MissingShort if ( $provider_key === 'core_front_page' ) { $front_page_id = get_option( 'page_on_front' ); if ( ! empty( $front_page_id ) ) { return get_edit_post_link( $front_page_id, 'link' ); } } return null; } // phpcs:ignore /** @inheritdoc */ public static function describe_key( $provider_key ) { // phpcs:ignore Generic.Commenting.DocComment.MissingShort $page = substr( $provider_key, strlen( static::$name ) + 1 ); switch ( $page ) { case 'posts_page': return __( 'Posts page', 'jetpack-boost' ); case 'front_page': return __( 'Front page', 'jetpack-boost' ); default: return $provider_key; } } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_success_ratio() { return 1; } }
projects/plugins/boost/app/lib/critical-css/source-providers/providers/Archive_Provider.php
<?php /** * Archive provider class. * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Providers; /** * Class Archive_Provider * * @package Automattic\Jetpack_Boost\Modules\Critical_CSS\Providers */ class Archive_Provider extends Provider { /** * Provider name. * * @var string */ protected static $name = 'archive'; // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_critical_source_urls( $context_posts = array() ) { // phpcs:ignore Generic.Commenting.DocComment.MissingShort $links = array(); $context_post_types = wp_list_pluck( $context_posts, 'post_type' ); $post_types = self::get_post_types(); if ( ! empty( $context_post_types ) ) { $post_types = array_intersect( $post_types, $context_post_types ); } foreach ( $post_types as $post_type ) { $link = get_post_type_archive_link( $post_type ); if ( ! empty( $link ) ) { $links[ $post_type ][] = $link; } } return $links; } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_current_storage_keys() { if ( ! is_archive() ) { return array(); } // For example: "archive_post". return array( self::$name . '_' . get_post_type() ); } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_keys() { // phpcs:ignore Generic.Commenting.DocComment.MissingShort return self::get_post_types(); } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_edit_url( $_provider_key ) { // phpcs:ignore Generic.Commenting.DocComment.MissingShort return null; } // phpcs:ignore /** @inheritdoc */ public static function describe_key( $provider_key ) { // phpcs:ignore Generic.Commenting.DocComment.MissingShort $post_type = substr( $provider_key, strlen( static::$name ) + 1 ); switch ( $post_type ) { case 'post': return __( 'Post archive view', 'jetpack-boost' ); case 'page': return __( 'Page archive view', 'jetpack-boost' ); default: return __( 'Archive page for custom post type', 'jetpack-boost' ); } } /** * Get post types that need Critical CSS. * * @return mixed|void */ public static function get_post_types() { $post_types = get_post_types( array( 'public' => true, 'has_archive' => true, ) ); unset( $post_types['attachment'] ); $post_types = array_filter( $post_types, 'is_post_type_viewable' ); return apply_filters( 'jetpack_boost_critical_css_post_types', $post_types ); } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_success_ratio() { // phpcs:ignore Generic.Commenting.DocComment.MissingShort return 1; } }
projects/plugins/boost/app/lib/critical-css/source-providers/providers/Post_ID_Provider.php
<?php /** * The Post ID provider class. * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Providers; /** * Class Post_ID_Provider * * @package Automattic\Jetpack_Boost\Modules\Critical_CSS\Providers */ class Post_ID_Provider extends Provider { /** * Post Ids storage key. * * @var string */ const STORAGE_KEY = 'jetpack_boost_critical_css_post_ids'; /** * Provider name. * * @var string */ protected static $name = 'post_id'; // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_critical_source_urls( $context_posts = array() ) { $results = array(); $query = self::get_posts(); $context_post_ids = wp_list_pluck( $context_posts, 'ID' ); if ( false === $query ) { return array(); } foreach ( $query->posts as $post ) { if ( empty( $context_post_ids ) || in_array( $post->ID, $context_post_ids, true ) ) { $results[ $post->ID ] = array( get_permalink( $post ) ); } } return $results; } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_current_storage_keys() { if ( ! is_singular() ) { return array(); } // For example: "post_id_123". return array( self::$name . '_' . get_the_ID() ); } // phpcs:ignore /** @inheritdoc */ public static function describe_key( $provider_key ) { // phpcs:ignore Generic.Commenting.DocComment.MissingShort $post_id = (int) substr( $provider_key, strlen( self::$name ) + 1 ); $post = get_post( $post_id ); if ( ! $post ) { /* translators: %d is the id of a post which cannot be found. */ return sprintf( __( 'Post %d', 'jetpack-boost' ), $post_id ); } return $post->post_title; } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_edit_url( $provider_key ) { // phpcs:ignore Generic.Commenting.DocComment.MissingShort $post_id = (int) substr( $provider_key, strlen( self::$name ) + 1 ); return get_edit_post_link( $post_id, 'link' ); } /** * Returns a key that can be used to identify the current page, if any exists. * * @return string|null */ public static function get_current_page_key() { $keys = static::get_current_storage_keys(); if ( count( $keys ) > 0 ) { return $keys[0]; } else { return null; } } /** * Get post ids. * * @return array */ public static function get_post_ids() { // Store the IDs somewhere. return get_option( self::STORAGE_KEY, array() ); } /** * Add post id to storage. * * @param int $post_id Post Id. * * @return bool */ public static function add_post_id( $post_id ) { $post_ids = static::get_post_ids(); if ( in_array( $post_id, $post_ids, true ) ) { return false; } $post_ids[] = (int) $post_id; return update_option( self::STORAGE_KEY, $post_ids ); } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_keys() { return self::get_post_ids(); } /** * Create a new WP_Query to gather sample posts. * * @return false|\WP_Query */ public static function get_posts() { $ids = self::get_post_ids(); if ( ! $ids ) { return false; } return new \WP_Query( array( 'post__in' => $ids, 'posts_per_page' => count( $ids ), // phpcs:disable WordPress.WP.PostsPerPage.posts_per_page_posts_per_page 'post_status' => array( 'publish' ), 'post_type' => 'any', 'no_found_rows' => true, 'ignore_sticky_posts' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, ) ); } // phpcs:ignore Generic.Commenting.DocComment.MissingShort /** @inheritdoc */ public static function get_success_ratio() { return 1; } }
projects/plugins/boost/app/lib/critical-css/source-providers/providers/Provider.php
<?php /** * Abstract Critical CSS provider class. * * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Providers; /** * Class Provider * * @package Automattic\Jetpack_Boost\Modules\Critical_CSS\Providers */ abstract class Provider { /** * The name of the provider. * * @since 1.0.0 * @access protected * @var string $name The name of the provider */ protected static $name; /** * Each provider must return a list of URLs to generate CSS from. * * @param \WP_Post[] $context_posts The posts to generate CSS from. * @return array */ abstract public static function get_critical_source_urls( $context_posts = array() ); /** * What key should this provider look for during the current request? * Used in the front-end to determine where the CSS * might be stored for the current request. * * @return array */ abstract public static function get_current_storage_keys(); /** * Returns a list of all keys that this provider can provide, regardless * of the current URL. */ abstract public static function get_keys(); /** * Get a human-displayable string describing the given provider key. * * @param string $provider_key the key to describe. */ abstract public static function describe_key( $provider_key ); /** * Get the URL of the edit page for the given provider key. * * @param string $provider_key the key to edit. */ abstract public static function get_edit_url( $provider_key ); /** * Returns true if the key looks like it belongs to this provider. * * @param boolean $key The key. */ public static function owns_key( $key ) { return strncmp( static::$name, $key, strlen( static::$name ) ) === 0; } /** * Get the name of the provider. * * @return string */ public static function get_provider_name() { return static::$name; } /** * Returns the ratio of valid urls from the provider source urls * for the Critical CSS generation to be considered successful. * * @return array */ abstract public static function get_success_ratio(); }
projects/plugins/boost/app/data-sync/Performance_History_Entry.php
<?php use Automattic\Jetpack\Boost_Speed_Score\Speed_Score_Graph_History_Request; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Get; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Set; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Lazy_Entry; class Performance_History_Entry implements Lazy_Entry, Entry_Can_Get, Entry_Can_Set { private $start_date; private $end_date; public function __construct() { // Default to the last 30 days $this->start_date = ( time() - 60 * 60 * 24 * 30 ) * 1000; $this->end_date = time() * 1000; } public function get( $_fallback = false ) { $request = new Speed_Score_Graph_History_Request( $this->start_date, $this->end_date, array() ); $result = $request->execute(); if ( is_wp_error( $result ) || empty( $result['data'] ) ) { return array( 'startDate' => $this->start_date, 'endDate' => $this->end_date, 'periods' => array(), 'annotations' => array(), ); } return array( 'startDate' => $result['data']['_meta']['start'], 'endDate' => $result['data']['_meta']['end'], 'periods' => $result['data']['periods'], 'annotations' => isset( $result['data']['annotations'] ) ? $result['data']['annotations'] : array(), ); } public function set( $value ) { $this->start_date = $value['startDate']; $this->end_date = $value['endDate']; } }
projects/plugins/boost/app/data-sync/Critical_CSS_Meta_Entry.php
<?php namespace Automattic\Jetpack_Boost\Data_Sync; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Get; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Generator; class Critical_CSS_Meta_Entry implements Entry_Can_Get { public function get( $_fallback = false ) { $generator = new Generator(); return $generator->get_generation_metadata(); } }
projects/plugins/boost/app/data-sync/Modules_State_Entry.php
<?php namespace Automattic\Jetpack_Boost\Data_Sync; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Get; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Merge; use Automattic\Jetpack_Boost\Modules\Modules_Index; class Modules_State_Entry implements Entry_Can_Get, Entry_Can_Merge { public function get( $_fallback = false ) { $modules = Modules_Index::MODULES; $modules_state = array(); $available_modules = ( new Modules_Index() )->available_modules(); /* * Module states are stored in their individual wp_options records. * We combining the states of all modules into a single record and attaching the availability of the module. */ foreach ( $modules as $module ) { $slug = $module::get_slug(); $always_on = is_subclass_of( $module, 'Automattic\Jetpack_Boost\Contracts\Is_Always_On' ); if ( $always_on ) { $is_on = true; } else { $option_name = $this->get_module_option_name( $slug ); $is_on = (bool) get_option( $option_name, false ); } $modules_state[ $slug ] = array( 'active' => isset( $available_modules[ $slug ] ) && $is_on, 'available' => isset( $available_modules[ $slug ] ), ); } return $modules_state; } public function set( $value ) { foreach ( $value as $module_slug => $module_state ) { $option_name = $this->get_module_option_name( $module_slug ); $updated = update_option( $option_name, $module_state['active'] ); if ( $updated ) { /** * Fires when a module is enabled or disabled. * * @param string $module The module slug. * @param bool $status The new status. * @since 1.5.2 */ do_action( 'jetpack_boost_module_status_updated', $module_slug, $module_state['active'] ); } } } public function merge( $value, $partial_value ) { return array_merge( $value, $partial_value ); } private function get_module_option_name( $module_slug ) { return 'jetpack_boost_status_' . str_replace( '_', '-', $module_slug ); } }
projects/plugins/boost/app/data-sync/Mergeable_Array_Entry.php
<?php namespace Automattic\Jetpack_Boost\Data_Sync; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Get; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Merge; class Mergeable_Array_Entry implements Entry_Can_Get, Entry_Can_Merge { private $option_key; public function __construct( $option_key ) { $this->option_key = $option_key; } public function get( $fallback_value = false ) { // WordPress looks at argument count to figure out if a fallback value was used. // Only provide the fallback value if it's not the default ( false ). if ( $fallback_value !== false ) { return get_option( $this->option_key, $fallback_value ); } return get_option( $this->option_key ); } public function set( $value ) { update_option( $this->option_key, $value, false ); } public function merge( $value, $partial_value ) { return array_merge( $value, $partial_value ); } }
projects/plugins/boost/app/data-sync/Getting_Started_Entry.php
<?php namespace Automattic\Jetpack_Boost\Data_Sync; use Automattic\Jetpack\Status; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Get; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Set; use Automattic\Jetpack_Boost\Lib\Connection; use Automattic\Jetpack_Boost\Lib\Premium_Features; class Getting_Started_Entry implements Entry_Can_Get, Entry_Can_Set { private $option_key = 'jb_get_started'; /** * Determines if the user should be shown the Getting Started page. */ public function get( $fallback = false ) { // No point in showing the page if the site is offline, it's probably localhost. if ( ( new Status() )->is_offline_mode() ) { return false; } // If there is no connection, the page must be shown to give them a chance to connect by choosing a plan. if ( ! ( new Connection() )->is_connected() ) { return true; } // If the site already has premium plan, there is no need to show the page. if ( Premium_Features::has_any() ) { return false; } // For all other cases, the page should be shown only if the flag is set. It indicates that it's a new site. if ( $fallback !== false ) { return \get_option( $this->option_key, $fallback ); } return \get_option( $this->option_key ); } public function set( $value ) { if ( $value === true ) { update_option( $this->option_key, $value, false ); } else { delete_option( $this->option_key ); } } }
projects/plugins/boost/app/data-sync/Minify_Excludes_State_Entry.php
<?php namespace Automattic\Jetpack_Boost\Data_Sync; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Get; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Set; /** * The Minify_Excludes_State_Entry class represents a single state entry for Jetpack Boost Data Sync. * * This class implements the Entry_Can_Get and Entry_Can_Set interfaces, allowing it to retrieve and set * the current state of the Minify Excludes option. * * @package Automattic\Jetpack_Boost\Data_Sync */ class Minify_Excludes_State_Entry implements Entry_Can_Get, Entry_Can_Set { /** * The option key used to store the Minify Excludes option. * * @var string */ private $option_key; /** * Constructs a new instance of the Minify_Excludes_State_Entry class. * * @param string $option_key The option key used to store the Minify Excludes option. */ public function __construct( $option_key ) { $this->option_key = 'jetpack_boost_ds_' . $option_key; } /** * Retrieves the value of the specified option. * * If the option does not exist, it returns the provided fallback value * or null if no fallback value is provided. * * @param mixed $fallback_value Optional. The value to return if the option does not exist. * Default is false. * @return mixed The value of the option, or the fallback value if the option does not exist. */ public function get( $fallback_value = false ) { if ( $fallback_value !== false ) { return get_option( $this->option_key, $fallback_value ); } return get_option( $this->option_key ); } /** * Sets the value of the Minify Excludes option. * * @param mixed $value The new value of the Minify Excludes option. */ public function set( $value ) { $value = $this->sanitize_value( $value ); update_option( $this->option_key, $value ); } /** * Sanitizes the given value, ensuring that it is a comma-separated list of unique, trimmed strings. * * @param mixed $value The value to sanitize. * * @return string The sanitized value, as a comma-separated list of unique, trimmed strings. */ private function sanitize_value( $value ) { if ( is_array( $value ) ) { $value = array_values( array_unique( array_filter( array_map( 'trim', $value ) ) ) ); } else { $value = array(); } return $value; } }
projects/plugins/boost/app/modules/Modules_Setup.php
<?php namespace Automattic\Jetpack_Boost\Modules; use Automattic\Jetpack_Boost\Contracts\Has_Activate; use Automattic\Jetpack_Boost\Contracts\Has_Deactivate; use Automattic\Jetpack_Boost\Contracts\Has_Setup; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Regenerate; use Automattic\Jetpack_Boost\Lib\Setup; use Automattic\Jetpack_Boost\Lib\Status; use Automattic\Jetpack_Boost\Modules\Optimizations\Cloud_CSS\Cloud_CSS; use Automattic\Jetpack_Boost\REST_API\Contracts\Has_Endpoints; use Automattic\Jetpack_Boost\REST_API\REST_API; class Modules_Setup implements Has_Setup { /** * @var Modules_Index */ protected $modules = array(); /** * @var Module[] - Associative array of all Jetpack Boost modules currently available. */ protected $available_modules = array(); public function __construct() { $this->modules = new Modules_Index(); $this->available_modules = $this->modules->available_modules(); } public function have_enabled_modules() { foreach ( $this->available_modules as $module ) { if ( $module->is_enabled() ) { return true; } } return false; } public function get_status() { $status = array(); foreach ( $this->available_modules as $slug => $module ) { $status[ $slug ] = $module->is_enabled(); } return $status; } public function register_endpoints( $feature ) { if ( ! $feature instanceof Has_Endpoints ) { return false; } if ( empty( $feature->get_endpoints() ) ) { return false; } REST_API::register( $feature->get_endpoints() ); } public function init_modules() { foreach ( $this->available_modules as $slug => $module ) { if ( ! $module->is_enabled() ) { continue; } Setup::add( $module->feature ); $this->register_endpoints( $module->feature ); do_action( "jetpack_boost_{$slug}_initialized", $this ); } } /** * @inheritDoc */ public function setup() { add_action( 'plugins_loaded', array( $this, 'init_modules' ) ); add_action( 'jetpack_boost_module_status_updated', array( $this, 'on_module_status_update' ), 10, 2 ); } /** * Handle module status changes. * * @param string $module_slug The module slug. * @param bool $is_activated The new status. */ public function on_module_status_update( $module_slug, $is_activated ) { $status = new Status( $module_slug ); $status->on_update( $is_activated ); $feature = $this->modules->get_feature_instance_by_slug( $module_slug ); $has_activate = $feature && $feature instanceof Has_Activate; $has_deactivate = $feature && $feature instanceof Has_Deactivate; if ( $is_activated && $has_activate ) { $feature::activate(); } if ( ! $is_activated && $has_deactivate ) { $feature::deactivate(); } if ( $module_slug === Cloud_CSS::get_slug() && $is_activated ) { ( new Regenerate() )->start(); } } }
projects/plugins/boost/app/modules/Module.php
<?php namespace Automattic\Jetpack_Boost\Modules; use Automattic\Jetpack_Boost\Contracts\Pluggable; use Automattic\Jetpack_Boost\Lib\Status; class Module { /** * @var Status */ private $status; /** * @var Pluggable */ public $feature; public function __construct( Pluggable $feature ) { $this->feature = $feature; $this->status = new Status( $feature::get_slug() ); } public function is_enabled() { return $this->status->is_enabled(); } }
projects/plugins/boost/app/modules/Modules_Index.php
<?php namespace Automattic\Jetpack_Boost\Modules; use Automattic\Jetpack_Boost\Contracts\Pluggable; use Automattic\Jetpack_Boost\Modules\Image_Guide\Image_Guide; use Automattic\Jetpack_Boost\Modules\Image_Size_Analysis\Image_Size_Analysis; use Automattic\Jetpack_Boost\Modules\Optimizations\Cloud_CSS\Cloud_CSS; use Automattic\Jetpack_Boost\Modules\Optimizations\Critical_CSS\Critical_CSS; use Automattic\Jetpack_Boost\Modules\Optimizations\Image_CDN\Image_CDN; use Automattic\Jetpack_Boost\Modules\Optimizations\Minify\Minify_CSS; use Automattic\Jetpack_Boost\Modules\Optimizations\Minify\Minify_JS; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Page_Cache; use Automattic\Jetpack_Boost\Modules\Optimizations\Render_Blocking_JS\Render_Blocking_JS; use Automattic\Jetpack_Boost\Modules\Performance_History\Performance_History; class Modules_Index { /** * @var Module[] - Associative array of all Jetpack Boost modules. * * Example: [ 'critical_css' => Module, 'image_cdn' => Module ] */ protected $modules = array(); /** * @var Pluggable[] - Classes that handle all Jetpack Boost featues. */ const MODULES = array( Critical_CSS::class, Cloud_CSS::class, Image_Size_Analysis::class, Minify_JS::class, Minify_CSS::class, Render_Blocking_JS::class, Image_Guide::class, Image_CDN::class, Performance_History::class, Page_Cache::class, ); /** * Initialize modules. * * Note: this method ignores the nonce verification linter rule, as jb-disable-modules is intended to work * without a nonce. */ public function __construct() { foreach ( self::MODULES as $module ) { if ( $module::is_available() ) { $slug = $module::get_slug(); $this->modules[ $slug ] = new Module( new $module() ); } } } /** * Get all modules that implement a specific interface. * * @param string $interface - The interface to search for. * @return array - An array of module classes indexed by slug that implement the interface. */ public static function get_modules_implementing( string $interface ): array { $matching_modules = array(); foreach ( self::MODULES as $module ) { if ( in_array( $interface, class_implements( $module ), true ) ) { $matching_modules[ $module::get_slug() ] = $module; } } return $matching_modules; } public function available_modules() { $forced_disabled_modules = $this->get_disabled_modules(); if ( empty( $forced_disabled_modules ) ) { return $this->modules; } if ( array( 'all' ) === $forced_disabled_modules ) { return array(); } $available_modules = array(); foreach ( $this->modules as $slug => $module ) { if ( ! in_array( $slug, $forced_disabled_modules, true ) ) { $available_modules[ $slug ] = $module; } } return $available_modules; } public function is_module_enabled( $slug ) { $available_modules = $this->available_modules(); if ( ! array_key_exists( $slug, $available_modules ) ) { return false; } $module = $available_modules[ $slug ]; return $module->is_enabled(); } /** * Get the lists of modules explicitly disabled from the 'jb-disable-modules' query string. * The parameter is a comma separated value list of module slug. * * @return array */ public function get_disabled_modules() { // phpcs:disable WordPress.Security.NonceVerification.Recommended if ( ! empty( $_GET['jb-disable-modules'] ) ) { // phpcs:disable WordPress.Security.NonceVerification.Recommended // phpcs:disable WordPress.Security.ValidatedSanitizedInput.MissingUnslash // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized return array_map( 'sanitize_key', explode( ',', $_GET['jb-disable-modules'] ) ); } return array(); } public function get_feature_instance_by_slug( $slug ) { return isset( $this->modules[ $slug ] ) ? $this->modules[ $slug ]->feature : false; } }
projects/plugins/boost/app/modules/image-size-analysis/Image_Size_Analysis_Fixer.php
<?php namespace Automattic\Jetpack_Boost\Modules\Image_Size_Analysis; class Image_Size_Analysis_Fixer { public static function setup() { add_filter( 'the_content', array( __CLASS__, 'fix_content' ), 99 ); add_filter( 'wp_calculate_image_srcset', array( __CLASS__, 'fix_image_attachments' ), 10, 5 ); add_filter( 'wp_calculate_image_sizes', array( __CLASS__, 'fix_image_sizes' ), 10, 5 ); } /** * Clean up image URLs, removing image dimensions and Photon parts from them. * Before: https://i0.wp.com/example.com/test-1024x768.jpg * After: https://example.com/test.jpg * * @param string $url * @return string * */ public static function fix_url( $url ) { $parsed_url = wp_parse_url( $url ); if ( ! isset( $parsed_url['host'] ) ) { return $url; } $path = preg_replace( '/-\d+x\d+\.jpg/', '.jpg', $parsed_url['path'] ); // remove "-1024x768" from the end of the URL. $host = str_replace( 'i0.wp.com/', '', $parsed_url['host'] ); return $parsed_url['scheme'] . '://' . $host . $path; } public static function get_fixes( $post_id ) { static $fixes = array(); if ( isset( $fixes[ $post_id ] ) ) { return $fixes[ $post_id ]; } $fixes[ $post_id ] = get_post_meta( $post_id, '_jb_image_fixes', true ); if ( ! $fixes[ $post_id ] ) { $fixes[ $post_id ] = array(); } return $fixes[ $post_id ]; } public static function get_all_fixes() { $fixes = array(); $posts = get_posts( array( 'posts_per_page' => -1, 'meta_key' => '_jb_image_fixes', 'meta_compare' => 'EXISTS', ) ); foreach ( $posts as $post ) { $fix = get_post_meta( $post->ID, '_jb_image_fixes', true ); if ( ! empty( $fix ) ) { $fixes[ $post->ID ] = $fix; } } return $fixes; } public static function get_post_id( $edit_url ) { if ( empty( $edit_url ) ) { return 0; } $query_string = wp_parse_url( esc_url_raw( $edit_url ), PHP_URL_QUERY ); parse_str( $query_string, $query_args ); if ( ! isset( $query_args['post'] ) ) { return 0; } return absint( $query_args['post'] ); } public static function is_fixed( $post_id, $image_url ) { $fixes = self::get_fixes( $post_id ); if ( ! $fixes ) { return false; } $image_url = self::fix_url( $image_url ); $attachment_id = attachment_url_to_postid( esc_url_raw( $image_url ) ); if ( $attachment_id && isset( $fixes[ $attachment_id ] ) ) { return true; } $url_key = md5( $image_url ); return isset( $fixes[ $url_key ] ); } // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable public static function fix_image_attachments( $sources, $size_array, $image_url, $image_meta, $attachment_id ) { $post = get_post(); $post_id = $post->ID; $fixes = self::get_fixes( $post_id ); $image_width = 0; // remove XxY dimension from $image_url as that's what's recorded by Image_Size_Analysis. $image_url_key = self::fix_url( $image_url ); if ( $attachment_id && isset( $fixes[ $attachment_id ] ) && ! empty( $fixes[ $attachment_id ] ) ) { $image_width = $fixes[ $attachment_id ]['image_width']; } elseif ( isset( $fixes[ $image_url_key ] ) ) { $image_width = $fixes[ $image_url_key ]['image_width']; } if ( $image_width ) { $sources [ $image_width ] = array( 'url' => \Automattic\Jetpack\Image_CDN\Image_CDN_Core::cdn_url( $image_url, array( 'w' => $image_width ) ), 'descriptor' => 'w', 'value' => $image_width, ); } return $sources; } // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable public static function fix_image_sizes( $sizes, $size, $image_url, $image_meta, $attachment_id ) { $post = get_post(); $post_id = $post->ID; $fixes = self::get_fixes( $post_id ); $image_width = 0; $image_url_key = self::fix_url( $image_url ); if ( $attachment_id && isset( $fixes[ $attachment_id ]['image_width'] ) ) { $image_width = $fixes[ $attachment_id ]['image_width']; } elseif ( isset( $fixes[ $image_url_key ]['image_width'] ) ) { $image_width = $fixes[ $image_url_key ]['image_width']; } if ( $image_width ) { $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $image_width ); } return $sizes; } public static function fix_content( $content ) { $post = get_post(); $fixes = self::get_fixes( $post->ID ); if ( ! $fixes ) { return $content; } $tag_processor = new \WP_HTML_Tag_Processor( $content ); while ( $tag_processor->next_tag( array( 'tag_name' => 'img' ) ) ) { $image_url = $tag_processor->get_attribute( 'src' ); $image_url_key = md5( self::fix_url( $image_url ) ); $srcset = $tag_processor->get_attribute( 'srcset' ); if ( ! isset( $fixes[ $image_url_key ] ) ) { continue; } if ( isset( $fixes[ $image_url_key ]['image_width'] ) && ! strpos( (string) $srcset, ' ' . $fixes[ $image_url_key ]['image_width'] . 'w' ) ) { $tag_processor->set_attribute( 'srcset', \Automattic\Jetpack\Image_CDN\Image_CDN_Core::cdn_url( $image_url, array( 'w' => $fixes[ $image_url_key ]['image_width'] ) ) . ' ' . $fixes[ $image_url_key ]['image_width'] . 'w, ' . $srcset ); } if ( isset( $fixes[ $image_url_key ]['image_width'] ) ) { $tag_processor->set_attribute( 'sizes', sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $fixes[ $image_url_key ]['image_width'] ) ); } } return $tag_processor->get_updated_html(); } public static function sanitize_params( $params ) { if ( ! isset( $params['image_url'] ) ) { throw new \Exception( 'Missing image_url' ); } if ( ! isset( $params['image_width'] ) ) { throw new \Exception( 'Missing image_width' ); } if ( ! isset( $params['image_height'] ) ) { throw new \Exception( 'Missing image_height' ); } if ( ! isset( $params['post_id'] ) ) { throw new \Exception( 'Missing post_id' ); } if ( ! isset( $params['fix'] ) ) { throw new \Exception( 'Missing fix' ); } if ( ! isset( $params['image_id'] ) ) { throw new \Exception( 'Missing image_id' ); } $out = array(); $out['image_id'] = absint( $params['image_id'] ); $out['image_url'] = esc_url_raw( $params['image_url'] ); $out['image_width'] = absint( $params['image_width'] ); $out['image_height'] = absint( $params['image_height'] ); $out['post_id'] = absint( $params['post_id'] ); $out['fix'] = (bool) $params['fix']; return $out; } }
projects/plugins/boost/app/modules/image-size-analysis/Image_Size_Analysis.php
<?php namespace Automattic\Jetpack_Boost\Modules\Image_Size_Analysis; use Automattic\Jetpack_Boost\Contracts\Is_Always_On; use Automattic\Jetpack_Boost\Contracts\Pluggable; use Automattic\Jetpack_Boost\Lib\Premium_Features; class Image_Size_Analysis implements Pluggable, Is_Always_On { public function setup() { Image_Size_Analysis_Fixer::setup(); } public static function is_available() { return Premium_Features::has_feature( Premium_Features::IMAGE_SIZE_ANALYSIS ); } public static function get_slug() { return 'image_size_analysis'; } }
projects/plugins/boost/app/modules/image-size-analysis/data-sync/init.php
<?php use Automattic\Jetpack\WP_JS_Data_Sync\Schema\Schema; use Automattic\Jetpack_Boost\Modules\Image_Size_Analysis\Data_Sync\Image_Size_Analysis_Entry; use Automattic\Jetpack_Boost\Modules\Image_Size_Analysis\Data_Sync\Image_Size_Analysis_Summary; use Automattic\Jetpack_Boost\REST_API\Endpoints\Image_Analysis_Action_Fix; use Automattic\Jetpack_Boost\REST_API\Endpoints\Image_Size_Analysis_Summary_Action_Paginate; use Automattic\Jetpack_Boost\REST_API\Endpoints\Image_Size_Analysis_Summary_Action_Start; $image_data = Schema::as_assoc_array( array( 'id' => Schema::as_string(), 'thumbnail' => Schema::as_string(), 'device_type' => Schema::enum( array( 'phone', 'desktop' ) ), 'status' => Schema::enum( array( 'active', 'ignored' ) )->fallback( 'active' ), 'instructions' => Schema::as_string(), 'type' => Schema::enum( array( 'image_size', 'bad_entry', 'image_missing' ) )->fallback( 'bad_entry' ), 'page' => Schema::as_assoc_array( array( 'id' => Schema::as_number(), 'url' => Schema::as_string(), 'edit_url' => Schema::as_string()->nullable(), 'title' => Schema::as_string(), ) ), 'image' => Schema::as_assoc_array( array( 'url' => Schema::as_string(), 'fixed' => Schema::as_boolean()->fallback( false ), 'dimensions' => Schema::as_assoc_array( array( 'file' => Schema::as_assoc_array( array( 'width' => Schema::as_number(), 'height' => Schema::as_number(), ) ), 'expected' => Schema::as_assoc_array( array( 'width' => Schema::as_number(), 'height' => Schema::as_number(), ) ), 'size_on_screen' => Schema::as_assoc_array( array( 'width' => Schema::as_number(), 'height' => Schema::as_number(), ) ), ) ), 'weight' => Schema::as_assoc_array( array( 'current' => Schema::as_number(), 'potential' => Schema::as_number(), ) ), ) )->nullable(), ) )->nullable(); $image_size_analysis = Schema::as_assoc_array( array( 'last_updated' => Schema::as_number(), 'total_pages' => Schema::as_number(), 'images' => Schema::as_array( $image_data ), ) ); jetpack_boost_register_option( 'image_size_analysis', $image_size_analysis, new Image_Size_Analysis_Entry() ); jetpack_boost_register_action( 'image_size_analysis', 'paginate', Schema::as_assoc_array( array( 'page' => Schema::as_number(), 'group' => Schema::as_string(), ) ), new Image_Size_Analysis_Summary_Action_Paginate() ); jetpack_boost_register_action( 'image_size_analysis', 'fix', Schema::as_assoc_array( array( 'image_id' => Schema::as_number(), 'image_url' => Schema::as_string(), 'image_width' => Schema::as_number(), 'image_height' => Schema::as_number(), 'post_id' => Schema::as_number(), 'fix' => Schema::as_boolean(), ) ), new Image_Analysis_Action_Fix() ); $group_schema = Schema::as_assoc_array( array( 'issue_count' => Schema::as_number(), 'scanned_pages' => Schema::as_number(), 'total_pages' => Schema::as_number(), ) )->nullable(); $summary_schema = Schema::as_assoc_array( array( 'status' => Schema::enum( array( 'not-found', 'new', 'queued', 'completed', 'error', 'error_stuck', ) ), 'report_id' => Schema::as_number()->nullable(), 'groups' => Schema::as_assoc_array( array( 'core_front_page' => $group_schema, 'singular_page' => $group_schema, 'singular_post' => $group_schema, 'other' => $group_schema, 'fixed' => $group_schema, ) )->nullable(), ) )->fallback( array( 'status' => 'not-found', 'groups' => null, ) ); jetpack_boost_register_option( 'image_size_analysis_summary', $summary_schema, new Image_Size_Analysis_Summary() ); jetpack_boost_register_action( 'image_size_analysis_summary', 'start', Schema::as_void(), new Image_Size_Analysis_Summary_Action_Start() );
projects/plugins/boost/app/modules/image-size-analysis/data-sync/Image_Size_Analysis_Action_Fix.php
<?php namespace Automattic\Jetpack_Boost\REST_API\Endpoints; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Data_Sync_Action; use Automattic\Jetpack_Boost\Lib\Premium_Features; use Automattic\Jetpack_Boost\Modules\Image_Size_Analysis\Image_Size_Analysis_Fixer; /** * Image Size Analysis: Action to fix an image */ class Image_Analysis_Action_Fix implements Data_Sync_Action { /** * Handles the action logic. * * @param mixed $data JSON Data passed to the action. * @param \WP_REST_Request $request The request object. * * @throws \Exception */ public function handle( $data, $_request ) { if ( ! Premium_Features::has_feature( Premium_Features::IMAGE_SIZE_ANALYSIS ) ) { return new \WP_Error( 'not-allowed', 'Feature not enabled' ); } $params = Image_Size_Analysis_Fixer::sanitize_params( $data ); $fixes = Image_Size_Analysis_Fixer::get_fixes( $params['post_id'] ); $image_url = Image_Size_Analysis_Fixer::fix_url( $params['image_url'] ); $attachment_id = attachment_url_to_postid( esc_url( $image_url ) ); $changed = false; if ( isset( $params['fix'] ) && ! $params['fix'] ) { if ( isset( $fixes[ $attachment_id ] ) ) { unset( $fixes[ $attachment_id ] ); } else { unset( $fixes[ md5( $image_url ) ] ); } $changed = 'removed'; } elseif ( $attachment_id ) { $fixes[ $attachment_id ] = $params; $changed = 'fix'; } else { $fixes[ md5( $image_url ) ] = $params; // hot linked image, possibly from another site. $changed = 'fix'; } if ( $changed ) { $status = update_post_meta( $data['post_id'], '_jb_image_fixes', $fixes ); } if ( ! $status ) { return array( 'status' => 'error', 'code' => 'failed-to-save-fixes', ); } return array( 'status' => 'success', 'code' => 'fixes-saved', 'changed' => $changed, 'image_id' => $data['image_id'], ); } }
projects/plugins/boost/app/modules/image-size-analysis/data-sync/Image_Size_Analysis_Summary_Action_Start.php
<?php namespace Automattic\Jetpack_Boost\REST_API\Endpoints; use Automattic\Jetpack\Boost_Core\Lib\Boost_API; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Data_Sync_Action; use Automattic\Jetpack_Boost\Lib\Premium_Features; /** * Image Size Analysis: Action to fix an image */ class Image_Size_Analysis_Summary_Action_Start implements Data_Sync_Action { public function handle( $_data, $_request ) { // @TODO: Add a proper feature flag for this instead of just checking if priority support available. if ( ! Premium_Features::has_feature( Premium_Features::IMAGE_SIZE_ANALYSIS ) ) { return new \WP_Error( 'not-allowed', 'Feature not enabled' ); } // Send a request to WPCOM asking for a new Image Size Analysis run. $response = Boost_API::post( 'image-guide/reports', array( 'report_type' => 'image-guide', ) ); // If WPCOM complains, add a little context to the error. if ( is_wp_error( $response ) ) { if ( $response->get_error_code() === '429' ) { return new \WP_Error( $response->get_error_code(), __( 'You have sent too many requests, please try later.', 'jetpack-boost' ) ); } return new \WP_Error( $response->get_error_code(), sprintf( /* translators: %s is the original error message from WordPress.com */ __( 'Jetpack Boost Cloud Error: "%s"', 'jetpack-boost' ), $response->get_error_message() ) ); } // Send a success response. return array( 'ok' => true, ); } }
projects/plugins/boost/app/modules/image-size-analysis/data-sync/Image_Size_Analysis_Entry.php
<?php namespace Automattic\Jetpack_Boost\Modules\Image_Size_Analysis\Data_Sync; use Automattic\Jetpack\Boost_Core\Lib\Boost_API; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Get; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Lazy_Entry; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Source_Providers; use Automattic\Jetpack_Boost\Modules\Image_Size_Analysis\Image_Size_Analysis_Fixer; class Image_Size_Analysis_Entry implements Lazy_Entry, Entry_Can_Get { public function get( $page = 1, $group = 'all' ) { $report_id = defined( 'JETPACK_BOOST_FORCE_REPORT_ID' ) ? JETPACK_BOOST_FORCE_REPORT_ID : 'latest'; $data = Boost_API::get( 'image-guide/reports/' . $report_id . '/issues', array( 'page' => $page, 'group' => sanitize_title( wp_unslash( $group ) ), 'per_page' => 20, ) ); $issues = array(); foreach ( $data['issues'] as $issue ) { $page_provider = $this->get_page( $issue ); $image = $this->get_image_info( $issue ); if ( empty( $page_provider['edit_url'] ) ) { // archive or front page $image['fixed'] = false; } else { $post_id = Image_Size_Analysis_Fixer::get_post_id( $page_provider['edit_url'] ); $image['fixed'] = Image_Size_Analysis_Fixer::is_fixed( $post_id, $image['url'] ); } $issues[] = array( 'id' => $issue['id'], 'thumbnail' => $issue['url'], 'device_type' => $issue['device'], 'type' => $issue['type'], 'status' => $issue['status'], 'instructions' => $this->get_instructions( $issue ), 'page' => $page_provider, 'image' => $image, ); } return array( 'last_updated' => strtotime( $data['last_updated'] ) * 1000, 'total_pages' => $data['pagination']['total_pages'], 'images' => $issues, ); } /** * Get the page info for a given key * * @todo: Implement */ private function get_page( $issue ) { $key = $issue['page_provider']; $provider = $this->get_provider( $key ); $title = empty( $provider ) ? $key : $provider::describe_key( $key ); $edit_url = empty( $provider ) ? null : $provider::get_edit_url( $key ); if ( empty( $title ) ) { $title = $issue['page_provider']; } return array( 'id' => $issue['page_id'], 'url' => $issue['page_url'], 'edit_url' => $edit_url ? $edit_url : null, 'title' => $title, ); } /** * Generate instructions for an issue. */ private function get_instructions( $_issue ) { return __( 'Resize the image to the expected dimensions and compress it.', 'jetpack-boost' ); } /** * Get the image info for a given issue * * @todo: Implement */ private function get_image_info( $issue ) { return array( 'url' => $issue['url'], 'dimensions' => array( 'file' => array( 'width' => $issue['meta']['fileSize_width'], 'height' => $issue['meta']['fileSize_height'], ), 'expected' => array( 'width' => $issue['meta']['expectedSize_width'], 'height' => $issue['meta']['expectedSize_height'], ), 'size_on_screen' => array( 'width' => $issue['meta']['sizeOnPage_width'], 'height' => $issue['meta']['sizeOnPage_height'], ), ), 'weight' => array( 'current' => $issue['meta']['fileSize_weight'], 'potential' => (int) $issue['meta']['potentialSavings'], ), ); } /** * Get a provider for a given key. */ private function get_provider( $key ) { static $providers = null; if ( null === $providers ) { $providers = new Source_Providers(); } return $providers->get_provider_for_key( $key ); } }
projects/plugins/boost/app/modules/image-size-analysis/data-sync/Image_Size_Analysis_Summary.php
<?php namespace Automattic\Jetpack_Boost\Modules\Image_Size_Analysis\Data_Sync; use Automattic\Jetpack\Boost_Core\Lib\Boost_API; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Get; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Lazy_Entry; use Automattic\Jetpack_Boost\Modules\Image_Size_Analysis\Image_Size_Analysis_Fixer; class Image_Size_Analysis_Summary implements Lazy_Entry, Entry_Can_Get { public function get( $_fallback = false ) { $fixes = Image_Size_Analysis_Fixer::get_all_fixes(); $report_id = defined( 'JETPACK_BOOST_FORCE_REPORT_ID' ) ? JETPACK_BOOST_FORCE_REPORT_ID : 'latest'; $report = Boost_API::get( 'image-guide/reports/' . $report_id ); if ( is_wp_error( $report ) ) { // If no report is found, return it as a status. if ( $report->get_error_code() === 'report-not-found' ) { throw new \RuntimeException( 'Report not found' ); } // Other kinds of errors are a problem. return array( 'status' => 'error', 'error' => $report->get_error_message(), ); } if ( ! empty( $fixes ) ) { // $fixes is an array of post_ids. which is an array of image fixes. count the number of image fixes. $fixed_count = 0; foreach ( $fixes as $image_fixes ) { $fixed_count += count( $image_fixes ); } // add fixed group object to $report->groups $report['groups']['fixed'] = array(); $report['groups']['fixed']['issue_count'] = $fixed_count; $report['groups']['fixed']['scanned_pages'] = count( $fixes ); $report['groups']['fixed']['total_pages'] = 1; } // disable the fixed group for now. unset( $report['groups']['fixed'] ); return $report; } }
projects/plugins/boost/app/modules/image-size-analysis/data-sync/Image_Size_Analysis_Action_Paginate.php
<?php namespace Automattic\Jetpack_Boost\REST_API\Endpoints; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Data_Sync_Action; use Automattic\Jetpack_Boost\Modules\Image_Size_Analysis\Data_Sync\Image_Size_Analysis_Entry; /** * Image Size Analysis: Action to fix an image */ class Image_Size_Analysis_Summary_Action_Paginate implements Data_Sync_Action { public function handle( $data, $_request ) { $entry = new Image_Size_Analysis_Entry(); return $entry->get( $data['page'], $data['group'] ); } }
projects/plugins/boost/app/modules/performance-history/Performance_History.php
<?php namespace Automattic\Jetpack_Boost\Modules\Performance_History; use Automattic\Jetpack_Boost\Contracts\Is_Always_On; use Automattic\Jetpack_Boost\Contracts\Pluggable; use Automattic\Jetpack_Boost\Lib\Premium_Features; class Performance_History implements Pluggable, Is_Always_On { public function setup() { // noop } public static function is_available() { return Premium_Features::has_feature( Premium_Features::PERFORMANCE_HISTORY ); } public static function get_slug() { return 'performance_history'; } }
projects/plugins/boost/app/modules/image-guide/Image_Guide_Proxy.php
<?php namespace Automattic\Jetpack_Boost\Modules\Image_Guide; /** * Add an ajax endpoint to proxy external CSS files. */ class Image_Guide_Proxy { const NONCE_ACTION = 'jb-ig-proxy-nonce'; public static function init() { add_action( 'wp_ajax_boost_proxy_ig', array( __CLASS__, 'handle_proxy' ) ); } /** * AJAX handler to handle proxying of external image resources. */ public static function handle_proxy() { // Verify valid nonce. if ( empty( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['nonce'] ), self::NONCE_ACTION ) ) { wp_send_json_error( 'bad nonce', 400 ); } // Make sure currently logged in as admin. if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( 'not admin', 400 ); } // Validate URL and fetch. $proxy_url = filter_var( wp_unslash( isset( $_POST['proxy_url'] ) ? $_POST['proxy_url'] : null ), FILTER_VALIDATE_URL ); if ( ! wp_http_validate_url( $proxy_url ) ) { wp_send_json_error( 'Invalid URL', 400 ); } $response = wp_remote_get( $proxy_url ); if ( is_wp_error( $response ) ) { wp_send_json_error( 'error', 400 ); } wp_send_json_success( iterator_to_array( wp_remote_retrieve_headers( $response ) ) ); die(); } }
projects/plugins/boost/app/modules/image-guide/Image_Guide.php
<?php namespace Automattic\Jetpack_Boost\Modules\Image_Guide; use Automattic\Jetpack_Boost\Admin\Admin; use Automattic\Jetpack_Boost\Contracts\Pluggable; use Automattic\Jetpack_Boost\Lib\Analytics; class Image_Guide implements Pluggable { public function setup() { // phpcs:ignore WordPress.Security.NonceVerification.Recommended $override = isset( $_GET['jb-debug-ig'] ); if ( is_admin() || is_user_logged_in() || current_user_can( 'manage_options' ) ) { Image_Guide_Proxy::init(); } // Show the UI only when the user is logged in, with sufficient permissions and isn't looking at the dashboard. if ( true !== $override && ( is_admin() || ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) ) { return; } // Enqueue the tracks library. add_action( 'wp_enqueue_scripts', array( Analytics::class, 'init_tracks_scripts' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) ); /** * The priority determines where the admin bar menu item is placed. */ add_action( 'admin_bar_menu', array( $this, 'add_to_adminbar' ), 500 ); } public static function get_slug() { return 'image_guide'; } public function enqueue_assets() { wp_enqueue_script( 'jetpack-boost-guide', plugins_url( 'dist/guide.js', __FILE__ ), array( 'wp-i18n' ), JETPACK_BOOST_VERSION, true ); wp_enqueue_style( 'jetpack-boost-guide', plugins_url( 'dist/guide.css', __FILE__ ), array(), JETPACK_BOOST_VERSION, 'screen' ); wp_localize_script( 'jetpack-boost-guide', 'jetpackBoostAnalytics', array( 'tracksData' => Analytics::get_tracking_data(), ) ); wp_localize_script( 'jetpack-boost-guide', 'jbImageGuide', array( 'proxyNonce' => wp_create_nonce( Image_Guide_Proxy::NONCE_ACTION ), 'ajax_url' => admin_url( 'admin-ajax.php' ), ) ); } /** * @param \WP_Admin_Bar $bar */ public function add_to_adminbar( $bar ) { // Disable in Admin Dashboard if ( is_admin() ) { return; } $bar->add_menu( array( 'id' => 'jetpack-boost-guide', 'parent' => null, 'group' => null, 'title' => __( 'Jetpack Boost', 'jetpack-boost' ), 'href' => admin_url( 'admin.php?page=' . Admin::MENU_SLUG ), 'meta' => array( 'target' => '_self', 'class' => 'jetpack-boost-guide', ), ) ); } public static function is_available() { return true; } }
projects/plugins/boost/app/modules/optimizations/index.php
<?php //phpcs:ignoreFile /** * Empty file. */ // Silence is golden.
projects/plugins/boost/app/modules/optimizations/minify/class-minify-css.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Minify; use Automattic\Jetpack_Boost\Contracts\Changes_Page_Output; use Automattic\Jetpack_Boost\Contracts\Pluggable; use Automattic\Jetpack_Boost\Lib\Minify\Concatenate_CSS; class Minify_CSS implements Pluggable, Changes_Page_Output { public static $default_excludes = array( 'admin-bar', 'dashicons', 'elementor-app' ); public function setup() { require_once JETPACK_BOOST_DIR_PATH . '/app/lib/minify/functions-helpers.php'; jetpack_boost_minify_setup(); if ( jetpack_boost_page_optimize_bail() ) { return; } add_action( 'init', array( $this, 'init_minify' ) ); } public static function get_slug() { return 'minify_css'; } public static function is_available() { return true; } public function init_minify() { global $wp_styles; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited $wp_styles = new Concatenate_CSS( $wp_styles ); $wp_styles->allow_gzip_compression = true; // @todo - used constant ALLOW_GZIP_COMPRESSION = true if not defined. } }
projects/plugins/boost/app/modules/optimizations/minify/class-minify-js.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Minify; use Automattic\Jetpack_Boost\Contracts\Changes_Page_Output; use Automattic\Jetpack_Boost\Contracts\Pluggable; use Automattic\Jetpack_Boost\Lib\Minify\Concatenate_JS; class Minify_JS implements Pluggable, Changes_Page_Output { public static $default_excludes = array( 'jquery', 'jquery-core', 'underscore', 'backbone' ); public function setup() { require_once JETPACK_BOOST_DIR_PATH . '/app/lib/minify/functions-helpers.php'; jetpack_boost_minify_setup(); if ( jetpack_boost_page_optimize_bail() ) { return; } add_action( 'init', array( $this, 'init_minify' ) ); } public static function get_slug() { return 'minify_js'; } public static function is_available() { return true; } public function init_minify() { global $wp_scripts; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited $wp_scripts = new Concatenate_JS( $wp_scripts ); $wp_scripts->allow_gzip_compression = true; // @todo - used constant ALLOW_GZIP_COMPRESSION = true if not defined. } }
projects/plugins/boost/app/modules/optimizations/cloud-css/Cloud_CSS.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Cloud_CSS; use Automattic\Jetpack\Boost_Core\Lib\Boost_API; use Automattic\Jetpack_Boost\Contracts\Changes_Page_Output; use Automattic\Jetpack_Boost\Contracts\Pluggable; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Admin_Bar_Compatibility; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_Invalidator; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_Storage; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Display_Critical_CSS; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Generator; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Source_Providers; use Automattic\Jetpack_Boost\Lib\Premium_Features; use Automattic\Jetpack_Boost\REST_API\Contracts\Has_Endpoints; use Automattic\Jetpack_Boost\REST_API\Endpoints\Update_Cloud_CSS; class Cloud_CSS implements Pluggable, Has_Endpoints, Changes_Page_Output { /** * Critical CSS storage class instance. * * @var Critical_CSS_Storage */ protected $storage; /** * Critical CSS Provider Paths. * * @var Source_Providers */ protected $paths; public function __construct() { $this->storage = new Critical_CSS_Storage(); $this->paths = new Source_Providers(); } public function setup() { add_action( 'wp', array( $this, 'display_critical_css' ) ); add_action( 'save_post', array( $this, 'handle_save_post' ), 10, 2 ); add_action( 'jetpack_boost_critical_css_invalidated', array( $this, 'handle_critical_css_invalidated' ) ); add_filter( 'jetpack_boost_total_problem_count', array( $this, 'update_total_problem_count' ) ); add_filter( 'query_vars', array( '\Automattic\Jetpack_Boost\Lib\Critical_CSS\Generator', 'add_generate_query_action_to_list' ) ); Generator::init(); Critical_CSS_Invalidator::init(); Cloud_CSS_Followup::init(); return true; } public static function is_available() { return true === Premium_Features::has_feature( Premium_Features::CLOUD_CSS ); } public static function get_slug() { return 'cloud_css'; } public function get_endpoints() { return array( new Update_Cloud_CSS(), ); } public function display_critical_css() { // Don't look for Critical CSS in the dashboard. if ( is_admin() ) { return; } // Don't show Critical CSS in customizer previews. if ( is_customize_preview() ) { return; } // Don't display Critical CSS, if current page load is by the Critical CSS generator. if ( Generator::is_generating_critical_css() ) { return; } // Get the Critical CSS to show. $critical_css = $this->paths->get_current_request_css(); if ( ! $critical_css ) { $keys = $this->paths->get_current_request_css_keys(); $pending = ( new Critical_CSS_State() )->has_pending_provider( $keys ); // If Cloud CSS is still generating and the user is logged in, render the status information in a comment. if ( $pending && is_user_logged_in() ) { $display = new Display_Critical_CSS( '/* ' . __( 'Jetpack Boost is currently generating critical css for this page', 'jetpack-boost' ) . ' */' ); add_action( 'wp_head', array( $display, 'display_critical_css' ), 0 ); } return; } $display = new Display_Critical_CSS( $critical_css ); add_action( 'wp_head', array( $display, 'display_critical_css' ), 0 ); add_filter( 'style_loader_tag', array( $display, 'asynchronize_stylesheets' ), 10, 4 ); add_action( 'wp_footer', array( $display, 'onload_flip_stylesheets' ) ); // Ensure admin bar compatibility. Admin_Bar_Compatibility::init(); } /** * Create a Cloud CSS requests for provider groups. * * Initialize the Cloud CSS request. Provide $post parameter to limit generating to provider groups only associated * with a specific post. */ public function generate_cloud_css( $providers = array() ) { $grouped_urls = array(); foreach ( $providers as $source ) { $provider = $source['key']; $grouped_urls[ $provider ] = $source['urls']; } // Send the request to the Cloud. $payload = array( 'providers' => $grouped_urls ); $payload['requestId'] = md5( wp_json_encode( $payload ) . time() ); return Boost_API::post( 'cloud-css', $payload ); } /** * Handle regeneration of Cloud CSS when a post is saved. */ public function handle_save_post( $post_id, $post ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable if ( ! $post || ! isset( $post->post_type ) || ! is_post_publicly_viewable( $post ) ) { return; } $this->regenerate_cloud_css(); } public function regenerate_cloud_css() { $result = $this->generate_cloud_css( $this->get_existing_sources() ); if ( is_wp_error( $result ) ) { $state = new Critical_CSS_State(); $state->set_error( $result->get_error_message() )->save(); } return $result; } /** * Called when stored Critical CSS has been invalidated. Triggers a new Cloud CSS request. */ public function handle_critical_css_invalidated() { $this->regenerate_cloud_css(); Cloud_CSS_Followup::schedule(); } public function get_existing_sources() { $state = new Critical_CSS_State(); $data = $state->get(); if ( isset( $data['providers'] ) ) { $providers = $data['providers']; } else { $source_providers = new Source_Providers(); $providers = $source_providers->get_provider_sources(); } return $providers; } /** * Updates the total problem count for Boost if something's * wrong with Cloud CSS. * * @param int $count The current problem count. * * @return int */ public function update_total_problem_count( $count ) { return ( new Critical_CSS_State() )->has_errors() ? ++$count : $count; } }
projects/plugins/boost/app/modules/optimizations/cloud-css/Cloud_CSS_Followup.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Cloud_CSS; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State; class Cloud_CSS_Followup { const SCHEDULER_HOOK = 'jetpack_boost_cloud_css_followup'; /** * Initiate the scheduler * * Whenever Cloud CSS module is setup, it will call this method. * * @return void */ public static function init() { /* * Run the scheduled job */ add_action( self::SCHEDULER_HOOK, array( self::class, 'run' ) ); } /** * Run the cron job. */ public static function run() { $state = new Critical_CSS_State(); if ( $state->has_errors() ) { $cloud_css = new Cloud_CSS(); $cloud_css->regenerate_cloud_css(); } } /** * Add a cron-job to maintain cloud CSS * * @param int $when Timestamp of when to schedule the event. * * @return void */ public static function schedule() { // Remove any existing schedule self::unschedule(); wp_schedule_single_event( time() + HOUR_IN_SECONDS, self::SCHEDULER_HOOK ); } /** * Remove the cron-job */ public static function unschedule() { wp_clear_scheduled_hook( self::SCHEDULER_HOOK ); } }
projects/plugins/boost/app/modules/optimizations/render-blocking-js/class-render-blocking-js.php
<?php /** * Implements the system to avoid render blocking JS execution. * * @link https://automattic.com * @since 0.2 * @package automattic/jetpack-boost */ namespace Automattic\Jetpack_Boost\Modules\Optimizations\Render_Blocking_JS; use Automattic\Jetpack_Boost\Contracts\Changes_Page_Output; use Automattic\Jetpack_Boost\Contracts\Pluggable; use Automattic\Jetpack_Boost\Lib\Output_Filter; /** * Class Render_Blocking_JS */ class Render_Blocking_JS implements Pluggable, Changes_Page_Output { /** * Holds the script tags removed from the output buffer. * * @var array */ protected $buffered_script_tags = array(); /** * HTML attribute name to be added to <script> tag to make it * ignored by this class. * * @var string|null */ private $ignore_attribute; /** * HTML attribute value to be added to <script> tag to make it * ignored by this class. * * @var string */ private $ignore_value = 'ignore'; /** * Utility class that supports output filtering. * * @var Output_Filter */ private $output_filter = null; /** * Flag indicating an opened <script> tag in output. * * @var string */ private $is_opened_script = false; public function setup() { $this->output_filter = new Output_Filter(); // Set up the ignore attribute value. $this->ignore_attribute = apply_filters( 'jetpack_boost_render_blocking_js_ignore_attribute', 'data-jetpack-boost' ); add_action( 'template_redirect', array( $this, 'start_output_filtering' ), -999999 ); } public static function is_available() { return true; } /** * Set up an output filtering callback. * * @return void */ public function start_output_filtering() { /** * We're doing heavy output filtering in this module * by using output buffering. * * Here are a few scenarios when we shouldn't do it: */ // Give a chance to disable defer blocking js. if ( false === apply_filters( 'jetpack_boost_should_defer_js', '__return_true' ) ) { return; } // Disable in robots.txt. if ( isset( $_SERVER['REQUEST_URI'] ) && strpos( home_url( wp_unslash( $_SERVER['REQUEST_URI'] ) ), 'robots.txt' ) !== false ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- This is validating. return; } // Disable in other possible AJAX requests setting cors related header. if ( isset( $_SERVER['HTTP_SEC_FETCH_MODE'] ) && 'cors' === strtolower( $_SERVER['HTTP_SEC_FETCH_MODE'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- This is validating. return; } // Disable in other possible AJAX requests setting XHR related header. if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && 'xmlhttprequest' === strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- This is validating. return; } // Disable in all XLS (see the WP_Sitemaps_Renderer class which is responsible for rendering Sitemaps data to XML // in accordance with sitemap protocol). if ( isset( $_SERVER['REQUEST_URI'] ) && ( // phpcs:disable WordPress.Security.ValidatedSanitizedInput -- This is validating. str_contains( $_SERVER['REQUEST_URI'], '.xsl' ) || str_contains( $_SERVER['REQUEST_URI'], 'sitemap-stylesheet=index' ) || str_contains( $_SERVER['REQUEST_URI'], 'sitemap-stylesheet=sitemap' ) // phpcs:enable WordPress.Security.ValidatedSanitizedInput ) ) { return; } // Disable in all POST Requests. // phpcs:disable WordPress.Security.NonceVerification.Missing if ( ! empty( $_POST ) ) { return; } // Disable in customizer previews if ( is_customize_preview() ) { return; } // Disable in feeds, AJAX, Cron, XML. if ( is_feed() || wp_doing_ajax() || wp_doing_cron() || wp_is_xml_request() ) { return; } // Disable in sitemaps. if ( ! empty( get_query_var( 'sitemap' ) ) ) { return; } // Disable in AMP pages. if ( function_exists( 'amp_is_request' ) && amp_is_request() ) { return; } // Print the filtered script tags to the very end of the page. add_filter( 'jetpack_boost_output_filtering_last_buffer', array( $this, 'append_script_tags' ), 10, 1 ); // Handle exclusions. add_filter( 'script_loader_tag', array( $this, 'handle_exclusions' ), 10, 2 ); $this->output_filter->add_callback( array( $this, 'handle_output_stream' ) ); } /** * Remove all inline and external <script> tags from the default output. * * @param string $buffer_start First part of the buffer. * @param string $buffer_end Second part of the buffer. * * For explanation on why there are two parts of a buffer here, see * the comments and examples in the Output_Filter class. * * @return array Parts of the buffer. */ public function handle_output_stream( $buffer_start, $buffer_end ) { $joint_buffer = $this->ignore_exclusion_scripts( $buffer_start . $buffer_end ); $script_tags = $this->get_script_tags( $joint_buffer ); if ( ! $script_tags ) { if ( $this->is_opened_script ) { // We have an opened script tag, move everything to the second buffer to avoid printing it to the page. // We will do this until the </script> closing tag is encountered. return array( '', $joint_buffer ); } // No script tags detected, return both chunks unaltered. return array( $buffer_start, $buffer_end ); } // Makes sure all whole <script>...</script> tags are in $buffer_start. list( $buffer_start, $buffer_end ) = $this->recalculate_buffer_split( $joint_buffer, $script_tags ); foreach ( $script_tags as $script_tag ) { $this->buffered_script_tags[] = $script_tag[0]; $buffer_start = str_replace( $script_tag[0], '', $buffer_start ); } // Detect a lingering opened script. $this->is_opened_script = $this->is_opened_script( $buffer_start . $buffer_end ); return array( $buffer_start, $buffer_end ); } /** * Matches <script> tags with their content in a string buffer. * * @param string $buffer Captured piece of output buffer. * * @return array */ protected function get_script_tags( $buffer ) { $regex = sprintf( '~<script(?![^>]*%s=(?<q>["\']*)%s\k<q>)([^>]*)>[\s\S]*?<\/script>~si', preg_quote( $this->ignore_attribute, '~' ), preg_quote( $this->ignore_value, '~' ) ); preg_match_all( $regex, $buffer, $script_tags, PREG_OFFSET_CAPTURE ); // No script_tags in the joint buffer. if ( empty( $script_tags[0] ) ) { return array(); } return apply_filters( 'jetpack_boost_render_blocking_js_exclude_scripts', $script_tags[0] ); } /** * Adds the ignore attribute to scripts in the exclusion list. * * @param string $buffer Captured piece of output buffer. * * @return string */ protected function ignore_exclusion_scripts( $buffer ) { $exclusions = array( // Scripts inside HTML comments. '~<!--.*?-->~si', // Scripts with types that do not execute complex code. Moving them down can be dangerous // and does not benefit performance. Includes types: application/json, application/ld+json and importmap. '~<script\s+[^\>]*type=(?<q>["\']*)(application\/(ld\+)?json|importmap)\k<q>.*?>.*?<\/script>~si', ); return preg_replace_callback( $exclusions, function ( $script_match ) { return str_replace( '<script', sprintf( '<script %s="%s"', esc_html( $this->ignore_attribute ), esc_attr( $this->ignore_value ) ), $script_match[0] ); }, $buffer ); } /** * Splits the buffer into two parts. * * First part contains all whole <script> tags, the second part * contains the rest of the buffer. * * @param string $buffer Captured piece of output buffer. * @param array $script_tags Matched <script> tags. * * @return array */ protected function recalculate_buffer_split( $buffer, $script_tags ) { $last_script_tag_index = count( $script_tags ) - 1; $last_script_tag_end_position = strrpos( $buffer, $script_tags[ $last_script_tag_index ][0] ) + strlen( $script_tags[ $last_script_tag_index ][0] ); // Bundle all script tags into the first buffer. $buffer_start = substr( $buffer, 0, $last_script_tag_end_position ); // Leave the rest of the data in the second buffer. $buffer_end = substr( $buffer, $last_script_tag_end_position ); return array( $buffer_start, $buffer_end ); } /** * Insert the buffered script tags just before the body tag if possible in the last buffer * otherwise at append it at the end. * * @param string $buffer String buffer. * * @return string */ public function append_script_tags( $buffer ) { if ( str_contains( $buffer, '</body>' ) ) { return str_replace( '</body>', implode( '', $this->buffered_script_tags ) . '</body>', $buffer ); } return $buffer . implode( '', $this->buffered_script_tags ); } /** * Exclude certain scripts from being processed by this class. * * @param string $tag <script> opening tag. * @param string $handle Script handle from register_ or enqueue_ methods. * * @return string */ public function handle_exclusions( $tag, $handle ) { $exclude_handles = apply_filters( 'jetpack_boost_render_blocking_js_exclude_handles', array() ); if ( ! in_array( $handle, $exclude_handles, true ) ) { return $tag; } return str_replace( '<script', sprintf( '<script %s="%s"', esc_html( $this->ignore_attribute ), esc_attr( $this->ignore_value ) ), $tag ); } /** * Detects an unclosed script tag in a buffer. * * @param string $buffer Joint buffer. * * @return bool */ public function is_opened_script( $buffer ) { $opening_tags_count = preg_match_all( '~<\s*script(?![^>]*%s="%s")([^>]*)>~', $buffer ); $closing_tags_count = preg_match_all( '~<\s*/script[^>]*>~', $buffer ); /** * This works, because the logic in `handle_output_stream` will never * allow an unpaired closing </script> tag to appear in the buffer. * * Open script tags are always kept in the buffer until their closing * tags eventually arrive as well. That means it's only possible to * encounter an unpaired opening <script> in a buffer, which is why * a simple comparison works. * * @todo What if there is a <!-- </script> --> comment? * @todo What happens when script tags are unclosed? */ return $opening_tags_count > $closing_tags_count; } public static function get_slug() { return 'render_blocking_js'; } }
projects/plugins/boost/app/modules/optimizations/critical-css/Critical_CSS.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Critical_CSS; use Automattic\Jetpack_Boost\Admin\Regenerate_Admin_Notice; use Automattic\Jetpack_Boost\Contracts\Changes_Page_Output; use Automattic\Jetpack_Boost\Contracts\Pluggable; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Admin_Bar_Compatibility; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_Invalidator; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_Storage; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Display_Critical_CSS; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Generator; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Source_Providers\Source_Providers; use Automattic\Jetpack_Boost\Lib\Premium_Features; class Critical_CSS implements Pluggable, Changes_Page_Output { /** * Critical CSS storage class instance. * * @var Critical_CSS_Storage */ protected $storage; /** * Critical CSS Provider Paths. * * @var Source_Providers */ protected $paths; /** * Prepare module. This is run irrespective of the module activation status. */ public function __construct() { $this->storage = new Critical_CSS_Storage(); $this->paths = new Source_Providers(); } public static function is_available() { return true !== Premium_Features::has_feature( Premium_Features::CLOUD_CSS ); } /** * This is only run if Critical CSS module has been activated. */ public function setup() { add_action( 'wp', array( $this, 'display_critical_css' ) ); add_filter( 'jetpack_boost_total_problem_count', array( $this, 'update_total_problem_count' ) ); add_filter( 'query_vars', array( '\Automattic\Jetpack_Boost\Lib\Critical_CSS\Generator', 'add_generate_query_action_to_list' ) ); Generator::init(); Critical_CSS_Invalidator::init(); CSS_Proxy::init(); // Admin Notices Regenerate_Admin_Notice::init(); return true; } public static function get_slug() { return 'critical_css'; } public function display_critical_css() { // Don't look for Critical CSS in the dashboard. if ( is_admin() ) { return; } // Don't display Critical CSS when generating Critical CSS. if ( Generator::is_generating_critical_css() ) { return; } // Don't show Critical CSS in customizer previews. if ( is_customize_preview() ) { return; } // Get the Critical CSS to show. $critical_css = $this->paths->get_current_request_css(); if ( ! $critical_css ) { return; } $display = new Display_Critical_CSS( $critical_css ); add_action( 'wp_head', array( $display, 'display_critical_css' ), 0 ); add_filter( 'style_loader_tag', array( $display, 'asynchronize_stylesheets' ), 10, 4 ); add_action( 'wp_footer', array( $display, 'onload_flip_stylesheets' ) ); // Ensure admin bar compatibility. Admin_Bar_Compatibility::init(); } public function update_total_problem_count( $count ) { return ( new Critical_CSS_State() )->has_errors() ? ++$count : $count; } }
projects/plugins/boost/app/modules/optimizations/critical-css/CSS_Proxy.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Critical_CSS; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State; /** * Add an ajax endpoint to proxy external CSS files. */ class CSS_Proxy { const NONCE_ACTION = 'jb-generate-proxy-nonce'; public static function init() { $instance = new self(); if ( is_admin() ) { add_action( 'wp_ajax_boost_proxy_css', array( $instance, 'handle_css_proxy' ) ); } } /** * AJAX handler to handle proxying of external CSS resources. */ public function handle_css_proxy() { // Verify valid nonce. if ( empty( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['nonce'] ), self::NONCE_ACTION ) ) { wp_die( '', 400 ); } // Make sure currently logged in as admin. if ( ! current_user_can( 'manage_options' ) ) { wp_die( '', 400 ); } // Reject any request made when not generating. if ( ! ( new Critical_CSS_State() )->is_requesting() ) { wp_die( '', 400 ); } // Validate URL and fetch. $proxy_url = filter_var( wp_unslash( isset( $_POST['proxy_url'] ) ? $_POST['proxy_url'] : null ), FILTER_VALIDATE_URL ); if ( ! wp_http_validate_url( $proxy_url ) ) { die( 'Invalid URL' ); } $response = wp_remote_get( $proxy_url ); if ( is_wp_error( $response ) ) { // TODO: Nicer error handling. die( 'error' ); } header( 'Content-type: text/css' ); // Outputting proxied CSS contents unescaped. // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo wp_strip_all_tags( $response['body'] ); die(); } }
projects/plugins/boost/app/modules/optimizations/page-cache/Page_Cache.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache; use Automattic\Jetpack\Status\Host; use Automattic\Jetpack_Boost\Contracts\Changes_Page_Output; use Automattic\Jetpack_Boost\Contracts\Has_Deactivate; use Automattic\Jetpack_Boost\Contracts\Pluggable; use Automattic\Jetpack_Boost\Modules\Modules_Index; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Settings; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Filesystem_Utils; class Page_Cache implements Pluggable, Has_Deactivate { /* * @var array - The errors that occurred when removing the cache. */ private $removal_errors = array(); /* * The signature used to identify the advanced-cache.php file owned by Jetpack Boost. */ const ADVANCED_CACHE_SIGNATURE = 'Boost Cache Plugin'; /** * The full signature including the current version, to verify the Advanced-cache file is current. */ const ADVANCED_CACHE_VERSION = 'v0.0.3'; /* * @var Boost_Cache_Settings - The settings for the page cache. */ private $settings; public function __construct() { $this->settings = Boost_Cache_Settings::get_instance(); } public function setup() { Garbage_Collection::setup(); add_action( 'jetpack_boost_module_status_updated', array( $this, 'handle_module_status_updated' ), 10, 2 ); add_action( 'jetpack_boost_critical_css_invalidated', array( $this, 'invalidate_cache' ) ); add_action( 'jetpack_boost_critical_css_generated', array( $this, 'invalidate_cache' ) ); } /** * Handles the module status updated event. * * @param string $module_slug The slug of the module that was updated. */ public function handle_module_status_updated( $module_slug, $status ) { // Get a list of modules that can change the HTML output. $output_changing_modules = Modules_Index::get_modules_implementing( Changes_Page_Output::class ); // Special case: don't clear when enabling Critical or Cloud CSS, as they will // be handled after generation. if ( $status === true ) { unset( $output_changing_modules['critical_css'] ); unset( $output_changing_modules['cloud_css'] ); } $slugs = array_keys( $output_changing_modules ); if ( in_array( $module_slug, $slugs, true ) ) { $this->invalidate_cache(); } } public function invalidate_cache() { $cache = new Boost_Cache(); $cache->get_storage()->invalidate( home_url(), Filesystem_Utils::DELETE_ALL ); } /** * Runs cleanup when the feature is deactivated. */ public static function deactivate() { Garbage_Collection::deactivate(); Boost_Cache_Settings::get_instance()->set( array( 'enabled' => false ) ); } public static function is_available() { // Disable Page Cache on Atomic. // It already has caching enabled. if ( ( new Host() )->is_woa_site() ) { return false; } return true; } public static function get_slug() { return 'page_cache'; } }
projects/plugins/boost/app/modules/optimizations/page-cache/Garbage_Collection.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Logger; class Garbage_Collection { const ACTION = 'jetpack_boost_cache_garbage_collection'; const INTERVAL_NAME = 'jetpack_boost_cache_gc_interval'; /** * Register hooks. */ public static function setup() { $cache = new Boost_Cache(); add_action( self::ACTION, array( $cache->get_storage(), 'garbage_collect' ) ); add_action( self::ACTION, array( Logger::class, 'delete_old_logs' ) ); } /** * Setup the garbage collection cron job. */ public static function activate() { self::setup(); if ( ! wp_next_scheduled( self::ACTION ) ) { wp_schedule_event( time(), 'hourly', self::ACTION ); } } /** * Remove the garbage collection cron job. */ public static function deactivate() { wp_clear_scheduled_hook( self::ACTION ); } }
projects/plugins/boost/app/modules/optimizations/page-cache/Page_Cache_Setup.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache; use Automattic\Jetpack_Boost\Lib\Analytics; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Error; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Settings; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Filesystem_Utils; class Page_Cache_Setup { /** * Runs setup steps and returns whether setup was successful or not. * @return bool|\WP_Error */ public static function run_setup() { $steps = array( 'verify_wp_content_writable', 'verify_permalink_setting', 'create_settings_file', 'create_advanced_cache', 'add_wp_cache_define', 'enable_caching', ); foreach ( $steps as $step ) { $result = self::$step(); if ( $result instanceof Boost_Cache_Error ) { Analytics::record_user_event( 'page_cache_setup_failed', array( 'error_code' => $result->get_error_code() ) ); return $result->to_wp_error(); } if ( is_wp_error( $result ) ) { Analytics::record_user_event( 'page_cache_setup_failed', array( 'error_code' => $result->get_error_code() ) ); return $result; } } Analytics::record_user_event( 'page_cache_setup_succeeded' ); return true; } /** * Enable caching step of setup. * * @return Boost_Cache_Error|true - True on success, error otherwise. */ private static function enable_caching() { $settings = Boost_Cache_Settings::get_instance(); return $settings->set( array( 'enabled' => true ) ); } /** * Returns true if the wp-content directory is writeable. */ private static function verify_wp_content_writable() { $filename = WP_CONTENT_DIR . '/' . uniqid() . '.txt'; $result = @file_put_contents( $filename, 'test' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents, WordPress.PHP.NoSilencedErrors.Discouraged wp_delete_file( $filename ); if ( $result === false ) { return new \WP_Error( 'wp-content-not-writable' ); } return true; } /** * Returns true if WordPress is using a proper permalink setup. WP_Error if not. */ private static function verify_permalink_setting() { global $wp_rewrite; if ( ! $wp_rewrite || ! $wp_rewrite->using_permalinks() ) { return new \WP_Error( 'not-using-permalinks' ); } } /** * Create a settings file, if one does not already exist. * * @return bool|\WP_Error */ private static function create_settings_file() { $result = Boost_Cache_Settings::get_instance()->create_settings_file(); return $result; } /** * Creates the advanced-cache.php file. * * Returns true if the files were setup correctly, or WP_Error if there was a problem. * * @return bool|\WP_Error */ private static function create_advanced_cache() { $advanced_cache_filename = WP_CONTENT_DIR . '/advanced-cache.php'; if ( file_exists( $advanced_cache_filename ) ) { $content = file_get_contents( $advanced_cache_filename ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents if ( strpos( $content, 'WP SUPER CACHE' ) !== false ) { return new \WP_Error( 'advanced-cache-for-super-cache' ); } if ( strpos( $content, Page_Cache::ADVANCED_CACHE_SIGNATURE ) === false ) { return new \WP_Error( 'advanced-cache-incompatible' ); } if ( strpos( $content, Page_Cache::ADVANCED_CACHE_VERSION ) !== false ) { // The version and signature match. return true; } } $plugin_dir_name = untrailingslashit( str_replace( JETPACK_BOOST_PLUGIN_FILENAME, '', JETPACK_BOOST_PLUGIN_BASE ) ); $boost_cache_filename = WP_CONTENT_DIR . '/plugins/' . $plugin_dir_name . '/app/modules/optimizations/page-cache/pre-wordpress/Boost_Cache.php'; if ( ! file_exists( $boost_cache_filename ) ) { return new \WP_Error( 'boost-cache-file-not-found' ); } $contents = '<?php // ' . Page_Cache::ADVANCED_CACHE_SIGNATURE . ' - ' . Page_Cache::ADVANCED_CACHE_VERSION . ' if ( ! file_exists( \'' . $boost_cache_filename . '\' ) ) { return; } require_once( \'' . $boost_cache_filename . '\'); $boost_cache = new Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache(); $boost_cache->init_actions(); $boost_cache->serve(); '; $write_advanced_cache = Filesystem_Utils::write_to_file( $advanced_cache_filename, $contents ); if ( $write_advanced_cache instanceof Boost_Cache_Error ) { return new \WP_Error( 'unable-to-write-to-advanced-cache', $write_advanced_cache->get_error_code() ); } self::clear_opcache( $advanced_cache_filename ); return true; } /** * Adds the WP_CACHE define to wp-config.php */ private static function add_wp_cache_define() { $config_file = self::find_wp_config(); if ( $config_file === false ) { return new \WP_Error( 'wp-config-not-found' ); } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents $content = file_get_contents( $config_file ); if ( preg_match( '#^\s*define\s*\(\s*[\'"]WP_CACHE[\'"]#m', $content ) === 1 ) { /* * wp-settings.php checks "if ( WP_CACHE )" so it may be truthy and * not === true to pass that check. * Later, it is defined as false in default-constants.php, but * it may have been defined manually as true using "true", 1, or "1" * in wp-config.php. */ if ( defined( 'WP_CACHE' ) && ! WP_CACHE ) { return new \WP_Error( 'wp-cache-defined-not-true' ); } return true; // WP_CACHE already added. } $content = preg_replace( '#^<\?php#', '<?php define( \'WP_CACHE\', true ); // ' . Page_Cache::ADVANCED_CACHE_SIGNATURE, $content ); $result = Filesystem_Utils::write_to_file( $config_file, $content ); if ( $result instanceof Boost_Cache_Error ) { return new \WP_Error( 'wp-config-not-writable' ); } self::clear_opcache( $config_file ); return true; } /** * Removes the advanced-cache.php file and the WP_CACHE define from wp-config.php * Fired when the plugin is deactivated. */ public static function deactivate() { self::delete_advanced_cache(); self::delete_wp_cache_constant(); return true; } /* * Removes the boost-cache directory, removing all cached files and the config file. * Fired when the plugin is uninstalled. */ public static function uninstall() { self::deactivate(); $result = Filesystem_Utils::delete_directory( WP_CONTENT_DIR . '/boost-cache', Filesystem_Utils::DELETE_ALL ); if ( $result instanceof Boost_Cache_Error ) { return $result->to_wp_error(); } return true; } /** * Deletes the file advanced-cache.php if it exists. */ public static function delete_advanced_cache() { $advanced_cache_filename = WP_CONTENT_DIR . '/advanced-cache.php'; if ( ! file_exists( $advanced_cache_filename ) ) { return; } $content = file_get_contents( $advanced_cache_filename ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents if ( strpos( $content, Page_Cache::ADVANCED_CACHE_SIGNATURE ) !== false ) { wp_delete_file( $advanced_cache_filename ); } self::clear_opcache( $advanced_cache_filename ); } /** * Deletes the WP_CACHE define from wp-config.php * * @return WP_Error if an error occurred. */ public static function delete_wp_cache_constant() { $config_file = self::find_wp_config(); if ( $config_file === false ) { return; } $lines = file( $config_file ); $found = false; foreach ( $lines as $key => $line ) { if ( preg_match( '#define\s*\(\s*[\'"]WP_CACHE[\'"]#', $line ) === 1 && strpos( $line, Page_Cache::ADVANCED_CACHE_SIGNATURE ) !== false ) { unset( $lines[ $key ] ); $found = true; } } if ( ! $found ) { return; } $content = implode( '', $lines ); Filesystem_Utils::write_to_file( $config_file, $content ); self::clear_opcache( $config_file ); } /** * Find location of wp-config.php file. * * @return string|false - The path to the wp-config.php file, or false if it was not found. */ private static function find_wp_config() { if ( file_exists( ABSPATH . 'wp-config.php' ) ) { return ABSPATH . 'wp-config.php'; } elseif ( file_exists( dirname( ABSPATH ) . '/wp-config.php' ) && ! file_exists( dirname( ABSPATH ) . '/wp-settings.php' ) ) { // While checking one directory up, check for wp-settings.php as well similar to WordPress core, to avoid nested WordPress installations. return dirname( ABSPATH ) . '/wp-config.php'; } return false; } /** * Clear opcache for a file. */ private static function clear_opcache( $file ) { if ( function_exists( 'opcache_invalidate' ) ) { opcache_invalidate( $file, true ); } } }
projects/plugins/boost/app/modules/optimizations/page-cache/data-sync-actions/run-setup.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Data_Sync_Actions; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Data_Sync_Action; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Garbage_Collection; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Page_Cache_Setup; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Settings; /** * Critical CSS Action: request regeneration. */ class Run_Setup implements Data_Sync_Action { /** * Handles the action logic. * * @param mixed $_data JSON Data passed to the action. * @param \WP_REST_Request $_request The request object. */ public function handle( $_data, $_request ) { $setup_result = Page_Cache_Setup::run_setup(); if ( is_wp_error( $setup_result ) ) { return $setup_result; } Garbage_Collection::activate(); Boost_Cache_Settings::get_instance()->set( array( 'enabled' => true ) ); return true; } }
projects/plugins/boost/app/modules/optimizations/page-cache/data-sync-actions/clear-page-cache.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Data_Sync_Actions; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Data_Sync_Action; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache; /** * Page Cache: Clear page cache */ class Clear_Page_Cache implements Data_Sync_Action { /** * Handles the action logic. * * @param mixed $_data JSON Data passed to the action. * @param \WP_REST_Request $_request The request object. */ public function handle( $_data, $_request ) { $cache = new Boost_Cache(); $delete = $cache->delete_cache(); if ( $delete === null || is_wp_error( $delete ) ) { return array( 'message' => __( 'Cache already cleared.', 'jetpack-boost' ), ); } if ( $delete ) { return array( 'message' => __( 'Cache cleared.', 'jetpack-boost' ), ); } return new \WP_Error( 'unable-to-clear-cache', __( 'Unable to clear cache.', 'jetpack-boost' ) ); } }
projects/plugins/boost/app/modules/optimizations/page-cache/pre-wordpress/Boost_Cache_Utils.php
<?php /* * This file may be called before WordPress is fully initialized. See the README file for info. */ namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress; class Boost_Cache_Utils { /** * Performs a deep string replace operation to ensure the values in $search are no longer present. * Copied from wp-includes/formatting.php * * Repeats the replacement operation until it no longer replaces anything to remove "nested" values * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that * str_replace would return * * @param string|array $search The value being searched for, otherwise known as the needle. * An array may be used to designate multiple needles. * @param string $subject The string being searched and replaced on, otherwise known as the haystack. * @return string The string with the replaced values. */ public static function deep_replace( $search, $subject ) { $subject = (string) $subject; $count = 1; while ( $count ) { $subject = str_replace( $search, '', $subject, $count ); } return $subject; } public static function trailingslashit( $string ) { return rtrim( $string, '/' ) . '/'; } /** * Returns a sanitized directory path. * @param string $path - The path to sanitize. * @return string */ public static function sanitize_file_path( $path ) { $path = self::trailingslashit( $path ); $path = self::deep_replace( array( '..', '\\' ), preg_replace( '/[ <>\'\"\r\n\t\(\)]/', '', preg_replace( '/(\?.*)?(#.*)?$/', '', $path ) ) ); return $path; } /** * Normalize the request uri so it can be used for caching purposes. * It removes the query string and the trailing slash, and characters * that might cause problems with the filesystem. * * **THIS DOES NOT SANITIZE THE VARIABLE IN ANY WAY.** * Only use it for comparison purposes or to generate an MD5 hash. * * @param string $request_uri - The request uri to normalize. * @return string - The normalized request uri. */ public static function normalize_request_uri( $request_uri ) { // get path from request uri $request_uri = parse_url( $request_uri, PHP_URL_PATH ); // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url if ( empty( $request_uri ) ) { $request_uri = '/'; } elseif ( substr( $request_uri, -1 ) !== '/' && ! is_file( ABSPATH . $request_uri ) ) { $request_uri .= '/'; } return $request_uri; } /** * Checks if the post type is public. * * @param WP_Post $post - The post to check. * @return bool - True if the post type is public. */ public static function is_visible_post_type( $post ) { $post_type = is_a( $post, 'WP_Post' ) ? get_post_type_object( $post->post_type ) : null; if ( empty( $post_type ) || ! $post_type->public ) { return false; } return true; } }
projects/plugins/boost/app/modules/optimizations/page-cache/pre-wordpress/Filesystem_Utils.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress; class Filesystem_Utils { const DELETE_ALL = 'delete-all'; // delete all files and directories in a given directory, recursively. const DELETE_FILE = 'delete-single'; // delete a single file or recursively delete a single directory in a given directory. const DELETE_FILES = 'delete-files'; // delete all files in a given directory. /** * Recursively delete a directory. * @param string $path - The directory to delete. * @param bool $type - The type of delete. DELETE_FILES to delete all files in the given directory. DELETE_ALL to delete everything in the given directory, recursively. * @return bool|Boost_Cache_Error */ public static function delete_directory( $path, $type ) { Logger::debug( "delete directory: $path $type" ); $path = realpath( $path ); if ( ! $path ) { // translators: %s is the directory that does not exist. return new Boost_Cache_Error( 'directory-missing', 'Directory does not exist: ' . $path ); // realpath returns false if a file does not exist. } // make sure that $dir is a directory inside WP_CONTENT . '/boost-cache/'; if ( self::is_boost_cache_directory( $path ) === false ) { // translators: %s is the directory that is invalid. return new Boost_Cache_Error( 'invalid-directory', 'Invalid directory %s' . $path ); } if ( ! is_dir( $path ) ) { return new Boost_Cache_Error( 'not-a-directory', 'Not a directory' ); } switch ( $type ) { case self::DELETE_ALL: // delete all files and directories in the given directory. $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $path, \RecursiveDirectoryIterator::SKIP_DOTS ) ); foreach ( $iterator as $file ) { if ( $file->isDir() ) { Logger::debug( 'rmdir: ' . $file->getPathname() ); @rmdir( $file->getPathname() ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir, WordPress.PHP.NoSilencedErrors.Discouraged } elseif ( $file->getFilename() !== 'index.html' ) { // Delete all files except index.html. index.html is used to prevent directory listing. Logger::debug( 'unlink: ' . $file->getPathname() ); @unlink( $file->getPathname() ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink, WordPress.PHP.NoSilencedErrors.Discouraged } } @rmdir( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir, WordPress.PHP.NoSilencedErrors.Discouraged, break; case self::DELETE_FILES: // delete all files in the given directory. // Files to delete are all files in the given directory, except index.html. index.html is used to prevent directory listing. $files = array_diff( scandir( $path ), array( '.', '..', 'index.html' ) ); foreach ( $files as $file ) { $file = $path . '/' . $file; if ( is_file( $file ) ) { Logger::debug( "unlink: $file" ); @unlink( $file ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.unlink_unlink } } break; } return true; } /** * Returns true if the given directory is inside the boost-cache directory. * @param string $dir - The directory to check. * @return bool */ public static function is_boost_cache_directory( $dir ) { $dir = Boost_Cache_Utils::sanitize_file_path( $dir ); return strpos( $dir, WP_CONTENT_DIR . '/boost-cache' ) !== false; } /** * Given a request_uri and its parameters, return the filename to use for this cached data. Does not include the file path. * * @param array $parameters - An associative array of all the things that make this request special/different. Includes GET parameters and COOKIEs normally. */ public static function get_request_filename( $parameters ) { $key_components = apply_filters( 'boost_cache_key_components', $parameters ); return md5( json_encode( $key_components ) ) . '.html'; // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode } /** * Recursively garbage collect a directory. * * @param string $directory - The directory to garbage collect. * @param int $file_ttl - Specify number of seconds after which a file is considered expired. * @return int - The number of files deleted. */ public static function delete_expired_files( $directory, $file_ttl ) { clearstatcache(); $count = 0; $now = time(); $handle = is_readable( $directory ) && is_dir( $directory ) ? opendir( $directory ) : false; // Could not open directory, exit early. if ( ! $handle ) { return $count; } // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition while ( false !== ( $file = readdir( $handle ) ) ) { if ( $file === '.' || $file === '..' || $file === 'index.html' ) { // Skip and continue to next file continue; } $file_path = $directory . '/' . $file; if ( ! file_exists( $file_path ) ) { // File doesn't exist, skip and continue to next file continue; } // Handle directories recursively. if ( is_dir( $file_path ) ) { $count += self::delete_expired_files( $file_path, $file_ttl ); continue; } $filemtime = filemtime( $file_path ); $expired = ( $filemtime + $file_ttl ) <= $now; if ( $expired ) { if ( self::delete_file( $file_path ) ) { ++$count; } else { Logger::debug( 'Could not delete file: ' . $file_path ); } } } closedir( $handle ); // If the directory is empty after processing it's files, delete it. $is_dir_empty = self::is_dir_empty( $directory ); if ( $is_dir_empty instanceof Boost_Cache_Error ) { Logger::debug( 'Could not check directory emptiness: ' . $is_dir_empty->get_error_message() ); return $count; } if ( $is_dir_empty === true ) { // Directory is considered empty even if it has an index.html file. Delete it it first. self::delete_file( $directory . '/index.html' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir, WordPress.PHP.NoSilencedErrors.Discouraged @rmdir( $directory ); } return $count; } /** * Creates the directory if it doesn't exist. * * @param string $path - The path to the directory to create. */ public static function create_directory( $path ) { if ( ! is_dir( $path ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.dir_mkdir_dirname, WordPress.WP.AlternativeFunctions.file_system_operations_mkdir, WordPress.PHP.NoSilencedErrors.Discouraged $dir_created = @mkdir( $path, 0755, true ); if ( $dir_created ) { self::create_empty_index_files( $path ); } return $dir_created; } return true; } /** * Create an empty index.html file in the given directory. * This is done to prevent directory listing. */ private static function create_empty_index_files( $path ) { if ( self::is_boost_cache_directory( $path ) ) { self::write_to_file( $path . '/index.html', '' ); // Create an empty index.html file in the parent directory as well. self::create_empty_index_files( dirname( $path ) ); } } /** * Delete a file. * * @param string $file_path - The file to delete. * @return bool - True if the file was deleted, false otherwise. */ public static function delete_file( $file_path ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable $deletable = is_writable( $file_path ); if ( $deletable ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink return unlink( $file_path ); } return false; } /** * Check if a directory is empty. * * @param string $dir - The directory to check. */ public static function is_dir_empty( $dir ) { if ( ! is_readable( $dir ) ) { return new Boost_Cache_Error( 'directory_not_readable', 'Directory is not readable' ); } $files = array_diff( scandir( $dir ), array( '.', '..', 'index.html' ) ); return empty( $files ); } /** * Writes data to a file. * This creates a temporary file first, then renames the file to the final filename. * This is done to prevent the file from being read while it is being written to. * * @param string $filename - The filename to write to. * @param string $data - The data to write to the file. * @return bool|Boost_Cache_Error - true on sucess or Boost_Cache_Error on failure. */ public static function write_to_file( $filename, $data ) { $tmp_filename = $filename . uniqid( uniqid(), true ) . '.tmp'; // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents, WordPress.PHP.NoSilencedErrors.Discouraged if ( false === @file_put_contents( $tmp_filename, $data ) ) { return new Boost_Cache_Error( 'could-not-write', 'Could not write to tmp file: ' . $tmp_filename ); } // phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename if ( ! rename( $tmp_filename, $filename ) ) { return new Boost_Cache_Error( 'could-not-rename', 'Could not rename tmp file to final file: ' . $filename ); } return true; } }
projects/plugins/boost/app/modules/optimizations/page-cache/pre-wordpress/Logger.php
<?php /* * This file may be called before WordPress is fully initialized. See the README file for info. */ namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress; /** * A utility that manages logging for the boost cache. */ class Logger { /** * The singleton instance of the logger. */ private static $instance = null; /** * The header to place on top of every log file. */ const LOG_HEADER = "<?php die(); // This file is not intended to be accessed directly. ?>\n\n"; /** * The directory where log files are stored. */ const LOG_DIRECTORY = WP_CONTENT_DIR . '/boost-cache/logs'; /** * The Process Identifier used by this Logger instance. */ private $pid = null; /** * Get the singleton instance of the logger. */ public static function get_instance() { if ( self::$instance !== null ) { return self::$instance; } $instance = new Logger(); $prepared_log_file = $instance->prepare_file(); if ( $prepared_log_file instanceof Boost_Cache_Error ) { return $prepared_log_file; } self::$instance = $instance; return $instance; } private function __construct() { if ( function_exists( 'getmypid' ) ) { $this->pid = getmypid(); } else { // Where PID is not available, use the microtime of the first log of the session. $this->pid = microtime( true ); } } /** * Ensure that the log file exists, and if not, create it. */ private function prepare_file() { $log_file = $this->get_log_file(); if ( file_exists( $log_file ) ) { return true; } $directory = dirname( $log_file ); if ( ! Filesystem_Utils::create_directory( $directory ) ) { return new Boost_Cache_Error( 'could-not-create-log-dir', 'Could not create boost cache log directory' ); } return Filesystem_Utils::write_to_file( $log_file, self::LOG_HEADER ); } /** * Add a debug message to the log file after doing necessary checks. */ public static function debug( $message ) { $settings = Boost_Cache_Settings::get_instance(); if ( ! $settings->get_logging() ) { return; } $logger = self::get_instance(); // TODO: Check to make sure that current request IP is allowed to create logs. if ( $logger instanceof Boost_Cache_Error ) { return; } $logger->log( $message ); } /** * Writes a message to the log file. * * @param string $message - The message to write to the log file. */ public function log( $message ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash $request_uri = htmlspecialchars( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '<unknown request uri>', ENT_QUOTES, 'UTF-8' ); // don't log the ABSPATH constant. Logs may be copied to a public forum. $message = str_replace( ABSPATH, '[...]/', $message ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode $line = json_encode( array( 'time' => gmdate( 'Y-m-d H:i:s' ), 'pid' => $this->pid, 'uri' => $request_uri, 'msg' => $message, 'uid' => uniqid(), // Uniquely identify this log line. ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log( $line . PHP_EOL, 3, $this->get_log_file() ); } /** * Reads the log file and returns the contents. * * @return string */ public static function read() { $instance = self::get_instance(); // If we failed to set up a Logger instance (e.g.: unwriteable directory), return the error as log content. if ( $instance instanceof Boost_Cache_Error ) { return $instance->get_error_message(); } $log_file = $instance->get_log_file(); if ( ! file_exists( $log_file ) ) { return ''; } // Get the content after skipping the LOG_HEADER. // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents $logs = file_get_contents( $log_file, false, null, strlen( self::LOG_HEADER ) ) ?? ''; $logs = explode( PHP_EOL, $logs ); $lines = array(); foreach ( $logs as $log ) { $line = json_decode( $log, true ); if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $line ) ) { continue; } // The current log format requires time, pid, uri, and msg. if ( ! isset( $line['time'] ) || ! isset( $line['pid'] ) || ! isset( $line['uri'] ) || ! isset( $line['msg'] ) ) { continue; } $info = sprintf( '[%s] [%s] ', $line['time'], $line['pid'] ); $formatted = $info . $line['uri']; // Add msg to the next line offset by the length of the info string. $formatted .= PHP_EOL . str_repeat( ' ', strlen( $info ) ) . $line['msg']; $lines[] = $formatted; } return implode( PHP_EOL, $lines ); } /** * Returns the path to the log file. * * @return string */ private static function get_log_file() { $today = gmdate( 'Y-m-d' ); return self::LOG_DIRECTORY . "/log-{$today}.log.php"; } public static function delete_old_logs() { Filesystem_Utils::delete_expired_files( self::LOG_DIRECTORY, 24 * 60 * 60 ); } }
projects/plugins/boost/app/modules/optimizations/page-cache/pre-wordpress/Boost_Cache_Settings.php
<?php /* * This file may be called before WordPress is fully initialized. See the README file for info. */ namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress; /* * Cache settings class. * Settings are stored in a file in the boost-cache directory. */ class Boost_Cache_Settings { private static $instance = null; private $settings = array(); private $config_file_path; private $config_file; /** * An uninitialized config holds these settings. */ private $default_settings = array( 'enabled' => false, 'bypass_patterns' => array(), 'logging' => false, ); private function __construct() { $this->config_file_path = WP_CONTENT_DIR . '/boost-cache/'; $this->config_file = $this->config_file_path . 'config.php'; } /** * Gets the instance of the class. * * @return Boost_Cache_Settings The instance of the class. */ public static function get_instance() { if ( self::$instance === null ) { self::$instance = new Boost_Cache_Settings(); self::$instance->init_settings(); } return self::$instance; } /** * Ensure a settings file exists, if one isn't there already. * @return mixed - True on success, or a Boost_Cache_Error on failure. */ public function create_settings_file() { if ( ! file_exists( $this->config_file_path ) ) { if ( ! Filesystem_Utils::create_directory( $this->config_file_path ) ) { return new Boost_Cache_Error( 'failed-settings-write', 'Failed to create settings directory at ' . $this->config_file_path ); } } if ( ! file_exists( $this->config_file ) ) { $write_result = $this->set( $this->default_settings ); if ( $write_result instanceof Boost_Cache_Error ) { return $write_result; } } return true; } /** * If an error occurs while reading the options, it will be impossible to ever log this to the Boost Cache logs. * So, if WP_DEBUG is enabled write it to the error_log instead. * * @param string $message - The message to log. */ private function log_init_error( $message ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } } /* * Load the settings from the config file, if available. Falls back to defaults if not. */ private function init_settings() { $this->settings = $this->default_settings; // If no settings file exists yet, don't try to create one until we are writing a value. if ( ! file_exists( $this->config_file ) ) { return; } $lines = @file( $this->config_file ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged if ( empty( $lines ) || count( $lines ) < 4 ) { $this->log_init_error( 'Invalid config file at ' . $this->config_file ); return; } $file_settings = null; foreach ( $lines as $line ) { if ( strpos( $line, '{' ) !== false ) { $file_settings = json_decode( $line, true ); break; } } if ( ! is_array( $file_settings ) ) { $this->log_init_error( 'Invalid config file at ' . $this->config_file ); return false; } $this->settings = $file_settings; } /* * Returns the value of the given setting. * * @param string $setting - The setting to get. * @return mixed - The value of the setting, or the default if the setting does not exist. */ public function get( $setting, $default = false ) { if ( ! isset( $this->settings[ $setting ] ) ) { return $default; } return $this->settings[ $setting ]; } /* * Returns true if the cache is enabled. * * @return bool */ public function get_enabled() { return $this->get( 'enabled', false ); } /* * Returns an array of URLs that should not be cached. * * @return array */ public function get_bypass_patterns() { return $this->get( 'bypass_patterns', array() ); } /** * Returns whether logging is enabled or not. * * @return bool */ public function get_logging() { return $this->get( 'logging', false ); } /* * Sets the given settings, and saves them to the config file. * @param array $settings - The settings to set in a key => value associative * array. This will be merged with the existing settings. * Example: * $result = $this->set( array( 'enabled' => true ) ); * * @return mixed - true if the settings were saved, Boost_Cache_Error otherwise. */ public function set( $settings ) { // If the settings file does not exist, attempt to create one. if ( ! file_exists( $this->config_file_path ) ) { $result = $this->create_settings_file(); if ( $result instanceof Boost_Cache_Error ) { return $result; } } if ( ! is_writable( $this->config_file_path ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable $error = new Boost_Cache_Error( 'failed-settings-write', 'Could not write to the config file at ' . $this->config_file_path ); Logger::debug( $error->get_error_message() ); return $error; } $this->settings = array_merge( $this->settings, $settings ); $contents = "<?php die();\n/*\n * Configuration data for Jetpack Boost Cache. Do not edit.\n" . json_encode( $this->settings ) . "\n */"; // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode $result = Filesystem_Utils::write_to_file( $this->config_file, $contents ); if ( $result instanceof Boost_Cache_Error ) { Logger::debug( $result->get_error_message() ); return new Boost_Cache_Error( 'failed-settings-write', 'Failed to write settings file: ' . $result->get_error_message() ); } return true; } }
projects/plugins/boost/app/modules/optimizations/page-cache/pre-wordpress/Boost_Cache.php
<?php /* * This file is loaded by advanced-cache.php, and so cannot rely on autoloading. */ namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress; /* * Require all pre-wordpress files here. These files aren't autoloaded as they are loaded before WordPress is fully initialized. * pre-wordpress files assume all other pre-wordpress files are loaded here. */ require_once __DIR__ . '/Boost_Cache_Actions.php'; require_once __DIR__ . '/Boost_Cache_Error.php'; require_once __DIR__ . '/Boost_Cache_Settings.php'; require_once __DIR__ . '/Boost_Cache_Utils.php'; require_once __DIR__ . '/Filesystem_Utils.php'; require_once __DIR__ . '/Logger.php'; require_once __DIR__ . '/Request.php'; require_once __DIR__ . '/storage/Storage.php'; require_once __DIR__ . '/storage/File_Storage.php'; // Define how many seconds the cache should last for each cached page. if ( ! defined( 'JETPACK_BOOST_CACHE_DURATION' ) ) { define( 'JETPACK_BOOST_CACHE_DURATION', HOUR_IN_SECONDS ); } class Boost_Cache { /** * @var Boost_Cache_Settings - The settings for the page cache. */ private $settings; /** * @var Storage\Storage - The storage system used by Boost Cache. */ private $storage; /** * @var Request - The request object that provides utility for the current request. */ private $request = null; /** * @param $storage - Optionally provide a Boost_Cache_Storage subclass to handle actually storing and retrieving cached content. Defaults to a new instance of File_Storage. */ public function __construct( $storage = null ) { $this->settings = Boost_Cache_Settings::get_instance(); $home = isset( $_SERVER['HTTP_HOST'] ) ? strtolower( $_SERVER['HTTP_HOST'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash $this->storage = $storage ?? new Storage\File_Storage( $home ); $this->request = Request::current(); } /** * Initialize the actions for the cache. */ public function init_actions() { add_action( 'transition_post_status', array( $this, 'delete_on_post_transition' ), 10, 3 ); add_action( 'transition_comment_status', array( $this, 'delete_on_comment_transition' ), 10, 3 ); add_action( 'comment_post', array( $this, 'delete_on_comment_post' ), 10, 3 ); add_action( 'edit_comment', array( $this, 'delete_on_comment_edit' ), 10, 2 ); add_action( 'switch_theme', array( $this, 'delete_cache' ) ); add_action( 'wp_trash_post', array( $this, 'delete_on_post_trash' ), 10, 2 ); add_filter( 'wp_php_error_message', array( $this, 'disable_caching_on_error' ) ); } /** * Serve the cached page if it exists, otherwise start output buffering. */ public function serve() { if ( ! $this->settings->get_enabled() || ! $this->request->is_cacheable() ) { return; } if ( ! $this->serve_cached() ) { $this->ob_start(); } } /** * Get the storage instance used by Boost Cache. * * @return Storage\Storage */ public function get_storage() { return $this->storage; } /** * Serve cached content, if any is available for the current request. Will terminate if it does so. * Otherwise, returns false. */ public function serve_cached() { if ( ! $this->request->is_cacheable() ) { return false; } $cached = $this->storage->read( $this->request->get_uri(), $this->request->get_parameters() ); if ( is_string( $cached ) ) { $this->send_header( 'X-Jetpack-Boost-Cache: hit' ); Logger::debug( 'Serving cached page' ); echo $cached; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped die(); } $this->send_header( 'X-Jetpack-Boost-Cache: miss' ); return false; } private function send_header( $header ) { if ( ! headers_sent() ) { header( $header ); } } /** * Starts output buffering and sets the callback to save the cache file. * * @return bool - false if page is not cacheable. */ public function ob_start() { if ( ! $this->request->is_cacheable() ) { return false; } ob_start( array( $this, 'ob_callback' ) ); } /** * Callback function from output buffer. This function saves the output * buffer to a cache file and then returns the buffer so PHP will send it * to the browser. * * @param string $buffer - The output buffer to save to the cache file. * @return string - The output buffer. */ public function ob_callback( $buffer ) { if ( strlen( $buffer ) > 0 && $this->request->is_cacheable() ) { if ( false === stripos( $buffer, '</html>' ) ) { Logger::debug( 'Closing HTML tag not found, not caching' ); return $buffer; } $result = $this->storage->write( $this->request->get_uri(), $this->request->get_parameters(), $buffer ); if ( $result instanceof Boost_Cache_Error ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf Logger::debug( 'Error writing cache file: ' . $result->get_error_message() ); } else { Logger::debug( 'Cache file created' ); } } return $buffer; } /** * Delete the cache for the front page and paged archives. * This is called when a post is edited, deleted, or published. * * @param WP_Post $post - The post that should be deleted. */ public function delete_cache_for_front_page() { if ( get_option( 'show_on_front' ) === 'page' ) { $front_page_id = get_option( 'page_on_front' ); // static page if ( $front_page_id ) { Logger::debug( 'delete_cache_for_front_page: deleting front page cache' ); $this->delete_cache_for_post( get_post( $front_page_id ) ); } $posts_page_id = get_option( 'page_for_posts' ); // posts page if ( $posts_page_id ) { Logger::debug( 'delete_cache_for_front_page: deleting posts page cache' ); $this->delete_cache_for_post( get_post( $posts_page_id ) ); } } else { $this->storage->invalidate( home_url(), Filesystem_Utils::DELETE_FILES ); Logger::debug( 'delete front page cache ' . Boost_Cache_Utils::normalize_request_uri( home_url() ) ); } } /** * Delete the cache for the given post. * * @param int $post_id - The ID of the post to delete the cache for. */ public function delete_cache_by_post_id( $post_id ) { $post = get_post( (int) $post_id ); if ( $post ) { $this->delete_cache_for_post( $post ); } } /** * Delete the cache for the post if the comment transitioned from one state to another. * * @param string $new_status - The new status of the comment. * @param string $old_status - The old status of the comment. * @param WP_Comment $comment - The comment that transitioned. */ public function delete_on_comment_transition( $new_status, $old_status, $comment ) { if ( $new_status === $old_status ) { return; } Logger::debug( "delete_on_comment_transition: $new_status, $old_status" ); if ( $new_status !== 'approved' && $old_status !== 'approved' ) { Logger::debug( 'delete_on_comment_transition: comment not approved' ); return; } $post = get_post( $comment->comment_post_ID ); $this->delete_cache_for_post( $post ); } /** * After editing a comment, delete the cache for the post if the comment is approved. * If changing state and editing, both actions will be called, but the cache will only be deleted once. * * @param int $comment_id - The id of the comment. * @param array $commentdata - The comment data. */ public function delete_on_comment_edit( $comment_id, $commentdata ) { $post = get_post( $commentdata['comment_post_ID'] ); if ( (int) $commentdata['comment_approved'] === 1 ) { $this->delete_cache_for_post( $post ); } } /** * After a comment is posted, delete the cache for the post if the comment is approved. * If the comment is not approved, only delete the cache for this post for this visitor. * * @param int $comment_id - The id of the comment. * @param int $comment_approved - The approval status of the comment. * @param array $commentdata - The comment data. */ public function delete_on_comment_post( $comment_id, $comment_approved, $commentdata ) { $post = get_post( $commentdata['comment_post_ID'] ); Logger::debug( "delete_on_comment_post: $comment_id, $comment_approved, {$post->ID}" ); /** * If a comment is not approved, we only need to delete the cache for * this post for this visitor so the unmoderated comment is shown to them. */ if ( $comment_approved !== 1 ) { $parameters = $this->request->get_parameters(); /** * if there are no cookies, then visitor did not click "remember me". * No need to delete the cache for this visitor as they'll be * redirected to a page with a hash in the URL for the moderation * message. */ if ( isset( $parameters['cookies'] ) && ! empty( $parameters['cookies'] ) ) { $filename = trailingslashit( get_permalink( $post->ID ) ) . Filesystem_Utils::get_request_filename( $parameters ); $this->storage->invalidate( $filename, Filesystem_Utils::DELETE_FILE ); } return; } $this->delete_cache_for_post( $post ); } /** * Returns true if the post is published or private. * * @param string $status - The status of the post. * @return bool */ private function is_published( $status ) { return $status === 'publish' || $status === 'private'; } /** * Delete the cached post if it transitioned from one state to another. * * @param string $new_status - The new status of the post. * @param string $old_status - The old status of the post. * @param WP_Post $post - The post that transitioned. */ public function delete_on_post_transition( $new_status, $old_status, $post ) { // Special case: Delete cache if the post type can effect the whole site. $special_post_types = array( 'wp_template', 'wp_template_part', 'wp_global_styles' ); if ( in_array( $post->post_type, $special_post_types, true ) ) { Logger::debug( 'delete_on_post_transition: special post type ' . $post->post_type ); $this->delete_cache(); return; } if ( ! Boost_Cache_Utils::is_visible_post_type( $post ) ) { return; } if ( $new_status === 'trash' ) { return; } Logger::debug( "delete_on_post_transition: $new_status, $old_status, {$post->ID}" ); // Don't delete the cache for posts that weren't published and aren't published now if ( ! $this->is_published( $new_status ) && ! $this->is_published( $old_status ) ) { Logger::debug( 'delete_on_post_transition: not published' ); return; } Logger::debug( "delete_on_post_transition: deleting post {$post->ID}" ); $this->delete_cache_for_post( $post ); $this->delete_cache_for_post_terms( $post ); $this->delete_cache_for_front_page(); $this->delete_cache_for_author( $post->post_author ); } /** * Delete the cache for the post if it was trashed. * * @param int $post_id - The id of the post. * @param string $old_status - The old status of the post. */ public function delete_on_post_trash( $post_id, $old_status ) { if ( $this->is_published( $old_status ) ) { $post = get_post( $post_id ); $this->delete_cache_for_post( $post ); $this->delete_cache_for_post_terms( $post ); $this->delete_cache_for_front_page(); $this->delete_cache_for_author( $post->post_author ); } } /** * Deletes cache files for the given post. * * @param WP_Post $post - The post to delete the cache file for. */ public function delete_cache_for_post( $post ) { static $already_deleted = -1; if ( $already_deleted === $post->ID ) { return; } /** * Don't delete the cache for post types that are not public. */ if ( ! Boost_Cache_Utils::is_visible_post_type( $post ) ) { return; } $already_deleted = $post->ID; /** * If a post is unpublished, the permalink will be deleted. In that case, * get_sample_permalink() will return a permalink with ?p=123 instead of * the post name. We need to get the post name from the post object. */ $permalink = get_permalink( $post->ID ); Logger::debug( "delete_cache_for_post: $permalink" ); $this->delete_cache_for_url( $permalink ); } /** * Delete the cache for terms associated with this post. * * @param WP_Post $post - The post to delete the cache for. */ public function delete_cache_for_post_terms( $post ) { $categories = get_the_category( $post->ID ); if ( is_array( $categories ) ) { foreach ( $categories as $category ) { $link = trailingslashit( get_category_link( $category->term_id ) ); $this->delete_cache_for_url( $link ); } } $tags = get_the_tags( $post->ID ); if ( is_array( $tags ) ) { foreach ( $tags as $tag ) { $link = trailingslashit( get_tag_link( $tag->term_id ) ); $this->delete_cache_for_url( $link ); } } } /** * Delete the entire cache for the author's archive page. * * @param int $author_id - The id of the author. * @return bool|WP_Error - True if the cache was deleted, WP_Error otherwise. */ public function delete_cache_for_author( $author_id ) { $author = get_userdata( $author_id ); if ( ! $author ) { return; } $author_link = get_author_posts_url( $author_id, $author->user_nicename ); return $this->delete_cache_for_url( $author_link ); } /** * Delete the cache for the given url. * * @param string $url - The url to delete the cache for. */ public function delete_cache_for_url( $url ) { Logger::debug( 'delete_cache_for_url: ' . $url ); return $this->storage->invalidate( $url, Filesystem_Utils::DELETE_ALL ); } /** * Delete the entire cache. */ public function delete_cache() { return $this->delete_cache_for_url( home_url() ); } public function disable_caching_on_error( $message ) { if ( ! defined( 'DONOTCACHEPAGE' ) ) { define( 'DONOTCACHEPAGE', true ); } Logger::debug( 'Fatal error detected, caching disabled' ); return $message; } }
projects/plugins/boost/app/modules/optimizations/page-cache/pre-wordpress/Boost_Cache_Actions.php
<?php /** * This file contains all the public actions for the Page Cache module. * This file is loaded before WordPress is fully initialized. */ use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache; /** * Delete all cache. * * Allow third-party plugins to clear all cache. */ add_action( 'jetpack_boost_clear_page_cache_all', 'jetpack_boost_delete_cache' ); /** * Delete cache for homepage and paged archives. * * Allow third-party plugins to clear front-page cache. */ add_action( 'jetpack_boost_clear_page_cache_home', 'jetpack_boost_delete_cache_for_home' ); /** * Delete cache for a specific URL. * * Allow third-party plugins to clear the cache for a specific URL. * * @param string $url - The URL to delete the cache for. */ add_action( 'jetpack_boost_clear_page_cache_url', 'jetpack_boost_delete_cache_for_url' ); /** * Delete cache for a specific post. * * Allow third-party plugins to clear the cache for a specific post. * * @param int $post_id - The ID of the post to delete the cache for. */ add_action( 'jetpack_boost_clear_page_cache_post', 'jetpack_boost_delete_cache_by_post_id' ); /** * Delete all cache files. */ function jetpack_boost_delete_cache() { $boost_cache = new Boost_Cache(); $boost_cache->delete_cache(); } /** * Delete cache for homepage and paged archives. */ function jetpack_boost_delete_cache_for_home() { $boost_cache = new Boost_Cache(); $boost_cache->delete_cache_for_front_page(); } /** * Delete cache for a specific URL. * @param string $url - The URL to delete the cache for. */ function jetpack_boost_delete_cache_for_url( $url ) { $boost_cache = new Boost_Cache(); $boost_cache->delete_cache_for_url( $url ); } /** * Delete cache for a specific post. * @param int $post_id - The ID of the post to delete the cache for. */ function jetpack_boost_delete_cache_by_post_id( $post_id ) { $boost_cache = new Boost_Cache(); $boost_cache->delete_cache_by_post_id( (int) $post_id ); }
projects/plugins/boost/app/modules/optimizations/page-cache/pre-wordpress/Boost_Cache_Error.php
<?php /* * This file may be called before WordPress is fully initialized. See the README file for info. */ namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress; /** * A replacement for WP_Error when working in a Pre_WordPress setting. * * This class deliberately offers a similar API to WP_Error for familiarity. All Pre_WordPress functions * which may return an error object use this class to represent an Error state. * * If you call a Pre_WordPress function after loading WordPress, use to_wp_error to convert these * objects to a standard WP_Error object. */ class Boost_Cache_Error { /** * @var string - The error code. */ private $code; /** * @var string - The error message. */ private $message; /** * Create a Boost_Cache_Error object, with a code and a message. */ public function __construct( $code, $message ) { $this->code = $code; $this->message = $message; } /** * Return the error message. */ public function get_error_message() { return $this->message; } /** * Return the error code. */ public function get_error_code() { return $this->code; } /** * Convert to a WP_Error. * * When calling a Pre_WordPress function from a WordPress context, use this method to convert * any resultant errors to WP_Errors for interfacing with other WordPress APIs. * * **Warning** - this function should only be called if WordPress has been loaded! */ public function to_wp_error() { if ( ! class_exists( '\WP_Error' ) ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log( 'Warning: Boost_Cache_Error::to_wp_error called from a Pre-WordPress context' ); } } return new \WP_Error( $this->get_error_code(), $this->get_error_message() ); } }
projects/plugins/boost/app/modules/optimizations/page-cache/pre-wordpress/Request.php
<?php /* * This file may be called before WordPress is fully initialized. See the README file for info. */ namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress; class Request { /** * @var Request - The request instance for current request. */ private static $current_request = null; /** * @var string - The normalized path for the current request. This is not sanitized. Only to be used for comparison purposes. */ private $request_uri = false; /** * @var array - The GET parameters and cookies for the current request. Everything considered in the cache key. */ private $request_parameters; /** * Gets the singleton request instance. * * @return Request The instance of the class. */ public static function current() { if ( self::$current_request === null ) { self::$current_request = new self( // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash isset( $_SERVER['REQUEST_URI'] ) ? Boost_Cache_Utils::normalize_request_uri( $_SERVER['REQUEST_URI'] ) : false, // Set the cookies and get parameters for the current request. Sometimes these arrays are modified by WordPress or other plugins. // We need to cache them here so they can be used for the cache key later. We don't need to sanitize them, as they are only used for comparison. array( 'cookies' => $_COOKIE, // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized 'get' => $_GET, // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.NonceVerification.Recommended ) ); } return self::$current_request; } public function __construct( $uri, $parameters ) { $this->request_uri = $uri; $this->request_parameters = $parameters; } public function get_uri() { return $this->request_uri; } public function get_parameters() { return $this->request_parameters; } /** * Returns true if the current request has a fatal error. * * @return bool */ private function is_fatal_error() { $error = error_get_last(); if ( $error === null ) { return false; } $fatal_errors = array( E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, ); return in_array( $error['type'], $fatal_errors, true ); } public function is_url_excluded( $request_uri = '' ) { if ( $request_uri === '' ) { $request_uri = $this->request_uri; } $bypass_patterns = Boost_Cache_Settings::get_instance()->get_bypass_patterns(); /** * Filters the bypass patterns for the page cache. * * @since $$next-version$$ * * @param array $bypass_patterns An array of regex patterns that define URLs that bypass caching. */ $bypass_patterns = apply_filters( 'jetpack_boost_cache_bypass_patterns', $bypass_patterns ); $bypass_patterns[] = 'wp-.*\.php'; foreach ( $bypass_patterns as $expr ) { if ( ! empty( $expr ) && preg_match( "~$expr~", $request_uri ) ) { return true; } } return false; } /** * Returns true if the request is cacheable. * * If a request is in the backend, or is a POST request, or is not an * html request, it is not cacheable. * The filter boost_cache_cacheable can be used to override this. * * @return bool */ public function is_cacheable() { /** * Determines if the request is considered cacheable. * * Can be used to prevent a request from being cached. * * @since $$next-version$$ * * @param string $request_uri The request URI to be evaluated for cacheability. */ if ( ! apply_filters( 'jetpack_boost_cache_request_cacheable', $this->request_uri ) ) { return false; } if ( defined( 'DONOTCACHEPAGE' ) ) { return false; } // do not cache post previews or customizer previews if ( ! empty( $_GET ) && ( isset( $_GET['preview'] ) || isset( $_GET['customize_changeset_uuid'] ) ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.NonceVerification.Recommended return false; } if ( $this->is_fatal_error() ) { return false; } if ( function_exists( 'is_user_logged_in' ) && is_user_logged_in() ) { return false; } if ( $this->is_404() ) { return false; } if ( $this->is_feed() ) { return false; } if ( $this->is_backend() ) { return false; } if ( $this->is_bypassed_extension() ) { return false; } if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] !== 'GET' ) { return false; } if ( $this->is_url_excluded() ) { Logger::debug( 'Url excluded, not cached!' ); return false; } /** * Filters the accept headers to determine if the request should be cached. * * This filter allows modification of the content types that browsers send * to the server during a request. If the acceptable browser content type header (HTTP_ACCEPT) * matches one of these content types the request will not be cached, * or a cached file served to this visitor. * * @since $$next-version$$ * * @param array $accept_headers An array of header values that should prevent a request from being cached. */ $accept_headers = apply_filters( 'jetpack_boost_cache_accept_headers', array( 'application/json', 'application/activity+json', 'application/ld+json' ) ); $accept_headers = array_map( 'strtolower', $accept_headers ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- $accept is checked and set below. $accept = isset( $_SERVER['HTTP_ACCEPT'] ) ? strtolower( filter_var( $_SERVER['HTTP_ACCEPT'] ) ) : ''; if ( $accept !== '' ) { foreach ( $accept_headers as $header ) { if ( str_contains( $accept, $header ) ) { return false; } } } return true; } /** * Returns true if the request appears to be for something with a known file extension that is not * usually HTML. e.g.: * - *.txt (including robots.txt, license.txt) * - *.ico (favicon.ico) * - *.jpg, *.png, *.webm (image files). */ public function is_bypassed_extension() { $file_extension = pathinfo( $this->request_uri, PATHINFO_EXTENSION ); return in_array( $file_extension, array( 'txt', 'ico', 'jpg', 'jpeg', 'png', 'webp', 'gif', ), true ); } /** * Returns true if the current request is one of the following: * 1. wp-admin * 2. wp-login.php, xmlrpc.php or wp-cron.php/cron request * 3. WP_CLI * 4. REST request. * * @return bool */ public function is_backend() { $is_backend = is_admin(); if ( $is_backend ) { return $is_backend; } $script = isset( $_SERVER['PHP_SELF'] ) ? basename( $_SERVER['PHP_SELF'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash if ( $script !== 'index.php' ) { if ( in_array( $script, array( 'wp-login.php', 'xmlrpc.php', 'wp-cron.php' ), true ) ) { $is_backend = true; } } if ( defined( 'DOING_CRON' ) && DOING_CRON ) { $is_backend = true; } if ( PHP_SAPI === 'cli' || ( defined( 'WP_CLI' ) && constant( 'WP_CLI' ) ) ) { $is_backend = true; } if ( defined( 'REST_REQUEST' ) ) { $is_backend = true; } return $is_backend; } /** * "Safe" version of WordPress' is_404 method. When called before WordPress' query is run, returns * `null` (a falsey value) instead of outputting a _doing_it_wrong warning. */ public function is_404() { global $wp_query; if ( ! isset( $wp_query ) || ! function_exists( '\is_404' ) ) { return null; } return \is_404(); } /** * "Safe" version of WordPress' is_feed method. When called before WordPress' query is run, returns * `null` (a falsey value) instead of outputting a _doing_it_wrong warning. */ public function is_feed() { global $wp_query; if ( ! isset( $wp_query ) || ! function_exists( '\is_feed' ) ) { return null; } return \is_feed(); } }
projects/plugins/boost/app/modules/optimizations/page-cache/pre-wordpress/storage/File_Storage.php
<?php /* * This file may be called before WordPress is fully initialized. See the README file for info. */ namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Storage; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Error; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Utils; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Filesystem_Utils; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Logger; /** * File Storage - handles writing to disk, reading from disk, purging and pruning old content. */ class File_Storage implements Storage { /** * @var string - The root path where all cached files go. */ private $root_path; public function __construct( $root_path ) { $this->root_path = WP_CONTENT_DIR . '/boost-cache/cache/' . Boost_Cache_Utils::sanitize_file_path( Boost_Cache_Utils::trailingslashit( $root_path ) ); } /** * Given a request_uri and its parameters, store the given data in the cache. * * @param string $request_uri - The URI of this request (excluding GET parameters) * @param array $parameters - An associative array of all the things that make this request special/different. Includes GET parameters and COOKIEs normally. * @param string $data - The data to write to disk. */ public function write( $request_uri, $parameters, $data ) { $directory = self::get_uri_directory( $request_uri ); $filename = Filesystem_Utils::get_request_filename( $parameters ); if ( ! Filesystem_Utils::create_directory( $directory ) ) { return new Boost_Cache_Error( 'cannot-create-cache-dir', 'Could not create cache directory' ); } return Filesystem_Utils::write_to_file( $directory . $filename, $data ); } /** * Given a request_uri and its parameters, return any stored data from the cache, or false otherwise. * * @param string $request_uri - The URI of this request (excluding GET parameters) * @param array $parameters - An associative array of all the things that make this request special/different. Includes GET parameters and COOKIEs normally. */ public function read( $request_uri, $parameters ) { $directory = self::get_uri_directory( $request_uri ); $filename = Filesystem_Utils::get_request_filename( $parameters ); $hash_path = $directory . $filename; if ( file_exists( $hash_path ) ) { $filemtime = filemtime( $hash_path ); $expired = ( $filemtime + JETPACK_BOOST_CACHE_DURATION ) <= time(); // If file exists and is not expired, return the file contents. if ( ! $expired ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents, WordPress.Security.EscapeOutput.OutputNotEscaped return file_get_contents( $hash_path ); } // If file exists but is expired, delete it. if ( Filesystem_Utils::delete_file( $hash_path ) ) { Logger::debug( "Deleted expired file: $hash_path" ); } else { Logger::debug( "Could not delete expired file: $hash_path" ); } } return false; } /** * Garbage collect expired files. */ public function garbage_collect() { if ( JETPACK_BOOST_CACHE_DURATION === 0 ) { // Garbage collection is disabled. return false; } $count = Filesystem_Utils::delete_expired_files( $this->root_path, JETPACK_BOOST_CACHE_DURATION ); Logger::debug( "Garbage collected $count files" ); } /** * Given a request_uri, return the filesystem path where it should get stored. Handles sanitization. * Note that the directory path does not take things like GET parameters or cookies into account, for easy cache purging. * * @param string $request_uri - The URI of this request (excluding GET parameters) */ private function get_uri_directory( $request_uri ) { return Boost_Cache_Utils::trailingslashit( $this->root_path . self::sanitize_path( $request_uri ) ); } /** * Sanitize a path for safe usage on the local filesystem. * * @param string $path - The path to sanitize. */ private function sanitize_path( $path ) { static $_cache = array(); if ( isset( $_cache[ $path ] ) ) { return $_cache[ $path ]; } $path = Boost_Cache_Utils::sanitize_file_path( $path ); $_cache[ $path ] = $path; return $path; } /** * Delete all cached data for the given path. * * @param string $path - The path to delete. File or directory. * @param string $type - defines what files/directories are deleted: DELETE_FILE, DELETE_FILES, DELETE_ALL. */ public function invalidate( $path, $type ) { Logger::debug( "invalidate: $path $type" ); $normalized_path = $this->root_path . Boost_Cache_Utils::normalize_request_uri( $path ); if ( in_array( $type, array( Filesystem_Utils::DELETE_FILES, Filesystem_Utils::DELETE_ALL ), true ) && is_dir( $normalized_path ) ) { return Filesystem_Utils::delete_directory( $normalized_path, $type ); } elseif ( $type === Filesystem_Utils::DELETE_FILE && is_file( $normalized_path ) ) { return Filesystem_Utils::delete_file( $normalized_path ); } else { return new Boost_Cache_Error( 'no-cache-files-to-delete', 'No cache files to delete.' ); } } }
projects/plugins/boost/app/modules/optimizations/page-cache/pre-wordpress/storage/Storage.php
<?php /* * This file may be called before WordPress is fully initialized. See the README file for info. */ namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Storage; /** * Interface for Cache storage - a system for storing and purging caches. */ interface Storage { public function write( $request_uri, $parameters, $data ); public function read( $request_uri, $parameters ); public function invalidate( $request_uri, $type ); public function garbage_collect(); }
projects/plugins/boost/app/modules/optimizations/page-cache/data-sync/Page_Cache_Entry.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Data_Sync; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Get; use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Set; use Automattic\Jetpack_Boost\Modules\Optimizations\Page_Cache\Pre_WordPress\Boost_Cache_Settings; class Page_Cache_Entry implements Entry_Can_Get, Entry_Can_Set { public function get( $_fallback = false ) { $cache_settings = Boost_Cache_Settings::get_instance(); $settings = array( 'bypass_patterns' => $cache_settings->get_bypass_patterns(), 'logging' => $cache_settings->get_logging(), ); return $settings; } public function set( $value ) { $cache_settings = Boost_Cache_Settings::get_instance(); $value['bypass_patterns'] = $this->sanitize_value( $value['bypass_patterns'] ); $cache_settings->set( $value ); } /** * Sanitizes the given value, ensuring that it is list of valid patterns. * * @param mixed $value The value to sanitize. * * @return string The sanitized value, as a list. */ private function sanitize_value( $value ) { if ( is_array( $value ) ) { $value = array_values( array_unique( array_filter( array_map( 'trim', array_map( 'strtolower', $value ) ) ) ) ); $home_url = home_url( '/' ); foreach ( $value as &$path ) { // Strip home URL (both secure and non-secure). $path = str_ireplace( array( $home_url, str_replace( 'http:', 'https:', $home_url ), ), array( '/', '/', ), $path ); // Remove double shashes. $path = str_replace( '//', '/', $path ); // Make sure there's a leading slash. $path = '/' . ltrim( $path, '/' ); // Fix up any wildcards. $path = $this->sanitize_wildcards( $path ); } } else { $value = array(); } return $value; } /** * Sanitize wildcards in a given path. * * @param string $path The path to sanitize. * @return string The sanitized path. */ private function sanitize_wildcards( $path ) { if ( ! $path ) { return ''; } $path_components = explode( '/', $path ); $arr = array( '.*' => '(.*)', '*' => '(.*)', '(*)' => '(.*)', '(.*)' => '(.*)', ); foreach ( $path_components as &$path_component ) { $path_component = strtr( $path_component, $arr ); } $path = implode( '/', $path_components ); return $path; } }
projects/plugins/boost/app/modules/optimizations/image-cdn/class-image-cdn.php
<?php namespace Automattic\Jetpack_Boost\Modules\Optimizations\Image_CDN; use Automattic\Jetpack\Image_CDN\Image_CDN_Setup; use Automattic\Jetpack_Boost\Contracts\Changes_Page_Output; use Automattic\Jetpack_Boost\Contracts\Pluggable; use Automattic\Jetpack_Boost\Lib\Premium_Features; class Image_CDN implements Pluggable, Changes_Page_Output { public function setup() { Image_CDN_Setup::load(); if ( Premium_Features::has_feature( Premium_Features::IMAGE_CDN_QUALITY ) ) { add_filter( 'jetpack_photon_pre_args', array( $this, 'add_quality_args' ), 10, 2 ); } } public static function get_slug() { return 'image_cdn'; } public static function is_available() { return true; } /** * Add quality arg to existing photon args. * * @param $args array - Existing photon args. * * @return mixed */ public function add_quality_args( $args, $image_url ) { $quality = $this->get_quality_for_image( $image_url ); if ( $quality !== null ) { $args['quality'] = $quality; } return $args; } /** * Get the quality for an image based on the extension. */ private function get_quality_for_image( $image_url ) { // Define an associative array to map extensions to image types $extension_to_quality = array( 'jpg' => $this->get_quality_for_type( 'jpg' ), 'jpeg' => $this->get_quality_for_type( 'jpg' ), 'webp' => $this->get_quality_for_type( 'webp' ), 'png' => $this->get_quality_for_type( 'png' ), ); // Extract the file extension from the URL $file_extension = pathinfo( $image_url, PATHINFO_EXTENSION ); // Convert the extension to lowercase for case-insensitive comparison $file_extension = strtolower( $file_extension ); // Determine the image type based on the extension if ( isset( $extension_to_quality[ $file_extension ] ) ) { return $extension_to_quality[ $file_extension ]; } return null; } private function get_quality_for_type( $image_type ) { $quality_settings = jetpack_boost_ds_get( 'image_cdn_quality' ); if ( ! isset( $quality_settings[ $image_type ] ) ) { return null; } // Passing 100 to photon will result in a lossless image return $quality_settings[ $image_type ]['lossless'] ? 100 : $quality_settings[ $image_type ]['quality']; } }
projects/plugins/boost/app/rest-api/REST_API.php
<?php namespace Automattic\Jetpack_Boost\REST_API; use Automattic\Jetpack_Boost\REST_API\Contracts\Endpoint; class REST_API { /** * @var Route[] */ protected $routes = array(); /** * @param Endpoint[] $routes */ public function __construct( $routes ) { foreach ( $routes as $route_class ) { $this->routes[] = new Route( $route_class ); } } public function register_rest_routes() { foreach ( $this->routes as $route ) { $route->register_rest_route(); } } /** * @param Endpoint|Endpoint[]|string $endpoints * * @return void */ public static function register( $endpoints ) { // If endpoints are passed as a string, // (array) will convert it to an array. $rest_api = new REST_API( (array) $endpoints ); add_action( 'rest_api_init', array( $rest_api, 'register_rest_routes' ) ); } }
projects/plugins/boost/app/rest-api/Route.php
<?php namespace Automattic\Jetpack_Boost\REST_API; class Route { /** * @var \Automattic\Jetpack_Boost\REST_API\Contracts\Endpoint */ protected $endpoint; protected $permissions; public function __construct( $endpoint ) { $this->endpoint = new $endpoint(); $this->permissions = $this->endpoint->permissions(); } public function register_rest_route() { register_rest_route( JETPACK_BOOST_REST_NAMESPACE, JETPACK_BOOST_REST_PREFIX . '/' . $this->endpoint->name(), array( 'methods' => $this->endpoint->request_methods(), 'callback' => array( $this->endpoint, 'response' ), 'permission_callback' => array( $this, 'verify_permissions' ), ) ); } /** * This method is going to run and try to verify that * all the permission callbacks are successful. * * If any of them fail - return false immediately. * * @param \WP_REST_Request $request * * @return bool */ public function verify_permissions( $request ) { foreach ( $this->permissions as $permission ) { if ( true !== $permission->verify( $request ) ) { return false; } } return true; } }
projects/plugins/boost/app/rest-api/endpoints/Update_Cloud_CSS.php
<?php /** * Save generated cloud critical CSS. * * This endpoint is used by WP.com to push the generated CSS to the boost plugin. */ namespace Automattic\Jetpack_Boost\REST_API\Endpoints; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State; use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_Storage; use Automattic\Jetpack_Boost\REST_API\Contracts\Endpoint; use Automattic\Jetpack_Boost\REST_API\Permissions\Signed_With_Blog_Token; use WP_REST_Server; /** * Handler for POST cloud-css/update. Expects the following body params: * - success: boolean - False if the whole Critical CSS job failed. * - message: string containing an error message if success is false. * - providers: Object containing one result for each provider_key: * * Each provider key contains: * - success: boolean - False if this provider key failed. * - data: Either a successful CSS block, or a CSS error. * * Each CSS block looks like: * - css: string - containing CSS data. * * Each CSS error looks like: * - urls: Object describing each URL which failed. Keys are URLs. * * Each URL failure looks like: * - message: string - containing an error message. * - type: string - machine readable error type. * - meta: Object - JSON string compatible object containing extra metadata for consumption in the UI. */ class Update_Cloud_CSS implements Endpoint { public function name() { return 'cloud-css/update'; } public function request_methods() { return WP_REST_Server::EDITABLE; } public function response( $request ) { $state = new Critical_CSS_State(); $storage = new Critical_CSS_Storage(); $params = $request->get_params(); $providers = empty( $params['providers'] ) || ! is_array( $params['providers'] ) ? array() : $params['providers']; $api_successful = array( 'success' => true ); // If success is false, the whole Cloud CSS generation process failed. if ( empty( $params['success'] ) ) { if ( empty( $params['message'] ) || ! is_string( $params['message'] ) ) { $error = __( 'An unknown error occurred', 'jetpack-boost' ); } else { $error = $params['message']; } $state->set_error( $error ); $state->save(); return $api_successful; } // Update each provider. foreach ( $providers as $provider_key => $result ) { if ( ! isset( $result['data'] ) ) { return new \WP_Error( 'invalid_data', __( 'Invalid request; missing data element', 'jetpack-boost' ) ); } $data = $result['data']; // Success if ( ! empty( $result['success'] ) && ! empty( $data['css'] ) && is_string( $data['css'] ) ) { $storage->store_css( $provider_key, $data['css'] ); $state->set_provider_success( $provider_key ); continue; } // Failures must have an array of urls. if ( empty( $data['urls'] ) || ! is_array( $data['urls'] ) ) { return new \WP_Error( 'invalid_data', __( 'Invalid request; missing urls element', 'jetpack-boost' ) ); } $state->set_provider_errors( $provider_key, $this->flatten_url_errors( $data['urls'] ) ); } // Save the state changes. $state->save(); return $api_successful; } /** * Errors arrive from Shield in an associative array with the URL as the key. * This function flattens the array into a list of assoc arrays with the URL in each member. */ private function flatten_url_errors( $errors ) { $flat_errors = array(); foreach ( $errors as $url => $error ) { $flat_errors[] = array_merge( array( 'url' => $url ), $error ); } return $flat_errors; } public function permissions() { return array( new Signed_With_Blog_Token(), ); } }