(bool) * 'resolution' => how often in seconds (float) * 'lifetime' => how long until entries expire in seconds (int) * 'verbose' => (bool) capture extra stuff. * ] * * @var array $options Option list. */ private $monitoring_options; /** * Database object. * @var SQLite3 instance. */ private $sqlite; /** * Constructor for SQLite Object Cache. * * @since 2.0.8 */ public function __construct() { $this->cache_group_types(); $this->has_hrtime = function_exists( 'hrtime' ); $this->has_microtime = function_exists( 'microtime' ); $this->has_igbinary = function_exists( 'igbinary_serialize' ) && function_exists( 'igbinary_unserialize' ); $this->sqlite_path = $this->create_database_path(); $this->sqlite_timeout = defined( 'WP_SQLITE_OBJECT_CACHE_TIMEOUT' ) ? WP_SQLITE_OBJECT_CACHE_TIMEOUT : self::SQLITE_TIMEOUT; $this->sqlite_journal_mode = defined( 'WP_SQLITE_OBJECT_CACHE_JOURNAL_MODE' ) ? WP_SQLITE_OBJECT_CACHE_JOURNAL_MODE : self::JOURNAL_MODE; $this->multisite = is_multisite(); $this->blog_prefix = $this->multisite ? get_current_blog_id() . ':' : ''; $this->cache_table_name = self::OBJECT_CACHE_TABLE; $this->noexpire_timestamp_offset = self::NOEXPIRE_TIMESTAMP_OFFSET; $this->max_lifetime = self::MAX_LIFETIME; } /** * Create the pathname for the sqlite database. * * This is based on WP_SQLITE_OBJECT_CACHE_DB_FILE, WP_CACHE_KEY_SALT, * and whether igbinary is available. * It may have -wal and -shm appended to it by the SQLite engine. * * @return string Full filesystem pathname for SQLite database. */ private function create_database_path() { $result = defined( 'WP_SQLITE_OBJECT_CACHE_DB_FILE' ) ? WP_SQLITE_OBJECT_CACHE_DB_FILE : WP_CONTENT_DIR . '/' . self::SQLITE_FILENAME; $salt = defined( 'WP_CACHE_KEY_SALT' ) ? WP_CACHE_KEY_SALT : ''; $salt .= $this->has_igbinary ? '' : '-a'; if ( strlen( $salt ) > 0 ) { $splits = explode( '.', $result ); if ( count( $splits ) >= 2 && 'sqlite' === $splits [ count( $splits ) - 1 ] ) { $splits[ count( $splits ) - 1 ] = $salt; $splits [] = 'sqlite'; $result = implode( '.', $splits ); } else { $result .= '.' . $salt . '.sqlite'; } } return $result; } /** * @param string|null $msg * * @return void */ public static function drop_dead( $msg = null ) { if ( ! $msg ) { if ( ! function_exists( '__' ) ) { wp_load_translations_early(); } $msg = __( 'The SQLite Object Cache temporarily failed. Please try again now.', 'sqlite-object-cache' ); } wp_die( esc_html( $msg ) ); } /** * Log an error. * * @param string $msg * @param Exception $exception * * @return void */ private function error_log( $msg, $exception = null ) { $msgs = []; $msgs [] = 'SQLite Object Cache:'; $msgs [] = $msg; if ( $this->sqlite ) { if ( $this->sqlite->lastErrorMsg() ) { $msgs [] = $this->sqlite->lastErrorMsg(); $msgs [] = '(' . $this->sqlite->lastErrorCode() . ')'; } } if ( $exception ) { if ( $exception->getMessage() !== $this->sqlite->lastErrorMsg() ) { $msgs[] = $exception->getMessage(); $msgs [] = '(' . $exception->getCode() . ')'; } $msgs [] = $exception->getTraceAsString(); } error_log( implode( ' ', $msgs ) ); } /** * Open SQLite3 connection. * @return void */ private function open_connection() { if ( $this->sqlite ) { return; } $max_retries = 3; $retries = 0; while ( ++ $retries <= $max_retries ) { try { $this->actual_open_connection(); return; } catch ( Exception $ex ) { /* something went wrong opening */ $this->error_log( 'open_connection failure', $ex ); $this->delete_offending_files( $retries ); } } } /** * Open SQLite3 connection. * * @return void * @throws Exception Announce SQLite failure. */ private function actual_open_connection() { $start = $this->time_usec(); $this->sqlite = new SQLite3( $this->sqlite_path, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, '' ); $this->sqlite->enableExceptions( true ); $this->sqlite->busyTimeout( $this->sqlite_timeout ); /* set some initial pragma stuff */ /* NOTE WELL: SQL in this file is not for use with $wpdb, but for SQLite3 */ /* Notice we sometimes use a journal mode (MEMORY) that risks database corruption. * That's OK, because it's faster, and because we have an error * recovery procedure that deletes and recreates a corrupt database file. */ $this->sqlite->exec( 'PRAGMA synchronous = OFF' ); $this->sqlite->exec( "PRAGMA journal_mode = $this->sqlite_journal_mode" ); $this->sqlite->exec( "PRAGMA encoding = 'UTF-8'" ); $this->sqlite->exec( 'PRAGMA case_sensitive_like = true' ); $this->create_object_cache_table(); $this->prepare_statements( $this->cache_table_name ); $this->preload( $this->cache_table_name ); $this->open_time = $this->time_usec() - $start; } /** * Get current time. * * @return float Current time in microseconds, from an arbitrary epoch. */ private function time_usec() { if ( $this->has_hrtime ) { /** @noinspection PhpMethodParametersCountMismatchInspection */ /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ return hrtime( true ) * 0.001; } if ( $this->has_microtime ) { return microtime( true ); } return time() * 1000000.0; } /** * Set group type array * * @return void */ protected function cache_group_types() { foreach ( $this->global_groups as $group ) { $this->group_type[ $group ] = 'global'; } foreach ( $this->unflushable_groups as $group ) { $this->group_type[ $group ] = 'unflushable'; } foreach ( $this->ignored_groups as $group ) { $this->group_type[ $group ] = 'ignored'; } } /** * Do the necessary Data Definition Language work. * * @return void * @throws Exception If something fails. * @noinspection SqlResolve */ private function create_object_cache_table() { /* NOTE WELL: SQL in this file is not for use with $wpdb, but for SQLite3 */ $this->sqlite->exec( 'BEGIN' ); /* does our table exist? */ $q = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND tbl_name = '$this->cache_table_name';"; $r = $this->sqlite->querySingle( $q ); if ( 0 === $r ) { /* later versions of SQLite3 have clustered primary keys, "WITHOUT ROWID" */ $uses_rowid = version_compare( $this->sqlite_get_version(), '3.8.2' ) < 0; if ( $uses_rowid ) { /* @noinspection SqlIdentifier */ $t = " CREATE TABLE IF NOT EXISTS $this->cache_table_name ( name TEXT NOT NULL COLLATE BINARY, value BLOB, expires INT ); CREATE UNIQUE INDEX IF NOT EXISTS name ON $this->cache_table_name (name); CREATE INDEX IF NOT EXISTS expires ON $this->cache_table_name (expires);"; } else { /* @noinspection SqlIdentifier */ $t = " CREATE TABLE IF NOT EXISTS $this->cache_table_name ( name TEXT NOT NULL PRIMARY KEY COLLATE BINARY, value BLOB, expires INT ) WITHOUT ROWID; CREATE INDEX IF NOT EXISTS expires ON $this->cache_table_name (expires);"; } $this->sqlite->exec( $t ); } $this->sqlite->exec( 'COMMIT' ); } /** * Do the necessary Data Definition Language work. * * @param string $tbl The name of the table. * * @return void * @throws Exception If something fails. * @noinspection SqlResolve */ private function maybe_create_stats_table( $tbl ) { /* NOTE WELL: SQL in this file is not for use with $wpdb, but for SQLite3 */ $this->sqlite->exec( 'BEGIN' ); /* does our table exist? */ $q = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND tbl_name = '$tbl';"; $r = $this->sqlite->querySingle( $q ); if ( 0 === $r ) { /* @noinspection SqlIdentifier */ $t = " CREATE TABLE IF NOT EXISTS $tbl ( value BLOB, timestamp INT ); CREATE INDEX IF NOT EXISTS expires ON $tbl (timestamp);"; $this->sqlite->exec( $t ); } $this->sqlite->exec( 'COMMIT' ); } /** * Create the prepared statements to use. * * @param string $tbl Table name. * * @return void * @throws Exception Announce failure. * @noinspection SqlResolve */ private function prepare_statements( $tbl ) { /* NOTE WELL: SQL in this file is not for use with $wpdb, but for SQLite3 */ $now = time(); $this->getone = $this->sqlite->prepare( "SELECT value FROM $tbl WHERE name = :name AND expires >= $now;" ); $this->deleteone = $this->sqlite->prepare( "DELETE FROM $tbl WHERE name = :name;" ); $this->deletegroup = $this->sqlite->prepare( "DELETE FROM $tbl WHERE name LIKE :group || '.%';" ); /* * Some versions of SQLite3 built into php predate the 3.38 advent of unixepoch() (2022-02-22). * And, others predate the 3.24 advent of UPSERT (that is, ON CONFLICT) syntax. * In that case we have to do attempt-update then insert to get updates to work. Sigh. */ $has_upsert = version_compare( $this->sqlite_get_version(), '3.24', 'ge' ); if ( $has_upsert ) { $this->upsertone = $this->sqlite->prepare( "INSERT INTO $tbl (name, value, expires) VALUES (:name, :value, $now + :expires) ON CONFLICT(name) DO UPDATE SET value=excluded.value, expires=excluded.expires;" ); } else { $this->insertone = $this->sqlite->prepare( "INSERT INTO $tbl (name, value, expires) VALUES (:name, :value, $now + :expires);" ); $this->updateone = $this->sqlite->prepare( "UPDATE $tbl SET value = :value, expires = $now + :expires WHERE name = :name;" ); } } /** * Preload frequently accessed items. * * @param string $tbl Cache table name. * * @return void * @noinspection SqlResolve */ public function preload( $tbl ) { $list = [ 'options|%', 'default|%', 'posts|last_changed', 'terms|last_changed', 'site_options|%notoptions', 'transient|doing_cron', ]; $sql = ''; $clauses = []; foreach ( $list as $item ) { /* NOTE WELL: SQL in this file is not for use with $wpdb, but for SQLite3 */ $clauses [] = "SELECT name, value FROM $tbl WHERE name LIKE '$item'"; } $sql .= implode( ' UNION ALL ', $clauses ) . ';'; $resultset = $this->sqlite->query( $sql ); if ( ! $resultset ) { return; } while ( true ) { $row = $resultset->fetchArray( SQLITE3_NUM ); if ( ! $row ) { break; } list( $group, $key ) = explode( '|', $row[0], 2 ); $val = $this->maybe_unserialize( $row[1] ); /* Put the preloaded value into the cache. */ $this->cache[ $group ][ $key ] = $val; } } /** * Serialize data for persistence if need be. Use igbinary if available. * * @param mixed $data To be unserialized. * * @return string|mixed Data ready for use. */ private function maybe_unserialize( $data ) { if ( $this->has_igbinary ) { return igbinary_unserialize( $data ); } return maybe_unserialize( $data ); } /** * Determine whether we can use SQLite3. * * @param string $directory The directory to hold the .sqlite file. Default WP_CONTENT_DIR. * * @return bool|string true, or an error message. */ public static function has_sqlite( $directory = WP_CONTENT_DIR ) { if ( ! wp_is_writable( $directory ) ) { if ( ! function_exists( '__' ) ) { wp_load_translations_early(); } //TODO THIS goes someplace else return sprintf( /* translators: 1: WP_CONTENT_DIR */ __( 'The SQLite Object Cache cannot be activated because the %s directory is not writable.', 'sqlite-object-cache' ), $directory ); } if ( ! class_exists( 'SQLite3' ) || ! extension_loaded( 'sqlite3' ) ) { if ( ! function_exists( '__' ) ) { wp_load_translations_early(); } return __( 'The SQLite Object Cache cannot be activated because the SQLite3 extension is not loaded.', 'sqlite-object-cache' ); } return true; } /** * Set the monitoring options for the SQLite cache. * * Options in array [ * 'capture' => (bool) * 'resolution' => how often in seconds (float) * 'lifetime' => how long until entries expire in seconds (int) * 'verbose' => (bool) capture extra stuff. * ] * * @param array $options Option list. * * @return void */ public function set_sqlite_monitoring_options( $options ) { $this->monitoring_options = $options; } /** * Is recording this performance sample appropriate. * * We decide to take a performance sample based upon: * -- the sqlite_object_cache_settings option existing. * -- $option.capture having the 'on' value. * -- $option.samplerate >= 100 or samplerate greater than a random number. * * @return bool True if this sample should be recorded. */ private function is_sample() { $options = get_option( 'sqlite_object_cache_settings', 'missing_option' ); if ( 'missing_option' === $options ) { /* set an absent option to the empty array, so we don't repeatedly hammer the cache looking for a missing option */ update_option( 'sqlite_object_cache_settings', [], true ); return false; } if ( is_array( $options ) && array_key_exists( 'capture', $options ) && 'on' === $options['capture'] ) { if ( array_key_exists( 'samplerate', $options ) && is_numeric( $options['samplerate'] ) ) { /* samplerate is a percentage likelihood in the option setting */ $samplerate = $options['samplerate'] * 0.01; if ( $samplerate > 0.0 ) { /* a random sample at $samplerate */ if ( $samplerate >= 1.0 ) { return true; } return $samplerate >= lcg_value(); } } } return false; } /** * Capture statistics if need be, then close the connection. * * @return bool */ public function close() { $result = true; if ( $this->sqlite ) { if ( $this->is_sample() ) { $this->capture( $this->monitoring_options ); } $result = $this->sqlite->close(); $this->sqlite = null; } return $result; } /** * Generate canonical name for cache item * * @param string $key The key name. * @param string $group The group name. * * @return string The name. */ private function name_from_key_group( $key, $group ) { return $group . '|' . $key; } /** * Serialize data for persistence if need be. Use igbinary if available. * * @param mixed $data To be serialized. * * @return string|mixed Data ready for dbms insertion. */ private function maybe_serialize( $data ) { if ( $this->has_igbinary ) { return igbinary_serialize( $data ); } return maybe_serialize( $data ); } /** * Remove statistics entries from the cache * * @param int|null $age Number of seconds' worth to retain. Default: retain none. * * @return void */ public function sqlite_reset_statistics( $age = null ) { try { if ( ! $this->sqlite ) { $this->open_connection(); } $object_stats = self::OBJECT_STATS_TABLE; $this->maybe_create_stats_table( $object_stats ); /* NOTE WELL: SQL in this file is not for use with $wpdb, but for SQLite3 */ if ( ! is_numeric( $age ) ) { /* @noinspection SqlWithoutWhere */ $sql = "DELETE FROM $object_stats;"; } else { $expires = (int) ( time() - $age ); /* @noinspection SqlResolve */ $sql = "DELETE FROM $object_stats WHERE timestamp < $expires;"; } $this->sqlite->exec( $sql ); } catch ( Exception $ex ) { $this->error_log( 'SQLite Object Cache exception resetting statistics. ', $ex ); } } /** * Remove old entries and VACUUM the database. * * @param mixed $retention How long, in seconds, to keep old entries. Default one week. * @param bool $use_transaction True if the cleanup should be inside BEGIN / COMMIT. * @param bool $vacuum VACUUM the db. * * @return void * @noinspection SqlResolve */ public function sqlite_clean_up_cache( $retention = null, $use_transaction = true, $vacuum = false ) { /* NOTE WELL: SQL in this file is not for use with $wpdb, but for SQLite3 */ try { if ( ! $this->sqlite ) { $this->open_connection(); } if ( $use_transaction ) { $this->sqlite->exec( 'BEGIN' ); } /* Remove items with definite expirations, like transients */ $sql = "DELETE FROM $this->cache_table_name WHERE expires <= :now;"; $stmt = $this->sqlite->prepare( $sql ); $stmt->bindValue( ':now', time(), SQLITE3_INTEGER ); $result = $stmt->execute(); $result->finalize(); /* Remove old items. We use the most recent update time. Tracking use time is too expensive. */ $retention = is_numeric( $retention ) ? $retention : $this->max_lifetime; $sql = "DELETE FROM $this->cache_table_name WHERE expires BETWEEN :offset AND :end;"; $stmt = $this->sqlite->prepare( $sql ); $offset = $this->noexpire_timestamp_offset; $end = time() + $offset - $retention; $stmt->bindValue( ':offset', $offset, SQLITE3_INTEGER ); $stmt->bindValue( ':end', $end, SQLITE3_INTEGER ); $result = $stmt->execute(); $result->finalize(); if ( $use_transaction ) { $this->sqlite->exec( 'COMMIT' ); } if ( $vacuum ) { $this->sqlite->exec( 'VACUUM' ); $this->sqlite->exec( 'PRAGMA analysis_limit=400' ); $this->sqlite->exec( 'PRAGMA optimize' ); } } catch ( Exception $ex ) { $this->error_log( 'sqlite_clean_up_cache', $ex ); } } /** * Read object names, sizes, expirations from cache. * * @param $timestamps true If the timestamps returned should be expirations, false means raw * * @return Generator of name/length/timestamp rows. * @throws Exception Announce SQLite failure. * @noinspection SqlResolve */ public function sqlite_load_usages( $timestamps = true ) { if ( ! $this->sqlite ) { $this->open_connection(); } $object_cache = self::OBJECT_CACHE_TABLE; $sql = "SELECT name, LENGTH(value) length, expires FROM $object_cache"; $stmt = $this->sqlite->prepare( $sql ); $resultset = $stmt->execute(); while ( true ) { $row = $resultset->fetchArray( SQLITE3_ASSOC ); if ( ! $row ) { break; } $row = (object) $row; if ( $timestamps ) { $expires = $row->expires; if ( $expires >= self::NOEXPIRE_TIMESTAMP_OFFSET ) { $expires -= self::NOEXPIRE_TIMESTAMP_OFFSET; } $row->expires = $expires; } yield $row; } $resultset->finalize(); } /** * Read rows from the stored statistics. * * @return Generator * @throws Exception Announce SQLite failure. * @noinspection SqlResolve */ public function sqlite_load_statistics() { if ( ! $this->sqlite ) { $this->open_connection(); } $object_stats = self::OBJECT_STATS_TABLE; $this->maybe_create_stats_table( $object_stats ); $sql = "SELECT value FROM $object_stats;"; $stmt = $this->sqlite->prepare( $sql ); $resultset = $stmt->execute(); while ( true ) { $row = $resultset->fetchArray( SQLITE3_NUM ); if ( ! $row ) { break; } $value = $this->maybe_unserialize( $row[0] ); yield (object) $value; } $resultset->finalize(); } /** * Do the performance-capture operation. * * Put a row named sqlite_object_cache.mon.123456 into sqlite containing the raw data. * * @param array $options Contents of $this->monitoring_options. * * @return void * @noinspection SqlResolve */ private function capture( $options ) { $now = microtime( true ); global $wpdb; $record = [ 'time' => $now, 'RAMhits' => $this->cache_hits, 'RAMmisses' => $this->cache_misses, 'DISKhits' => $this->persistent_hits, 'DISKmisses' => $this->persistent_misses, 'open' => $this->open_time, 'selects' => $this->select_times, 'inserts' => $this->insert_times, 'deletes' => $this->delete_times, 'DBMSqueries' => $wpdb->num_queries, ]; if ( is_array( $options ) && $options['verbose'] ) { $record ['select_names'] = $this->select_names; $record ['delete_names'] = $this->insert_names; } $object_stats = self::OBJECT_STATS_TABLE; try { if ( ! $this->sqlite ) { $this->open_connection(); } $this->maybe_create_stats_table( $object_stats ); $sql = "INSERT INTO $object_stats (value, timestamp) VALUES (:value, :timestamp);"; $stmt = $this->sqlite->prepare( $sql ); $stmt->bindValue( ':value', $this->maybe_serialize( $record ), SQLITE3_BLOB ); $stmt->bindValue( ':timestamp', time(), SQLITE3_INTEGER ); $result = $stmt->execute(); $result->finalize(); } catch ( Exception $ex ) { $this->error_log( 'error capturing performance stats, skipping.', $ex ); } unset( $record, $stmt ); } /** * Get the version of SQLite in use. * * @return string */ public function sqlite_get_version() { $v = SQLite3::version(); return $v['versionString']; } /** * Sets the list of groups not to be cached by Redis. * * @param array $groups List of groups that are to be ignored. */ public function add_non_persistent_groups( $groups ) { /** * Filters list of groups to be added to {@see self::$ignored_groups} * * @param string[] $groups List of groups to be ignored. * * @since 2.1.7 */ $groups = apply_filters( 'sqlite_object_cache_add_non_persistent_groups', (array) $groups ); $this->ignored_groups = array_unique( array_merge( $this->ignored_groups, $groups ) ); $this->cache_group_types(); } /** * Makes private properties readable for backward compatibility. * * @param string $name Property to get. * * @return mixed Property. * @since 4.0.0 */ public function __get( $name ) { return $this->$name; } /** * Makes private properties settable for backward compatibility. * * @param string $name Property to set. * @param mixed $value Property value. * * @return mixed Newly-set property. * @since 4.0.0 */ public function __set( $name, $value ) { return $this->$name = $value; } /** * Makes private properties checkable for backward compatibility. * * @param string $name Property to check if set. * * @return bool Whether the property is set. * @since 4.0.0 */ public function __isset( $name ) { return isset( $this->$name ); } /** * Makes private properties un-settable for backward compatibility. * * @param string $name Property to unset. * * @since 4.0.0 */ public function __unset( $name ) { unset( $this->$name ); } /** * Adds multiple values to the cache in one call. * * @param array $data Array of keys and values to be added. * @param string $group Optional. Where the cache contents are grouped. Default empty. * @param int $expire Optional. When to expire the cache contents, in seconds. * Default 0 (no expiration). * * @return bool[] Array of return values, grouped by key. Each value is either * true on success, or false if cache key and group already exist. * @since 6.0.0 */ public function add_multiple( array $data, $group = '', $expire = 0 ) { $values = []; try { if ( ! $this->sqlite ) { $this->open_connection(); } /* use a transaction to accelerate add_multiple */ $this->transaction_active = true; $this->sqlite->exec( 'BEGIN' ); foreach ( $data as $key => $value ) { $values[ $key ] = $this->add( $key, $value, $group, $expire ); } $this->sqlite->exec( 'COMMIT' ); $this->transaction_active = false; } catch ( Exception $ex ) { $this->error_log( 'add_multiple', $ex ); $this->delete_offending_files(); self::drop_dead(); } return $values; } /** * Adds data to the cache if it doesn't already exist. * * @param int|string $key What to call the contents in the cache. * @param mixed $data The contents to store in the cache. * @param string $group Optional. Where to group the cache contents. Default 'default'. * @param int $expire Optional. When to expire the cache contents, in seconds. * Default 0 (no expiration). * * @return bool True on success, false if cache key and group already exist. * @throws Exception Announce database failure. * @since 2.0.0 * * @uses WP_Object_Cache::cache_item_exists() Checks to see if the cache already has data. * @uses WP_Object_Cache::set() Sets the data after the checking the cache * contents existence. */ public function add( $key, $data, $group = 'default', $expire = 0 ) { if ( wp_suspend_cache_addition() ) { return false; } if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } $id = $key; if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $id = $this->blog_prefix . $key; } if ( $this->cache_item_exists( $id, $group ) ) { return false; } return $this->set( $key, $data, $group, (int) $expire ); } /** * Serves as a utility function to determine whether a key is valid. * * @param int|string $key Cache key to check for validity. * * @return bool Whether the key is valid. * @since 6.1.0 */ protected function is_valid_key( $key ) { if ( is_int( $key ) ) { return true; } if ( is_string( $key ) && trim( $key ) !== '' ) { return true; } $type = gettype( $key ); if ( ! function_exists( '__' ) ) { wp_load_translations_early(); } $message = is_string( $key ) ? __( 'Cache key must not be an empty string.' ) /* translators: %s: The type of the given cache key. */ : sprintf( __( 'Cache key must be integer or non-empty string, %s given.' ), $type ); // phpcs:ignore _doing_it_wrong( sprintf( '%s::%s', __CLASS__, debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 )[1]['function'] ), $message, '6.1.0' ); return false; } /** * Determine whether a key exists in the cache. * * @param int|string $key Cache key to check for existence. * @param string $group Cache group for the key existence check. * * @return bool Whether the key exists in the cache for the given group. * @throws Exception Announce database failure. * @since 3.4.0 */ protected function cache_item_exists( $key, $group ) { $exists = isset( $this->cache[ $group ] ) && ( isset( $this->cache[ $group ][ $key ] ) || array_key_exists( $key, $this->cache[ $group ] ) ); if ( ! $exists ) { $val = $this->getone( $key, $group ); if ( null !== $val ) { if ( ! array_key_exists( $group, $this->cache ) ) { $this->cache [ $group ] = []; } $this->cache[ $group ][ $key ] = $val; $exists = true; $this->persistent_hits ++; } else { $this->persistent_misses ++; } } return $exists; } /** * Get one item from external cache. * * @param string $key Cache key. * @param string $group Group name. * * @return mixed|null Cached item, or null if not found. (Cached item can be false.) * @throws Exception Announce database failure. */ private function getone( $key, $group ) { $start = $this->time_usec(); $name = $this->name_from_key_group( $key, $group ); if ( array_key_exists( $name, $this->not_in_persistent_cache ) ) { return null; } $data = null; try { if ( ! $this->sqlite ) { $this->open_connection(); } $stmt = $this->getone; $stmt->bindValue( ':name', $name, SQLITE3_TEXT ); $result = $stmt->execute(); $row = $result->fetchArray( SQLITE3_NUM ); $data = false !== $row && is_array( $row ) && 1 === count( $row ) ? $row[0] : null; if ( null !== $data ) { $data = $this->maybe_unserialize( $data ); $this->in_persistent_cache [ $name ] = true; } else { $this->not_in_persistent_cache [ $name ] = true; } $result->finalize(); } catch ( Exception $ex ) { unset( $this->in_persistent_cache[ $name ] ); $this->not_in_persistent_cache [ $name ] = true; $this->error_log( 'getone', $ex ); $this->delete_offending_files(); self::drop_dead(); } $this->select_times[] = $this->time_usec() - $start; $this->select_names[] = $name; return $data; } /** * Sets the data contents into the cache. * * The cache contents are grouped by the $group parameter followed by the * $key. This allows for duplicate IDs in unique groups. Therefore, naming of * the group should be used with care and should follow normal function * naming guidelines outside of core WordPress usage. * * The $expire parameter is not used, because the cache will automatically * expire for each time a page is accessed and PHP finishes. The method is * more for cache plugins which use files. * * @param int|string $key What to call the contents in the cache. * @param mixed $data The contents to store in the cache. * @param string $group Optional. Where to group the cache contents. Default 'default'. * @param int $expire Optional. Not used. * * @return bool True if contents were set, false if key is invalid. * @since 2.0.0 * @since 6.1.0 Returns false if cache key is invalid. * */ public function set( $key, $data, $group = 'default', $expire = 0 ) { if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $key = $this->blog_prefix . $key; } if ( is_object( $data ) ) { $data = clone $data; } $this->cache[ $group ][ $key ] = $data; $this->handle_put( $key, $data, $group, $expire ); return true; } /** * Write to the persistent cache. * * @param int|string $key What to call the contents in the cache. * @param mixed $data The contents to store in the cache. * @param string $group Optional. Where to group the cache contents. Default 'default'. * @param int $expire Optional. Not used. * * @return void */ private function handle_put( $key, $data, $group, $expire ) { if ( $this->is_ignored_group( $group ) ) { return; } try { if ( ! $this->sqlite ) { $this->open_connection(); } $name = $this->name_from_key_group( $key, $group ); $start = $this->time_usec(); $value = $this->maybe_serialize( $data ); $expires = $expire ?: $this->noexpire_timestamp_offset; if ( $this->upsertone ) { $stmt = $this->upsertone; $stmt->bindValue( ':name', $name, SQLITE3_TEXT ); $stmt->bindValue( ':value', $value, SQLITE3_BLOB ); $stmt->bindValue( ':expires', $expires, SQLITE3_INTEGER ); $result = $stmt->execute(); $result->finalize(); } else { /* Pre-upsert version (pre- 3.24) of SQLite, * Need to try update, then do insert if need be. * Race conditions are possible, hence BEGIN / COMMIT */ if ( ! $this->transaction_active ) { $this->sqlite->exec( 'BEGIN' ); } $stmt = $this->updateone; $stmt->bindValue( ':name', $name, SQLITE3_TEXT ); $stmt->bindValue( ':value', $value, SQLITE3_BLOB ); $stmt->bindValue( ':expires', $expires, SQLITE3_INTEGER ); $result = $stmt->execute(); $result->finalize(); if ( 0 === $this->sqlite->changes() ) { /* Updated zero rows, so we need an insert. */ $stmt = $this->insertone; $stmt->bindValue( ':name', $name, SQLITE3_TEXT ); $stmt->bindValue( ':value', $value, SQLITE3_BLOB ); $stmt->bindValue( ':expires', $expires, SQLITE3_INTEGER ); $result = $stmt->execute(); $result->finalize(); } if ( ! $this->transaction_active ) { $this->sqlite->exec( 'COMMIT' ); } } } catch ( Exception $ex ) { $this->error_log( 'handle_put', $ex ); $this->delete_offending_files(); self::drop_dead(); } unset( $this->not_in_persistent_cache[ $name ] ); $this->in_persistent_cache[ $name ] = true; /* track how long it took. */ $this->insert_times[] = $this->time_usec() - $start; $this->insert_names[] = $name; } /** * Replaces the contents in the cache, if contents already exist. * * @param int|string $key What to call the contents in the cache. * @param mixed $data The contents to store in the cache. * @param string $group Optional. Where to group the cache contents. Default 'default'. * @param int $expire Optional. When to expire the cache contents, in seconds. * Default 0 (no expiration). * * @return bool True if contents were replaced, false if original value does not exist. * @see WP_Object_Cache::set() * * @since 2.0.0 * */ public function replace( $key, $data, $group = 'default', $expire = 0 ) { if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } $id = $key; if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $id = $this->blog_prefix . $key; } if ( ! $this->cache_item_exists( $id, $group ) ) { return false; } return $this->set( $key, $data, $group, (int) $expire ); } /** * Sets multiple values to the cache in one call. * * @param array $data Array of key and value to be set. * @param string $group Optional. Where the cache contents are grouped. Default empty. * @param int $expire Optional. When to expire the cache contents, in seconds. * Default 0 (no expiration). * * @return bool[] Array of return values, grouped by key. Each value is always true. * @since 6.0.0 */ public function set_multiple( array $data, $group = '', $expire = 0 ) { $values = []; try { if ( ! $this->sqlite ) { $this->open_connection(); } /* use a transaction to accelerate set_multiple */ $this->transaction_active = true; $this->sqlite->exec( 'BEGIN' ); foreach ( $data as $key => $value ) { $values[ $key ] = $this->set( $key, $value, $group, $expire ); } $this->sqlite->exec( 'COMMIT' ); $this->transaction_active = false; } catch ( Exception $ex ) { $this->error_log( 'set_multiple', $ex ); $this->delete_offending_files(); self::drop_dead(); } return $values; } /** * Retrieves multiple values from the cache in one call. * * @param array $keys Array of keys under which the cache contents are stored. * @param string $group Optional. Where the cache contents are grouped. Default 'default'. * @param bool $force Optional. Whether to force an update of the local cache * from the persistent cache. Default false. * * @return array Array of return values, grouped by key. Each value is either * the cache contents on success, or false on failure. * @since 5.5.5 */ public function get_multiple( $keys, $group = 'default', $force = false ) { $values = []; try { if ( ! $this->sqlite ) { $this->open_connection(); } /* use a transaction to accelerate get_multiple */ $this->transaction_active = true; $this->sqlite->exec( 'BEGIN' ); foreach ( $keys as $key ) { $values[ $key ] = $this->get( $key, $group, $force ); } $this->sqlite->exec( 'COMMIT' ); $this->transaction_active = false; } catch ( Exception $ex ) { $this->error_log( 'get_multiple', $ex ); $this->delete_offending_files(); self::drop_dead(); } return $values; } /** * Retrieves the cache contents, if it exists. * * The contents will be first attempted to be retrieved by searching by the * key in the cache group. If the cache is hit (success) then the contents * are returned. * * On failure, the number of cache misses will be incremented. * * @param int|string $key The key under which the cache contents are stored. * @param string $group Optional. Where the cache contents are grouped. Default 'default'. * @param bool $force Optional. Whether to force an update of the local cache * from the persistent cache. Default false. * @param bool $found Optional. Whether the key was found in the cache (passed by reference). * Disambiguates a return of false, a storable value. Default null. * * @return mixed|false The cache contents on success, false on failure to retrieve contents. * @since 2.0.0 */ public function get( $key, $group = 'default', $force = false, &$found = null ) { if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $key = $this->blog_prefix . $key; } if ( $force ) { unset( $this->cache[ $group ][ $key ] ); } try { if ( $this->cache_item_exists( $key, $group ) ) { $found = true; ++ $this->cache_hits; if ( is_object( $this->cache[ $group ][ $key ] ) ) { return clone $this->cache[ $group ][ $key ]; } return $this->cache[ $group ][ $key ]; } } catch ( Exception $ex ) { $this->delete_offending_files(); return false; } $found = false; $this->cache_misses ++; return false; } /** * Deletes multiple values from the cache in one call. * * @param array $keys Array of keys to be deleted. * @param string $group Optional. Where the cache contents are grouped. Default empty. * * @return bool[] Array of return values, grouped by key. Each value is either * true on success, or false if the contents were not deleted. * @since 6.0.0 */ public function delete_multiple( array $keys, $group = '' ) { $values = []; foreach ( $keys as $key ) { $values[ $key ] = $this->delete( $key, $group ); } return $values; } /** * Removes the contents of the cache key in the group. * * If the cache key does not exist in the group, then nothing will happen. * * @param int|string $key What the contents in the cache are called. * @param string $group Optional. Where the cache contents are grouped. Default 'default'. * @param bool $deprecated Optional. Unused. Default false. * * @return bool True on success, false if the contents were not deleted. * @since 2.0.0 * */ public function delete( $key, $group = 'default', $deprecated = false ) { if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $key = $this->blog_prefix . $key; } try { if ( ! $this->cache_item_exists( $key, $group ) ) { return false; } } catch ( Exception $ex ) { $this->delete_offending_files(); return true; } unset( $this->cache[ $group ][ $key ] ); $this->handle_delete( $key, $group ); return true; } /** * Delete from the persistent cache. * * @param int|string $key What to call the contents in the cache. * @param string $group Optional. Where to group the cache contents. Default 'default'. * * @return void */ private function handle_delete( $key, $group ) { $name = $this->name_from_key_group( $key, $group ); $start = $this->time_usec(); $stmt = $this->deleteone; try { if ( ! $this->sqlite ) { $this->open_connection(); } $stmt->bindValue( ':name', $name, SQLITE3_TEXT ); $result = $stmt->execute(); $result->finalize(); } catch ( Exception $ex ) { $this->delete_offending_files(); } unset( $this->in_persistent_cache[ $name ] ); $this->not_in_persistent_cache[ $name ] = true; /* track how long it took. */ $this->delete_times[] = $this->time_usec() - $start; } /** * Increments numeric cache item's value. * * @param int|string $key The cache key to increment. * @param int $offset Optional. The amount by which to increment the item's value. * Default 1. * @param string $group Optional. The group the key is in. Default 'default'. * * @return int|false The item's new value on success, false on failure. * @since 3.3.0 */ public function incr( $key, $offset = 1, $group = 'default' ) { if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $key = $this->blog_prefix . $key; } if ( ! $this->cache_item_exists( $key, $group ) ) { return false; } if ( ! is_numeric( $this->cache[ $group ][ $key ] ) ) { $this->cache[ $group ][ $key ] = 0; } $offset = (int) $offset; $this->cache[ $group ][ $key ] += $offset; if ( $this->cache[ $group ][ $key ] < 0 ) { $this->cache[ $group ][ $key ] = 0; } $this->handle_put( $key, $group, $this->cache[ $group ][ $key ], 0 ); return $this->cache[ $group ][ $key ]; } /** * Decrements numeric cache item's value. * * @param int|string $key The cache key to decrement. * @param int $offset Optional. The amount by which to decrement the item's value. * Default 1. * @param string $group Optional. The group the key is in. Default 'default'. * * @return int|false The item's new value on success, false on failure. * @since 3.3.0 * */ public function decr( $key, $offset = 1, $group = 'default' ) { if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $key = $this->blog_prefix . $key; } if ( ! $this->cache_item_exists( $key, $group ) ) { return false; } if ( ! is_numeric( $this->cache[ $group ][ $key ] ) ) { $this->cache[ $group ][ $key ] = 0; } $offset = (int) $offset; $this->cache[ $group ][ $key ] -= $offset; if ( $this->cache[ $group ][ $key ] < 0 ) { $this->cache[ $group ][ $key ] = 0; } $this->handle_put( $key, $group, $this->cache[ $group ][ $key ], 0 ); return $this->cache[ $group ][ $key ]; } /** * Clears the object cache of all data. * * @param bool $vacuum True to do a VACUUM operation. * * @return bool Always returns true. * @since 2.0.0 */ public function flush( $vacuum = false ) { /* NOTE WELL: SQL in this file is not for use with $wpdb, but for SQLite3 */ try { if ( ! $this->sqlite ) { $this->open_connection(); } $this->cache = []; $this->not_in_persistent_cache = []; $selective = defined( 'WP_SQLITE_OBJECT_CACHE_SELECTIVE_FLUSH' ) ? WP_SQLITE_OBJECT_CACHE_SELECTIVE_FLUSH : null; if ( $selective && is_array( $this->unflushable_groups ) && count( $this->unflushable_groups ) > 0 ) { $clauses = []; foreach ( $this->unflushable_groups as $unflushable_group ) { $unflushable_group = sanitize_key( $unflushable_group ); $clauses [] = "(name NOT LIKE '$unflushable_group|%')"; } /* @noinspection SqlConstantCondition, SqlConstantExpression */ $sql = 'DELETE FROM ' . $this->cache_table_name . ' WHERE ' . implode( ' AND ', $clauses ) . ';'; } else { /* SQLite's TRUNCATE TABLE equivalent */ $sql = 'DELETE FROM ' . $this->cache_table_name . ';'; } $this->sqlite->exec( $sql ); if ( $vacuum ) { $this->sqlite->exec( 'VACUUM;' ); } } catch ( Exception $ex ) { $this->error_log( 'flush', $ex ); $this->delete_offending_files(); self::drop_dead(); } return true; } /** * Clears the in-memory cache of all data leaving the external cache untouched. * * @return bool Always returns true. * @since 2.0.0 */ public function flush_runtime() { $this->cache = []; $this->not_in_persistent_cache = []; $this->in_persistent_cache = []; return true; } /** * Removes all cache items in a group. * * @param string $group Name of group to remove from cache. * * @return true Always returns true. * @since 6.1.0 */ public function flush_group( $group ) { try { if ( ! $this->sqlite ) { $this->open_connection(); } $start = $this->time_usec(); unset( $this->cache[ $group ] ); $stmt = $this->deletegroup; $stmt->bindValue( ':group', $group, SQLITE3_TEXT ); $result = $stmt->execute(); $result->finalize(); } catch ( Exception $ex ) { $this->error_log( 'flush_group', $ex ); $this->delete_offending_files(); self::drop_dead(); } /* remove hints about what is in the persistent cache */ $this->not_in_persistent_cache = []; $this->in_persistent_cache = []; return true; } /** * Sets the list of groups not to flushed cached. * * @param array $groups List of groups that are unflushable. */ public function add_unflushable_groups( $groups ) { $groups = (array) $groups; $this->unflushable_groups = array_unique( array_merge( $this->unflushable_groups, $groups ) ); $this->cache_group_types(); } /** * Sets the list of global cache groups. * * @param string|string[] $groups List of groups that are global. * * @since 3.0.0 */ public function add_global_groups( $groups ) { $groups = (array) $groups; $groups = array_fill_keys( $groups, true ); $this->global_groups = array_merge( $this->global_groups, $groups ); $this->cache_group_types(); } /** * Switches the internal blog ID. * * This changes the blog ID used to create keys in blog specific groups. * * @param int $blog_id Blog ID. * * @since 3.5.0 * */ public function switch_to_blog( $blog_id ) { $blog_id = (int) $blog_id; $this->blog_prefix = $this->multisite ? $blog_id . ':' : ''; } /** * Resets cache keys. * * @since 3.0.0 * * @deprecated 3.5.0 Use WP_Object_Cache::switch_to_blog() * @see switch_to_blog() */ public function reset() { _deprecated_function( __FUNCTION__, '3.5.0', 'WP_Object_Cache::switch_to_blog()' ); // Clear out non-global caches since the blog ID has changed. foreach ( array_keys( $this->cache ) as $group ) { if ( ! isset( $this->global_groups[ $group ] ) ) { unset( $this->cache[ $group ] ); } } } /** * Echoes the stats of the caching. * * Gives the cache hits, and cache misses. Also prints every cached group, * key and the data. * * @since 2.0.0 */ public function stats() { echo '
Cache Hits: ' . esc_html( $this->cache_hits ) . '
';
echo 'Cache Misses: ' . esc_html( $this->cache_misses ) . '