get_row( $wpdb->prepare( "SELECT data, expires FROM {$t['refs']} WHERE ref_key = %s", self::key( $key ) ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter if ( ! $row ) { return null; } if ( (int) $row->expires > 0 && (int) $row->expires < time() ) { return null; } $data = json_decode( $row->data, true ); return null === $data ? null : $data; } /** * Store a value. * * @param string $key Cache key. * @param mixed $data JSON-serialisable data. * @param int $ttl Seconds; 0 = no expiry. */ public static function set( $key, $data, $ttl = 0 ) { global $wpdb; $t = Schema::tables(); $wpdb->replace( // phpcs:ignore WordPress.DB.DirectDatabaseQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter $t['refs'], array( 'ref_key' => self::key( $key ), 'data' => wp_json_encode( $data ), 'expires' => $ttl > 0 ? time() + $ttl : 0, ), array( '%s', '%s', '%d' ) ); } /** * Remove expired rows. Every cached item has an expiry (checksums: 90 days), * so data of versions no longer installed disappears on its own. */ public static function purge() { global $wpdb; $t = Schema::tables(); $wpdb->query( $wpdb->prepare( "DELETE FROM {$t['refs']} WHERE expires > 0 AND expires < %d", time() ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter } /** * Keys longer than the column are hashed. * * @param string $key Cache key. * @return string */ private static function key( $key ) { return strlen( $key ) <= 191 ? $key : 'h:' . sha1( $key ); } }