settings = $settings; $this->logger = $logger; } /** * Register hooks. * * @return void */ public function register() { add_action( 'send_headers', array( $this, 'send_headers' ) ); } /** * Send safe cache headers for HTML responses. * * @return void */ public function send_headers() { if ( ! $this->settings->get( 'browser.enabled', 1 ) || is_admin() || headers_sent() ) { return; } header( 'Vary: Accept-Encoding' ); if ( is_user_logged_in() ) { header( 'Cache-Control: private, no-cache, no-store, must-revalidate' ); header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' ); return; } header( 'Cache-Control: public, max-age=300, must-revalidate' ); header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 300 ) . ' GMT' ); header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', time() ) . ' GMT' ); } /** * Apache rules for static browser cache. * * @return array */ public function rules() { $max_age = max( 3600, absint( $this->settings->get( 'browser.max_age', 2592000 ) ) ); $etags = $this->settings->get( 'browser.etags', 1 ); $rules = array( '', 'ExpiresActive On', 'ExpiresByType text/css "access plus 1 year"', 'ExpiresByType application/javascript "access plus 1 year"', 'ExpiresByType text/javascript "access plus 1 year"', 'ExpiresByType image/jpeg "access plus 1 year"', 'ExpiresByType image/png "access plus 1 year"', 'ExpiresByType image/gif "access plus 1 year"', 'ExpiresByType image/webp "access plus 1 year"', 'ExpiresByType image/svg+xml "access plus 1 year"', 'ExpiresByType font/woff2 "access plus 1 year"', 'ExpiresByType font/woff "access plus 1 year"', '', '', '', 'Header set Cache-Control "public, max-age=' . $max_age . ', immutable"', 'Header set Vary "Accept-Encoding"', '', '', ); if ( $etags ) { $rules[] = 'FileETag MTime Size'; } else { $rules[] = 'FileETag None'; $rules[] = ''; $rules[] = 'Header unset ETag'; $rules[] = ''; } return $rules; } /** * Write Apache rules to .htaccess using WordPress markers. * * @return bool */ public function apply_rules() { if ( ! function_exists( 'insert_with_markers' ) ) { require_once ABSPATH . 'wp-admin/includes/misc.php'; } $result = insert_with_markers( ABSPATH . '.htaccess', 'Acelora Browser Cache', $this->rules() ); $this->logger->log( $result ? 'info' : 'error', 'Browser cache rules write attempted.', array( 'result' => (bool) $result ) ); return (bool) $result; } }