namespace WPForms\Helpers;
* Remote data cache handler.
* Usage example in `WPForms\Admin\Addons\AddonsCache` and `WPForms\Admin\Builder\TemplatesCache`.
abstract class CacheBase {
protected const ENCRYPT = false;
* Request lock time, min.
private const REQUEST_LOCK_TIME = 15;
* A class id or array of cache class ids to sync updates with.
protected const SYNC_WITH = [];
* The current class is syncing updates now.
private $syncing_updates = false;
* Indicates whether the cache was updated during the current run.
protected $updated = false;
* Determine if the class is allowed to load.
abstract protected function allow_load();
// Init settings before allow_load() as settings are used in get().
$this->update_settings();
$this->cache_key = $this->settings['cache_file'];
$this->cache_dir = $this->get_cache_dir(); // See comment in the method.
$this->cache_file = $this->cache_dir . $this->settings['cache_file'];
// Do not update caches on heartbeat events.
// phpcs:ignore WordPress.Security.NonceVerification.Missing
$action = isset( $_POST['action'] ) ? sanitize_text_field( wp_unslash( $_POST['action'] ) ) : '';
if ( $action === 'heartbeat' ) {
if ( ! $this->allow_load() ) {
// Quit if settings weren't provided.
empty( $this->settings['remote_source'] ) ||
empty( $this->settings['cache_file'] )
private function hooks(): void {
add_action( 'shutdown', [ $this, 'cache_dir_complete' ] );
if ( empty( $this->settings['update_action'] ) ) {
// Schedule recurring updates.
add_action( 'admin_init', [ $this, 'schedule_update_cache' ] );
add_action( $this->settings['update_action'], [ $this, 'update' ] );
add_action( 'wpforms_helpers_cache_base_sync_updates', [ $this, 'sync_updates' ] );
* If one update has been done, run the update for other caches.
* @noinspection PhpCastIsUnnecessaryInspection
* @noinspection UnnecessaryCastingInspection
public function sync_updates(): void {
// Prevent infinite loop.
if ( $this->syncing_updates ) {
foreach ( (array) static::SYNC_WITH as $classname ) {
$cache = wpforms()->obj( $classname );
if ( ! $cache instanceof self ) {
private function update_settings(): void {
// For instance: 'https://wpformsapi.com/feeds/v1/addons/'.
// Request timeout in seconds.
// Just file name. For instance: 'addons.json'.
// Cache time to live in seconds.
'cache_ttl' => WEEK_IN_SECONDS,
// Scheduled update action.
// For instance: 'wpforms_admin_addons_cache_update'.
// Additional query args for the remote source URL.
$this->settings = wp_parse_args( $this->setup(), $default_settings );
* @return array Settings array.
abstract protected function setup();
* Get a cache directory path.
protected function get_cache_dir() {
return File::get_cache_dir();
* Get data from cache or from API call.
$cache = $this->get_from_cache();
if ( ! empty( $cache ) && ! $this->is_expired_cache() ) {
return $this->get_from_cache();
* Determine if the cache is expired.
private function is_expired_cache(): bool {
return $this->cache_time() + $this->settings['cache_ttl'] < time();
* Get cache creation time.
private function cache_time(): int {
return (int) Transient::get( $this->cache_key );
* Determine if the cache file exists.
private function exists(): bool {
return is_file( $this->cache_file ) && is_readable( $this->cache_file );
* Get cache from a cache file.
private function get_from_cache(): array {
if ( ! $this->exists() ) {
$content = File::get_contents( $this->cache_file );
// Do not decrypt non-encrypted legacy files, they will be encrypted on the scheduled update.
if ( static::ENCRYPT && ! wpforms_is_json( $content ) ) {
$content = Crypto::decrypt( $content );
return (array) json_decode( $content, true );
* @param bool $force Force update.
public function update( bool $force = false ): bool {
time() < $this->cache_time() + self::REQUEST_LOCK_TIME * MINUTE_IN_SECONDS
Transient::set( $this->cache_key, time(), $this->settings['cache_ttl'] );
if ( ! wp_mkdir_p( $this->cache_dir ) ) {
$data = $this->perform_remote_request();
$content = wp_json_encode( $data );
$this->maybe_update_transient( $data );
$content = Crypto::encrypt( $content );
if ( ! File::put_contents( $this->cache_file, $content ) ) {
if ( ! $this->syncing_updates ) {
$this->syncing_updates = true;
* Action hook after the cache has been updated.
do_action( 'wpforms_helpers_cache_base_sync_updates' );
protected function perform_remote_request(): array {
$query_args = $this->settings['query_args'] ?? [];
$request_url = add_query_arg( $query_args, $this->settings['remote_source'] );
$user_agent = wpforms_get_default_user_agent();
$request = wp_remote_get(
'timeout' => $this->settings['timeout'],
'user-agent' => $user_agent,
$request_url_log = remove_query_arg( [ 'tgm-updater-key' ], $request_url );
// Log if the request failed.
if ( is_wp_error( $request ) ) {
'Cached data: HTTP request error',
'class' => static::class,
'request_url' => $request_url_log,
'error' => $request->get_error_message(),
'error_data' => $request->get_error_data(),
$response_code = wp_remote_retrieve_response_code( $request );
$raw_headers = wp_remote_retrieve_headers( $request );
$response_headers = is_object( $raw_headers ) ? $raw_headers->getAll() : (array) $raw_headers;
$response_body = wp_remote_retrieve_body( $request );
$response_body_len = strlen( $response_body );
$response_body_log = $response_body_len > 1024 ? "(First 1 kB):\n" . substr( trim( $response_body ), 0, 1024 ) . '...' : trim( $response_body );
$response_body_log = esc_html( $response_body_log );
'class' => static::class,
'request_url' => $request_url_log,
'code' => $response_code,
'headers' => $response_headers,
'content_length' => $response_body_len,
'body' => $response_body_log,
// Log the response details in debug mode.
$this->add_log( 'Cached data: Response details', $log_data );
// Log the error if the response code is not 2xx or 3xx.
if ( $response_code > 399 ) {
$this->add_log( 'Cached data: HTTP request error', $log_data, 'error' );
$json = trim( $response_body );
$data = json_decode( $json, true );
$message = $data === null ? 'Invalid JSON' : 'Empty JSON';
'json_result' => $message,
'cache_file' => $this->settings['cache_file'],
'remote_source' => $this->settings['remote_source'],
$this->add_log( 'Cached data: ' . $message, $log_data, 'error' );
return $this->prepare_cache_data( $data );
* @param string $title Log title.
* @param array $data Log data.
* @param string $type Log type.
protected function add_log( string $title, array $data, string $type = 'log' ): void {
public function schedule_update_cache(): void {
// Just skip if not need to register a scheduled action.
if ( empty( $this->settings['update_action'] ) ) {
$tasks = wpforms()->obj( 'tasks' );
! $tasks instanceof Tasks ||
$tasks->is_scheduled( $this->settings['update_action'] ) !== false