From 5ec016004f366d92cb6662b1ca25d6aa47b20771 Mon Sep 17 00:00:00 2001 From: Kevin Burkholder <149023389+KBurkholder@users.noreply.github.com> Date: Fri, 5 Jan 2024 23:52:30 -0500 Subject: [PATCH] Initial commit --- .DS_Store | Bin 0 -> 6148 bytes .gitattributes | 2 + Extensions/.DS_Store | Bin 0 -> 6148 bytes Extensions/class.eacObjectCache.extension.php | 662 ++++++ LICENSE.md | 675 ++++++ eacObjectCache.php | 76 + readme.txt | 453 ++++ src/object-cache.php | 2035 +++++++++++++++++ src/wp-cache.php | 516 +++++ 9 files changed, 4419 insertions(+) create mode 100644 .DS_Store create mode 100644 .gitattributes create mode 100644 Extensions/.DS_Store create mode 100755 Extensions/class.eacObjectCache.extension.php create mode 100644 LICENSE.md create mode 100755 eacObjectCache.php create mode 100644 readme.txt create mode 100644 src/object-cache.php create mode 100644 src/wp-cache.php diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..87d7b57525c8d8fdf508c1f3113331c270d385f5 GIT binary patch literal 6148 zcmeHK&1xGl5FXiX?ZhqkkU#@D2zoWx#xW`6vUTlCE`@Gs5B+hxUXv_YuNLpR4j9As z(nFi~$TRc-+DGUc^gTKwO|Xq^=qWTs1EWu?nUQ8bkhB5-(VqAXfC>PVPzejW*lZB8 zldegQM;;*xJx2ry1fYP>ierIo`3zdiV?_L}RNm{S} z61jZg!NVd-x%k1oP*XSUr<0`JAHSoo*Gh%nZNKlm35L^NW$%TG(tZ#P$2uVJhv@SD zZ4mit+E$auPjswn3_B>j%E4^be0E%w&F0a(Drb#)t67z;qsDx`Q`&!8J9*W+3`ddr zX4n;Y_-J{|cnjCq*;t&P3_=f+rNE62;d#Rys8MWYihpkN8>vo*St=dg)XE<}|9HOL z*Z*tZ_+okejMCVc=O=d@g(^BnJJpiMb9W4bAMG^1#hz(! zBO+1-$*a^S={)EpMMON`bTgtU5mjh{EXs(8dDOM%!3RLrIWpaK_shP`xgVM6FPh}r z59xuf=$1O#`u>5Vzn(3Yd9~JE@aAGWah02->&vkG*nB_t;~ z){eyx9tc}1&{Ek;47POGlgHJL#n94;z4%~X`J;GYT^;i$4JWP*qYnmxfguC?Hk``+ ze~w>fw8$T(#3&dD2L2fXJZToq9GmjHb!U5W*Cw<}G!cm_qClVz9swB0IdY;-^C!^} YS34F%nMLfH4vdF@5)xf7@CyvQ1H{BNVE_OC literal 0 HcmV?d00001 diff --git a/Extensions/class.eacObjectCache.extension.php b/Extensions/class.eacObjectCache.extension.php new file mode 100755 index 0000000..b2b875f --- /dev/null +++ b/Extensions/class.eacObjectCache.extension.php @@ -0,0 +1,662 @@ + + * @copyright Copyright (c) 2023 EarthAsylum Consulting + * @version 1.x + * @link https://eacDoojigger.earthasylum.com/ + */ + + class object_cache_extension extends \EarthAsylumConsulting\abstract_extension + { + /** + * @var string extension version + */ + const VERSION = '23.1210.1'; + + + /** + * constructor method + * + * @param object $plugin main plugin object + * @return void + */ + public function __construct($plugin) + { + $this->enable_option = false; + parent::__construct($plugin, self::ALLOW_ADMIN|self::ONLY_ADMIN|self::ALLOW_NETWORK); + + if ($this->is_admin()) + { + $this->wpConfig = $this->wpconfig_handle(); + + $this->registerAs = 'Object Cache'; + $this->registerTab = + ($this->wpConfig && method_exists($this->plugin,'isAdvancedMode') && $this->plugin->isAdvancedMode('settings')) + ? 'Object Cache' + : 'Tools'; + + register_activation_hook(dirname(__DIR__).'/eacObjectCache.php',function() + { + $this->install_object_cache('update'); + } + ); + register_deactivation_hook(dirname(__DIR__).'/eacObjectCache.php',function() + { + $this->install_object_cache('delete'); + } + ); + $this->registerExtension( [$this->registerAs,$this->registerTab] ); + // Register plugin options when needed + $this->add_action( "options_settings_page", array($this, 'admin_options_settings') ); + // Add contextual help + $this->add_action( 'options_settings_help', array($this, 'admin_options_help') ); + } + } + + + /** + * register options on options_settings_page + * + * @return void + */ + public function admin_options_settings(): void + { + $check = $this->checkForInstall('version'); + + if ( $check !== true ) + { + $this->registerExtensionOptions( [$this->registerAs,$this->registerTab], + [ + '_sqlite_version' => array( + 'type' => 'display', + 'label' => 'Object Cache', + 'default' => $check['message'], + ), + ] + ); + return; + } + + $check = $this->checkForInstall('pdo'); + + if ( $check !== true ) + { + $this->registerExtensionOptions( [$this->registerAs,$this->registerTab], + [ + '_pdo_missing' => array( + 'type' => 'display', + 'label' => 'PHP Configuration', + 'default' => $check['message'], + ), + ] + ); + return; + } + + $check = $this->checkForInstall('existing'); + + if ( $check !== true ) + { + $this->registerExtensionOptions( [$this->registerAs,$this->registerTab], + [ + '_3rd_party' => array( + 'type' => 'display', + 'title' => $check['data']['Title'], + 'label' => 'Object Cache', + 'default' => $check['message'], + ), + ] + ); + return; + } + + if ($this->checkForInstall('admin') === true && $this->checkForInstall('source') === true) + { + $default = $this->varPost('_btnCacheInstall') ?: ((defined('EACDOOJIGGER_OBJECT_CACHE')) ? 'Install' : 'Uninstall'); + $default = ($default=='Install') ? 'Uninstall' : 'Install'; + $this->registerExtensionOptions( [$this->registerAs,$this->registerTab], + [ + '_btnCacheInstall' => array( + 'type' => 'button', + 'label' => 'Object Cache', + 'default' => $default, + 'info' => $default.' the {eac}ObjectCache drop-in.'. + '
* Requires write access to wp-content folder.', + 'validate' => [$this, 'install_object_cache'], + ), + ] + ); + } + + if (defined('EACDOOJIGGER_OBJECT_CACHE')) + { + global $wp_object_cache; + $stats = $wp_object_cache->getStats(); + $stats = $stats['database-groups']['Total'] ?? [0,0]; + $this->registerExtensionOptions( [$this->registerAs,$this->registerTab], + [ + '_btnCacheFlush' => array( + 'type' => 'button', + 'label' => 'Flush Objects', + 'default' => 'Erase Cache', + 'info' => 'Erase the persistent object cache.
'. + '* The cache database currently has '. + ''.number_format($stats[0],0).''. + ' records using over '. + ''.number_format($stats[1] / MB_IN_BYTES, 2).'mb'. + ' of storage.', + 'validate' => 'wp_cache_flush_blog', + ), + ] + ); + $this->registerExtensionOptions( [$this->registerAs,$this->registerTab], + [ + 'object_cache_stats' => array( + 'type' => 'radio', + 'label' => 'Show Stats', + 'options' => [ 'Disabled'=>'','Use Current Request'=>'current','Use Last Sample'=>'sample' ], + 'default' => '', + 'info' => 'Display object cache counts in a notification block on administrator pages.', + 'attributes'=> ['onchange'=>'options_form.submit()'], + ), + ] + ); + + // updates to wp-config.php... + + if (! $this->wpConfig) return; + + if (method_exists($this->plugin,'isAdvancedMode') && $this->plugin->isAdvancedMode('settings')) + { + $this->admin_options_settings_advanced(); + return; + } + + $this->registerExtensionOptions( [$this->registerAs,$this->registerTab], + [ + '_delayed_writes' => array( + 'type' => 'radio', + 'label' => 'Delayed Writes', + 'options' => [ 'Disabled'=>0, 'Enabled'=>1 ], + 'default' => ($wp_object_cache->delayed_writes) ? 1 : 0, + 'info' => 'When disabled all L2 cache updates occur in real time. '. + 'When enabled, updates are held until the end of the script/page.', + 'validate' => [$this,'validate_config_option'], + 'attributes'=> ['onchange'=>'options_form.submit()'], + ), + ] + ); + } + } + + + /** + * register advanced options on options_settings_page + * + * @return void + */ + public function admin_options_settings_advanced(): void + { + global $wp_object_cache; + + $this->registerExtensionOptions( [$this->registerAs,$this->registerTab], + [ + '_advanced' => array( + 'type' => 'display', + 'label' => '

', + 'default' => '

Advanced options update settings in the wp-config.php file.

', + ), + '_timeout' => array( + 'type' => 'number', + 'label' => 'Cache Timeout', + 'default' => (int)$wp_object_cache->pdo_timeout, + 'after' => ' seconds', + 'info' => 'Set the SQLite database timeout.', + 'attributes'=> ['min'=>'1','max'=>'20','step'=>'1'], + 'validate' => [$this,'validate_config_option'], + ), + + '_retries' => array( + 'type' => 'number', + 'label' => 'Cache Retries', + 'default' => (int)$wp_object_cache->max_retries, + 'info' => 'Set the number of retries to attempt on critical actions.', + 'attributes'=> ['min'=>'1','max'=>'6','step'=>'1'], + 'validate' => [$this,'validate_config_option'], + ), + + '_delayed_writes' => array( + 'type' => 'select', + 'label' => 'Delayed Writes', + 'options' => [ + "Disabled" => 0, // false + "8 Records" => 8, + "16 Records" => 16, + "32 Records" => 32, + "64 Records" => 64, + "128 Records" => 128, + "Unlimited" => 1, // true + ], + 'default' => (int)$wp_object_cache->delayed_writes, + 'info' => 'Set the number of records to hold in memory before writing to disk.', + 'help' => "[info] The lower the number, the more frequent disk writes but greater integrity. ". + "A Higher value means less writes but a little more risk. ". + "Records are always written at the end of the script process (page load).", + 'validate' => [$this,'validate_config_option'], + ), + + '_default_expire' => array( + 'type' => 'select', + 'label' => 'Default Expiration', + 'options' => [ + "Cache in memory only" => -1, + "Expire after 1 Minute" => MINUTE_IN_SECONDS, + "Expire after 5 Minutes" => MINUTE_IN_SECONDS * 5, + "Expire after 30 Minutes" => MINUTE_IN_SECONDS * 30, + "Expire after 1 Hour" => HOUR_IN_SECONDS, + "Expire after 12 Hours" => HOUR_IN_SECONDS * 12, + "Expire after 1 Day" => DAY_IN_SECONDS, + "Expire after 1 Week" => WEEK_IN_SECONDS, + "Expire after 1 Month" => MONTH_IN_SECONDS, + "No expiration" => 0, + ], + 'default' => $wp_object_cache->default_expire, + 'info' => 'Set the default when an object key does not specify an expiration time.', + 'help' => "[info] Cache persistence may sometimes causes issues. Here we can set a default expiration ". + "to alleviate problems and/or improve performance by limiting cache data.", + 'validate' => [$this,'validate_config_option'], + ), + + '_prefetch_misses' => array( + 'type' => 'radio', + 'label' => 'Pre-fetch Misses', + 'options' => ['Enabled'=>1,'Disabled'=>0], + 'default' => (int)$wp_object_cache->prefetch_misses, + 'info' => 'Pre-fetching cache misses prevents repeated, unnecessary reads of the L2 cache.', + 'validate' => [$this,'validate_config_option'], + ), + + '_probability' => array( + 'type' => 'select', + 'label' => 'Probablity Factor', + 'options' => [ + "1 in 10 Requests" => 10, + "1 in 50 Requests" => 50, + "1 in 100 Requests" => 100, + "1 in 250 Requests" => 250, + "1 in 500 Requests" => 500, + "1 in 1000 Requests" => 1000, + "1 in 2500 Requests" => 2500, + "1 in 5000 Requests" => 5000, + "1 in 10000 Requests" => 10000, + ], + 'default' => $wp_object_cache->gc_probability, + 'info' => 'Determines how often expired objects are purged and stats are sampled.', + 'validate' => [$this,'validate_config_option'], + ), + + '_nonp_groups' => array( + 'type' => 'textarea', + 'label' => "Non-Persistent Groups ", + 'default' => (defined('EAC_OBJECT_CACHE_NON_PERSISTENT_GROUPS') && is_array(EAC_OBJECT_CACHE_NON_PERSISTENT_GROUPS)) + ? implode(', ',EAC_OBJECT_CACHE_NON_PERSISTENT_GROUPS) : '', + 'info' => "Cache groups that should not be stored in the cache table.", + 'help' => "[info] Non-persistent groups are object groups that do not persist across page loads. ". + "This may be another method to alleviate issues caused by cache persistence ". + "or improve performance by limiting cache data.", + 'validate' => [$this,'validate_config_option'], + 'height' => '2', + ), + + '_prefetch_groups' => array( + 'type' => 'textarea', + 'label' => "Pre-fetch Groups ", + 'default' => (defined('EAC_OBJECT_CACHE_PREFETCH_GROUPS') && is_array(EAC_OBJECT_CACHE_PREFETCH_GROUPS)) + ? implode(', ',EAC_OBJECT_CACHE_PREFETCH_GROUPS) : '', + 'info' => "Pre-fetch specific object groups from disk at startup.", + 'help' => "[info] Pre-fretching a group of records may be much faster than loading each key individually, ". + "but may load keys that are not neaded, using memory unnecessarily.", + 'validate' => [$this,'validate_config_option'], + 'height' => '2', + ), + ] + ); + + // reload page after submit so we show changes to wp-config constants + $this->add_action('options_form_post', function($posted) + { + $this->page_reload(true); + } + ); + } + + + /** + * validate/set config options + * + * @return void + */ + public function validate_config_option($value, $fieldName, $metaData, $priorValue) + { + global $wp_object_cache; + switch ($fieldName) + { + case '_timeout': + if ($value == $wp_object_cache->pdo_timeout) return $value; // no change + $value = (is_numeric($value)) ? (int)$value : 3; + $this->wpConfig->update( 'constant', 'EAC_OBJECT_CACHE_TIMEOUT', "{$value}", ['raw'=>true] ); + break; + case '_retries': + if ($value == $wp_object_cache->max_retries) return $value; // no change + $value = (is_numeric($value)) ? (int)$value : 3; + $this->wpConfig->update( 'constant', 'EAC_OBJECT_CACHE_RETRIES', "{$value}", ['raw'=>true] ); + break; + case '_delayed_writes': + if ($value == (int)$wp_object_cache->delayed_writes) return $value; // no change + $value = ($value == 0) ? 'FALSE' : ( ($value == 1) ? 'TRUE' : (int)$value ); + $this->wpConfig->update( 'constant', 'EAC_OBJECT_CACHE_DELAYED_WRITES', "{$value}", ['raw'=>true] ); + break; + case '_default_expire': + if ($value == $wp_object_cache->default_expire) return $value; // no change + $value = (is_numeric($value)) ? (int)$value : -1; + $this->wpConfig->update( 'constant', 'EAC_OBJECT_CACHE_DEFAULT_EXPIRE', "{$value}", ['raw'=>true] ); + break; + case '_prefetch_misses': + if ($value == (int)$wp_object_cache->prefetch_misses) return $value; // no change + $value = ($value == 0) ? 'FALSE' : 'TRUE'; + $this->wpConfig->update( 'constant', 'EAC_OBJECT_CACHE_PREFETCH_MISSES', "{$value}", ['raw'=>true] ); + break; + case '_probability': + if ($value == $wp_object_cache->gc_probability) return $value; // no change + $value = (is_numeric($value)) ? (int)($value + ($value % 2)) : 100; + $this->wpConfig->update( 'constant', 'EAC_OBJECT_CACHE_PROBABILITY', "{$value}", ['raw'=>true] ); + break; + case '_nonp_groups': + $current = defined('EAC_OBJECT_CACHE_NON_PERSISTENT_GROUPS') ? EAC_OBJECT_CACHE_NON_PERSISTENT_GROUPS : []; + $value = array_filter(array_map('trim', explode("\n", str_replace([',',' '],"\n",$value)))); + if ($value == $current) return $value; + $value = (!empty($value)) ? "[ '".implode("', '",$value)."' ]" : '[]'; + $this->wpConfig->update( 'constant', 'EAC_OBJECT_CACHE_NON_PERSISTENT_GROUPS', "{$value}", ['raw'=>true] ); + break; + case '_prefetch_groups': + $current = defined('EAC_OBJECT_CACHE_PREFETCH_GROUPS') ? EAC_OBJECT_CACHE_PREFETCH_GROUPS : []; + $value = array_filter(array_map('trim', explode("\n", str_replace([',',' '],"\n",$value)))); + if ($value == $current) return $value; + $value = (!empty($value)) ? "[ '".implode("', '",$value)."' ]" : '[]'; + $this->wpConfig->update( 'constant', 'EAC_OBJECT_CACHE_PREFETCH_GROUPS', "{$value}", ['raw'=>true] ); + break; + } + } + + + /** + * Add help tab on admin page + * + * @return void + */ + public function admin_options_help() + { + if (!$this->plugin->isSettingsPage($this->registerTab)) return; + + ob_start(); + ?> + The {eac}Doojigger Object Cache is a light-weight and highly efficient drop-in persistent object cache + that uses a SQLite database to cache WordPress objects. + + See: The WordPress Object Cache + +
Configuration Options + {eac}ObjectCache configuration options may be set by adding defines in the wp-config.php file. +
    +
  • To set the location of the SQLite database (default: '../wp-content/cache'):
    + define( 'EAC_OBJECT_CACHE_DIR', '/full/path/to/folder' ); + +
  • To set the name of the SQLite database (default: '.eac_object_cache.sqlite'):
    + define( 'EAC_OBJECT_CACHE_FILE', 'filename.sqlite' ); + +
  • To set SQLite journal mode (default: 'WAL', Write-Ahead Log):
    + define( 'EAC_OBJECT_CACHE_JOURNAL_MODE', journal_mode ) +
    journal_mode is one of 'DELETE', 'TRUNCATE', 'PERSIST', 'MEMORY', 'WAL', or 'OFF' + +
  • To set SQLite timeout in seconds (default: 3)
    + define( 'EAC_OBJECT_CACHE_TIMEOUT', int ); + +
  • To set SQLite retries (default: 3)
    + define( 'EAC_OBJECT_CACHE_RETRIES', int ); + +
  • To set delayed writes (default: 32):
    + define( 'EAC_OBJECT_CACHE_DELAYED_WRITES', true|false|int ); +
    false = no delayed writes, true = write all records at end, +
    int = the number of records in memory before writing to disk.
    + +
  • To set the default expiration time (in seconds, default: 0)
    + define( 'EAC_OBJECT_CACHE_DEFAULT_EXPIRE', -1|0|int ); +
    -1 = don't cache to persistent database, 0 = never expire, int = number of seconds until expired. + +
  • To enable/disable pre-fetching of cache misses (default: true)
    + define('EAC_OBJECT_CACHE_PREFETCH_MISSES', true | false); + +
  • To set maintenance/sampling probability (default: 100)
    + define( 'EAC_OBJECT_CACHE_PROBABILITY', int ); + +
  • To set groups as global (not site-specific in multisite)
    + define( 'EAC_OBJECT_CACHE_GLOBAL_GROUPS', [ 'groupA', 'groupB', ... ] ); +
    WordPress automatically loads a list of global groups. + +
  • To set groups as non-persistant (not stored in the SQLite table)
    + define( 'EAC_OBJECT_CACHE_NON_PERSISTENT_GROUPS', [ 'groupA', 'groupB', ... ] ); +
    WordPress automatically loads a list of non-persistent groups. + +
  • To pre-fetch group(s) into memory at startup
    + define( 'EAC_OBJECT_CACHE_PREFETCH_GROUPS', [ 'groupA', 'groupB', ... ] ); +
+
+ addPluginHelpTab($this->registerTab,$content,['Object Cache','open']); + + $this->addPluginSidebarLink( + "{eac}ObjectCache", + "https://eacdoojigger.earthasylum.com/eacobjectcache/", + "{eac}ObjectCache Extension Plugin" + ); + } + + + /** + * initialize method - called from main plugin + * + * @return void + */ + public function initialize() + { + if ( ! parent::initialize() ) return; // disabled + + if (defined('EACDOOJIGGER_OBJECT_CACHE')) + { + global $wp_object_cache; + $wp_object_cache->display_stats = $this->get_option('object_cache_stats'); + $wp_object_cache->display_errors = true; + $wp_object_cache->log_errors = true; + } + } + + + /** + * Add filters and actions - called from main plugin + * + * @return void + */ + public function addActionsAndFilters() + { + parent::addActionsAndFilters(); + } + + + /** + * check installation criteria + * + * @return bool|array + */ + public function checkForInstall($check='all') + { + // check SQLite version + if ($check == 'all' || $check == 'version') + { + $version = (class_exists('\SQLite3')) ? \SQLite3::version()['versionString'] : ''; + if ( version_compare( $version, '3.8.0' ) < 0 ) + { + return [ + 'type' => 'version', + 'data' => $version, + 'message' => '{eac}ObjectCache requires SQLite v3.8.0 or greater. '. + ($version ? "Version {$version} is currently installed." : '').'.' + ]; + } + } + + // check PDO extensions + if ($check == 'all' || $check == 'pdo') + { + if ( ! extension_loaded( 'pdo' ) ) + { + return [ + 'type' => 'pdo', + 'message' => 'The PHP PDO Extension is not loaded.' + ]; + } + if ( ! extension_loaded( 'pdo_sqlite' ) ) + { + return [ + 'type' => 'pdo_sqlite', + 'message' => 'The PHP PDO Driver for SQLite is missing.' + ]; + } + } + + // check 3rd-party object cache + if ($check == 'all' || $check == 'existing') + { + if (file_exists(WP_CONTENT_DIR.'/object-cache.php') && !defined('EACDOOJIGGER_OBJECT_CACHE')) + { + $plugin_data = get_plugin_data( WP_CONTENT_DIR.'/object-cache.php', true ); + if ( ! $plugin_data['Title'] ) $plugin_data['Title'] = '3rd Party Object Cache'; + return [ + 'type' => 'exists', + 'data' => $plugin_data, + 'message' => 'a 3rd-party object cache drop-in is already installed '. + 'and must be removed before using {eac}ObjectCache.', + + ]; + } + } + + // check network admin + if ($check == 'all' || $check == 'admin') + { + if (is_multisite() && !$this->plugin->is_network_admin()) + { + return [ + 'type' => 'admin', + 'message' => 'You must be a network administrator.' + ]; + } + } + + // check source to install + if ($check == 'all' || $check == 'source') + { + if (!file_exists(dirname(__DIR__).'/src/object-cache.php')) + { + return [ + 'type' => 'source', + 'message' => 'The object-cache source file is missing.' + ]; + } + } + + return true; + } + + + /** + * install/uninstall object cache + * + * @param $action button ('Install' | 'Uninstall') or ('update' | 'delete') + * @return string $action + */ + public function install_object_cache($action) + { + if ($this->checkForInstall() !== true) + { + return false; + } + + $action = strtolower($action); + + if ($action == 'uninstall' || $action == 'delete') + { + global $wp_object_cache; + if (method_exists($wp_object_cache,'delete_cache_file')) { + $wp_object_cache->delete_cache_file(); + } + } + else if ($fs = $this->fs->load_wp_filesystem()) + { + $cache = (defined( 'EAC_OBJECT_CACHE_DIR' ) && is_string( EAC_OBJECT_CACHE_DIR )) + ? EAC_OBJECT_CACHE_DIR + : $fs->wp_content_dir().'/cache'; + + // since we write not using $fs, we need owner & group access + if (!$fs->exists($cache)) { + $fs->mkdir($cache,FS_CHMOD_DIR|0660); + } else { + $fs->chmod($cache,FS_CHMOD_DIR|0660); + } + } + + $this->installer->invoke($action,false, + [ + 'title' => 'The {eac}Doojigger Object Cache', + 'sourcePath' => dirname(__DIR__).'/src', + 'sourceFile' => 'object-cache.php', + 'targetPath' => WP_CONTENT_DIR, + 'targetFile' => 'object-cache.php', + 'return_url' => ($action != 'delete' && $action != 'update') + ? remove_query_arg('fs') : '', // force reload after manual install + ] + ); + return $action; + } + + + /** + * version updated + * + * @param string $curVersion currently installed version number + * @param string $newVersion version being installed/updated + * @return bool + */ + public function adminVersionUpdate($curVersion,$newVersion) + { + if (defined('EACDOOJIGGER_OBJECT_CACHE')) + { + $this->install_object_cache('update'); + } + } + } +} +/** + * return a new instance of this class + */ +if (isset($this)) return new object_cache_extension($this); +?> diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..2fb2e74 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,675 @@ +### GNU GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +### Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom +to share and change all versions of a program--to make sure it remains +free software for all its users. We, the Free Software Foundation, use +the GNU General Public License for most of our software; it applies +also to any other work released this way by its authors. You can apply +it to your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you +have certain responsibilities if you distribute copies of the +software, or if you modify it: responsibilities to respect the freedom +of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the +manufacturer can do so. This is fundamentally incompatible with the +aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for +individuals to use, which is precisely where it is most unacceptable. +Therefore, we have designed this version of the GPL to prohibit the +practice for those products. If such problems arise substantially in +other domains, we stand ready to extend this provision to those +domains in future versions of the GPL, as needed to protect the +freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish +to avoid the special danger that patents applied to a free program +could make it effectively proprietary. To prevent this, the GPL +assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + +### TERMS AND CONDITIONS + +#### 0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +#### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +#### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +#### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +#### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +#### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +#### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +#### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +#### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +#### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +#### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +#### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +#### 13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +#### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in +detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or +of any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public +License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU General Public License can be used, that proxy's public +statement of acceptance of a version permanently authorizes you to +choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +#### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +#### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +#### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +### How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively state +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper +mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands \`show w' and \`show c' should show the +appropriate parts of the General Public License. Of course, your +program's commands might be different; for a GUI interface, you would +use an "about box". + +You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU GPL, see . + +The GNU General Public License does not permit incorporating your +program into proprietary programs. If your program is a subroutine +library, you may consider it more useful to permit linking proprietary +applications with the library. If this is what you want to do, use the +GNU Lesser General Public License instead of this License. But first, +please read . diff --git a/eacObjectCache.php b/eacObjectCache.php new file mode 100755 index 0000000..c255065 --- /dev/null +++ b/eacObjectCache.php @@ -0,0 +1,76 @@ + + * @copyright Copyright (c) 2023 EarthAsylum Consulting + * @version 1.x + * @link https://eacDoojigger.earthasylum.com/ + * + * @wordpress-plugin + * Plugin Name: {eac}ObjectCache + * Description: {eac}Doojigger Object Cache - SQLite powered WP_Object_Cache Drop-in + * Version: 1.0.0 + * Requires at least: 5.5.0 + * Tested up to: 6.4 + * Requires PHP: 7.4 + * Plugin URI: https://eacdoojigger.earthasylum.com/eacobjectcache/ + * Author: EarthAsylum Consulting + * Author URI: http://www.earthasylum.com + * License: GPLv3 or later + * License URI: https://www.gnu.org/licenses/gpl.html + */ + +class eacObjectCache +{ + /** + * constructor method + * + * @return void + */ + public function __construct() + { + /** + * {pluginname}_load_extensions - get the extensions directory to load + * + * @param array $extensionDirectories - array of [plugin_slug => plugin_directory] + * @return array updated $extensionDirectories + */ + add_filter( 'eacDoojigger_load_extensions', function($extensionDirectories) + { + /* + * Enable update notice (self hosted or wp hosted) + */ + // eacDoojigger::loadPluginUpdater(__FILE__,'wp'); + + /* + * Add links on plugins page + */ + add_filter( (is_network_admin() ? 'network_admin_' : '').'plugin_action_links_' . plugin_basename( __FILE__ ), + function($pluginLinks, $pluginFile, $pluginData) { + return array_merge( + [ + 'settings' => eacDoojigger::getSettingsLink($pluginData,'tools'), + 'documentation' => eacDoojigger::getDocumentationLink($pluginData), + 'support' => eacDoojigger::getSupportLink($pluginData), + ], + $pluginLinks + ); + },20,3 + ); + + /* + * Add our extension to load + */ + $extensionDirectories[ plugin_basename( __FILE__ ) ] = [plugin_dir_path( __FILE__ ).'/Extensions']; + return $extensionDirectories; + } + ); + } +} +new \EarthAsylumConsulting\eacObjectCache(); +?> diff --git a/readme.txt b/readme.txt new file mode 100644 index 0000000..9d30504 --- /dev/null +++ b/readme.txt @@ -0,0 +1,453 @@ +=== {eac}ObjectCache - SQLite powered WP_Object_Cache Drop-in. === +Plugin URI: https://eacdoojigger.earthasylum.com/eacobjectcache/ +Author: [EarthAsylum Consulting](https://www.earthasylum.com) +Stable tag: 1.0.0 +Last Updated: 27-Dec-2023 +Requires at least: 5.5.0 +Tested up to: 6.4 +Requires PHP: 7.4 +Requires EAC: 2.4 +Contributors: kevinburkholder +License: GPLv3 or later +License URI: https://www.gnu.org/licenses/gpl.html +Tags: cache, object cache, wp cache, sqlite, performance, {eac}Doojigger, +WordPress URI: https://wordpress.org/plugins/eacobjectcache + +{eac}ObjectCache is a drop-in persistent object cache using a SQLite database to cache WordPress objects. + +== Description == + +The _{eac}Doojigger Object Cache_ ({eac}ObjectCache) is a light-weight and very efficient drop-in persistent object cache that uses a fast SQLite database to cache WordPress objects. + +See [The WordPress Object Cache](https://developer.wordpress.org/reference/classes/wp_object_cache/) + +> The WordPress Object Cache is used to save on trips to the database. The Object Cache stores all of the cache data to memory and makes the cache contents available by using a key, which is used to name and later retrieve the cache contents. + +> By default, the object cache is non-persistent. This means that data stored in the cache resides in memory only and only for the duration of the request. Cached data will not be stored persistently across page loads unless you install a persistent caching plugin. + +Here, an object is any piece of data - a number, text, a set of database records, an API response, etc. - that can be referenced by a name or key. Objects are categorized by a group name. Groups help identify what an object is and how it is used. + +{eac}ObjectCache replaces the default WordPress object cache to not only store data in memory but to also store data persistently, across requests, in a SQLite database, increasing the likelihood of cache hits and decreasing the need for costly computations, complex MySQL database queries, and remote API requests. + +SQLite is a fast, small, single-file relational database engine. By using SQLite to store objects, {eac}ObjectCache is able to manage a relatively large amount of data (groups, keys, and values) in a very efficient and fast data-store. + += Features = + ++ Lightweight, efficient, and fast! ++ L1 (memory) _and_ L2 (SQLite) caching. ++ Supports Write-Back (delayed transactions) or Write-Through caching. ++ Cache by object group name. + + Preserves uniqueness of keys. + + Manage keys by group name. ++ Pre-fetch object groups from L2 to L1 cache. ++ Caches and pre-fetches L2 misses (known to not be in L2 cache). + + Prevents repeated, unnecessary L2 cache reads across requests. ++ Multisite / Network support: + + Cache by blog id. + + Flush by blog id. ++ Caching statistics: + + Overall and L1/L2 hits, misses, & ratio. + + L1 hits by object groups. + + L2 group keys stored. + + L2 select/update/delete/commit counts. ++ Supports a superset of WP_Object_Cache functions. ++ Imports existing transients when enabled. ++ Easily enabled or disabled from administrator page. ++ Uses the PHP Data Objects (PDO) extension included with PHP. + + +== Settings == + +Several cache settings can be modified by adding defined constants to the `wp-config.php` file. The default settings are recommended and optimal in most cases but individual settings may need to be adjusted based on traffic volume, specific requirements, or unique circumstances. + +* * * + ++ To set the location of the SQLite database (default: ../wp-content/cache): + +``` + define( 'EAC_OBJECT_CACHE_DIR', '/full/path/to/folder' ); +``` + +This folder can be outside of the web-accessable folders of your site - i.e. above the document root (htdocs, www, etc.) - provided that PHP can access (read/write) the folder (see the PHP *open_basedir* directive). + +This folder should not be on a network share or other remote media. We're caching data for quick access, the cache folder should be on fast, local media. + +* * * + ++ To set the name of the SQLite database (default: '.eac_object_cache.sqlite'): + +``` + define( 'EAC_OBJECT_CACHE_FILE', 'filename.sqlite' ); +``` + +In addition to the database file, SQLite may also create temporary files using the same file name with a '-shm' and '-wal' suffix. + +* * * + ++ To set SQLite journal mode (default: 'WAL'): + +``` + define( 'EAC_OBJECT_CACHE_JOURNAL_MODE', journal_mode ) +``` + +*journal_mode* can be one of 'DELETE', 'TRUNCATE', 'PERSIST', 'MEMORY', 'WAL', or 'OFF'. +See [SQLite journal mode](https://www.sqlite.org/pragma.html#pragma_journal_mode) + +* * * + ++ To set SQLite timeout (default: 3): + +``` + define( 'EAC_OBJECT_CACHE_TIMEOUT', int ); +``` + +Sets the number of seconds before a SQLite transaction may timeout in error: + +* * * + ++ To set SQLite retries (default: 3): + +``` + define( 'EAC_OBJECT_CACHE_RETRIES', int ); +``` + +Sets the number of retries to attempt on critical actions. + +* * * + ++ To set delayed writes (default: 32): + +``` + define( 'EAC_OBJECT_CACHE_DELAYED_WRITES', true|false|int ); +``` + +{eac}ObjectCache caches all objects in memory and writes new or updated objects to the L2 (SQLite) cache. *delayed writes* simply holds objects in memory until the number of objects reaches a specified threshold, then writes them, in a single transaction, to the L2 cache (a.k.a. write-back caching). Setting *delayed writes* to false turns this functionality off (a.k.a. write-through caching). Setting to true writes all records only at the end of the script process/page load. Setting this to a number sets the object pending threshold to that number of objects. + +* * * + ++ To set the default expiration time (in seconds) (default: 0 [never]): + +``` + define( 'EAC_OBJECT_CACHE_DEFAULT_EXPIRE', -1|0|int ); +``` + +When using the default WordPress object cache, object expiration isn't very important because the entire cache expires at the end of the script process/page load. With a persistent cache, this isn't the case. When an object is cached, the developer has the option of specifying an expiration time for that object. Since we don't know the intent of the developer when not specifying an expiration time, cache persistence *may* sometimes cause issues. Setting *default expiration* may alleviate problems and/or possibly improve performance by limiting cache data. When set to -1, objects with no expiration are not saved in the L2 cache. + +_\* Transients with no expiration overide this setting and are allowed (as that is the normal WordPress functionality)._ + +_\* More often than not, unexpired objects are updated when the source data has changed and do not present any issues._ + +* * * + ++ To enable or disable pre-fetching of cache misses (default: true [enabled]): + +``` + define( 'EAC_OBJECT_CACHE_PREFETCH_MISSES', true | false ); +``` + +Pre-fetching cache misses (keys that are not in the L2 persistent cache) prevents repeated, unnecessary reads of the L2 cache. + +* * * + ++ To set maintenance/sampling probability (default: 100): + +``` + define( 'EAC_OBJECT_CACHE_PROBABILITY', int ); +``` + +Sets the probability of running maintenance & sampling tasks (approximately 1 in n requests). + +* * * + ++ Object groups that are global (not site-specific) in a multi-site/network environment: + +``` + define( 'EAC_OBJECT_CACHE_GLOBAL_GROUPS', [ 'groupA', 'groupB', ... ] ); +``` + +Global Object groups are not tagged with or separated by the site/blog id. + +_\* WordPress already defines several global groups that do not need to be duplicated here, rather the groups entered here are added to those defined by WordPress._ + + +* * * + ++ Object groups that should not be stored in the persistent cache: + +``` + define( 'EAC_OBJECT_CACHE_NON_PERSISTENT_GROUPS', [ 'groupA', 'groupB', ... ] ); +``` + +Non-persistent groups are object groups that do not persist across page loads. This may be another method to alleviate issues caused by cache persistence or to improve performance by limiting cache data. + +_\* WordPress already defines several non-persistent groups that do not need to be duplicated here, rather the groups entered here are added to those defined by WordPress._ + +* * * + ++ Object groups that are allowed permanence: + +``` + define( 'EAC_OBJECT_CACHE_PERMANENT_GROUPS', [ 'groupA', 'groupB', ... ] ); +``` + +When setting a default expiration (`EAC_OBJECT_CACHE_DEFAULT_EXPIRE`) for objects without an expiration, these groups are excluded from using the default, allowing them to be permanent (with no expiration). Transients and site-transients are automatically included. + +* * * + ++ To pre-fetch specific object groups from the L2 cache at startup: + +``` + define( 'EAC_OBJECT_CACHE_PREFETCH_GROUPS', [ 'groupA', 'groupB', ... ] ); +``` + +Pre-fetching a group of records may be much faster than loading each key individually, but may load keys that are not needed, using memory unnecessarily. + += Utility methods = + ++ Outputs an html table of current stats. Use `$wp_object_cache->statsCSS` to style. + +``` + $wp_object_cache->htmlStats(); +``` + ++ Outputs an html table of current stats similar to that generated by the default WordPress object cache. + +``` + $wp_object_cache->stats(); +``` + ++ Returns an array of current stats. + +``` + $wp_object_cache->getStats(); +``` + ++ Returns an array of stats from the last sample saved (or current). + +``` + $wp_object_cache->getLastSample(); +``` + += Optional runtime settings = + ++ Delay writing to database until shutdown or n pending records (see *delayed writes*). + +``` + $wp_object_cache->delayed_writes = true | false | n; +``` + ++ Outputs an administrator notice using htmlStats(). + +``` + $wp_object_cache->display_stats = true | 'current' | 'sample'; +``` + ++ Outputs an administrator notice on error. + +``` + $wp_object_cache->display_errors = true; +``` + ++ Log errors to {eac}Doojigger log. + +``` + $wp_object_cache->log_errors = true; +``` + + +== WP-Cache == + += Implemented Standard and Non-Standard WP-Cache API Functions: = + +[wp_cache_init](https://developer.wordpress.org/reference/functions/wp_cache_init/)() + +[wp_cache_add](https://developer.wordpress.org/reference/functions/wp_cache_add/)( $key, $data, $group = '', $expire = 0 ) + +[wp_cache_add_multiple](https://developer.wordpress.org/reference/functions/wp_cache_add_multiple/)( array $data, $group = '', $expire = 0 ) + +[wp_cache_replace](https://developer.wordpress.org/reference/functions/wp_cache_replace/)( $key, $data, $group = '', $expire = 0 ) + +wp_cache_replace_multiple( array $data, $group = '', $expire = 0 ) + +[wp_cache_set](https://developer.wordpress.org/reference/functions/wp_cache_set/)( $key, $data, $group = '', $expire = 0 ) + +[wp_cache_set_multiple](https://developer.wordpress.org/reference/functions/wp_cache_set_multiple/)( array $data, $group = '', $expire = 0 ) + +[wp_cache_get](https://developer.wordpress.org/reference/functions/wp_cache_get/)( $key, $group = '', $force = false, &$found = null ) + +[wp_cache_get_multiple](https://developer.wordpress.org/reference/functions/wp_cache_get_multiple/)( $keys, $group = '', $force = false ) + +[wp_cache_delete](https://developer.wordpress.org/reference/functions/wp_cache_delete/)( $key, $group = '' ) + +[wp_cache_delete_multiple](https://developer.wordpress.org/reference/functions/wp_cache_delete_multiple/)( array $keys, $group = '' ) + +[wp_cache_incr](https://developer.wordpress.org/reference/functions/wp_cache_incr/)( $key, $offset = 1, $group = '' ) + +[wp_cache_decr](https://developer.wordpress.org/reference/functions/wp_cache_decr/)( $key, $offset = 1, $group = '' ) + +[wp_cache_flush](https://developer.wordpress.org/reference/functions/wp_cache_flush/)() + +[wp_cache_flush_runtime](https://developer.wordpress.org/reference/functions/wp_cache_flush_runtime/)() + +[wp_cache_flush_group](https://developer.wordpress.org/reference/functions/wp_cache_flush_group/)( $group ) + +wp_cache_flush_blog( $blog_id = null ) + +[wp_cache_supports](https://developer.wordpress.org/reference/functions/wp_cache_supports/)( $feature ) + +[wp_cache_close](https://developer.wordpress.org/reference/functions/wp_cache_close/)() + +[wp_cache_add_global_groups](https://developer.wordpress.org/reference/functions/wp_cache_add_global_groups/)( $groups ) + +[wp_cache_add_non_persistent_groups](https://developer.wordpress.org/reference/functions/)( $groups ) + +wp_cache_add_permanent_groups( $groups ) + +wp_cache_add_prefetch_groups( $groups ) + +[wp_cache_switch_to_blog](https://developer.wordpress.org/reference/functions/wp_cache_switch_to_blog/)( $blog_id ) + + += Examples = + +```php + /* + * add custom groups to pre-fetch + */ + if (wp_cache_supports( 'prefetch_groups' )) { + wp_cache_add_prefetch_groups( [ 'ridiculous', 'absurd' ] ); + } + + /* + * calculate the sum of all digits in Pi multiplied by each known prime number... + * only do this once a year (or when cache is cleared) 'cause it may take a while. + */ + if ( ! $result = wp_cache_get('calculation_result','ridiculous') ) { + $result = do_calculation(); + wp_cache_set( 'calculation_result', $result, 'ridiculous', YEAR_IN_SECONDS ); + } + + /* + * erase the 'ridiculous' group + */ + wp_cache_flush_group( 'ridiculous' ); + + /* + * erase the cache for this blog only (multisite) + */ + if (wp_cache_supports( 'flush_blog' )) { + wp_cache_flush_blog(); + } +``` + + +== Installation == + +**{eac}ObjectCache** is an extension plugin to and requires installation and registration of [{eac}Doojigger](https://eacDoojigger.earthasylum.com/). + +_\* Currently pending approval from the WordPress Plugin Repository._ + += Automatic Plugin Installation = + +This plugin is available from the [WordPress Plugin Repository](https://wordpress.org/plugins/search/earthasylum/) and can be installed from the WordPress Dashboard » *Plugins* » *Add New* page. Search for 'EarthAsylum', click the plugin's [Install] button and, once installed, click [Activate]. + +See [Managing Plugins -> Automatic Plugin Installation](https://wordpress.org/support/article/managing-plugins/#automatic-plugin-installation-1) + += Upload via WordPress Dashboard = + +Installation of this plugin can be managed from the WordPress Dashboard » *Plugins* » *Add New* page. Click the [Upload Plugin] button, then select the eacobjectcache.zip file from your computer. + +See [Managing Plugins -> Upload via WordPress Admin](https://wordpress.org/support/article/managing-plugins/#upload-via-wordpress-admin) + += Manual Plugin Installation = + +You can install the plugin manually by extracting the eacobjectcache.zip file and uploading the 'eacobjectcache' folder to the 'wp-content/plugins' folder on your WordPress server. + +See [Managing Plugins -> Manual Plugin Installation](https://wordpress.org/support/article/managing-plugins/#manual-plugin-installation-1) + += Settings = + +Once installed and activated options for this extension will show in the 'Tools' or 'Object Cache' tab of {eac}Doojigger settings. + + +== Screenshots == + +1. Object Cache (Tools) +![{eac}ObjectCache](https://d2xk802d4616wu.cloudfront.net/eacobjectcache/assets/screenshot-1.png) + +2. Object Cache (Advanced Options) +![{eac}ObjectCache Advanced](https://d2xk802d4616wu.cloudfront.net/eacobjectcache/assets/screenshot-2.png) + +3. Object Cache (Cache Stats) +![{eac}ObjectCache Stats](https://d2xk802d4616wu.cloudfront.net/eacobjectcache/assets/screenshot-3.png) + + + +== Other Notes == + += Additional Information = + ++ {eac}ObjectCache is an extension plugin to and requires installation and registration of [{eac}Doojigger](https://eacDoojigger.earthasylum.com/). + + +== Copyright == + += Copyright © 2023, EarthAsylum Consulting, distributed under the terms of the GNU GPL. = + +This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should receive a copy of the GNU General Public License along with this program. If not, see [https://www.gnu.org/licenses/](https://www.gnu.org/licenses/). + + +== Changelog == + += Version 1.0.0 - December 9, 2023 = + ++ First public release. + += Version 0.5 = + ++ Testing in live, multisite environment. ++ Ignore 'force_cache' flag (force L2 read). + + if we've updated a key, but not written yet, then force a persistent load, we lose that value. ++ Added wp_flush_blog() function. ++ Cache L2 misses saving sqlite selects on records known to not exist. ++ Don't attempt read or delete on non-persistent groups. ++ Added cache hit ratio to stats. ++ Remove function call counts (for testing). + += Version 0.4 = + ++ Enhanced admin screen with advanced options. ++ Group constants used: + + EAC_OBJECT_CACHE_GLOBAL_GROUPS + + EAC_OBJECT_CACHE_NON_PERSISTENT_GROUPS + + EAC_OBJECT_CACHE_PERMANENT_GROUPS + + EAC_OBJECT_CACHE_PREFETCH_GROUPS ++ Added non-standard wp_cache_add_permanent_groups(), wp_cache_add_prefetch_groups() + += Version 0.3 = + ++ Parameterize timeout, retries. ++ Import transients from MySQL. ++ Rework select/replace/delete SQL. + + New select_one(), select_all() methods. ++ key_exists(), key_exists_memory(), key_exists_database() replace _exists(). ++ Add permanent groups (allow no expiration, overriding default expire). ++ Add function call counts (for testing). + += Version 0.2 = + ++ Support add/get/set/delete _multiple methods (non-standard replace_multiple). ++ Add pre-fetch groups. ++ Add delayed writes. ++ Add settings via defined constants. ++ Add more detailed counts/stats. ++ Manage install/uninstall, activate/deactivate actions. + += Version 0.1 = + ++ Simple memory caching with get/set persistent cache supporting wp-cache functions. ++ Testing SQLite methods. diff --git a/src/object-cache.php b/src/object-cache.php new file mode 100644 index 0000000..d053cc6 --- /dev/null +++ b/src/object-cache.php @@ -0,0 +1,2035 @@ +htmlStats(); + * outputs an html table of current stats + * get (or set) $wp_object_cache->statsCSS to style + * $wp_object_cache->getStats(); + * returns an array of current stats + * $wp_object_cache->getLastSample(); + * returns an array of stats from the last sample saved (or current) + * + */ + +/** + * The WordPress Object Cache is used to save on trips to the database. The + * Object Cache stores all of the cache data to memory and makes the cache + * contents available by using a key, which is used to name and later retrieve + * the cache contents. + */ + +class WP_Object_Cache +{ + /** + * this class id + * + * @var string + */ + const CLASS_NAME = 'eacDoojigger_object_cache'; + + /** + * internal group id + * + * @var string + */ + const GROUP_ID = '@object-cache'; + + /** + * path name to cache folder (EAC_OBJECT_CACHE_DIR) + * + * @var string + */ + private $cache_folder = WP_CONTENT_DIR.'/cache'; + + /** + * name of cache file (EAC_OBJECT_CACHE_FILE) + * + * @var string + */ + private $cache_file = '.eac_object_cache.sqlite'; + + /** + * SQLite journal mode (EAC_OBJECT_CACHE_JOURNAL_MODE). + * + * @var string + */ + private $journal_mode = 'WAL'; + + /** + * SQLite timeout in seconds (EAC_OBJECT_CACHE_TIMEOUT). + * + * @var bool|int + */ + private $pdo_timeout = 3; + + /** + * open/write/delete retries (EAC_OBJECT_CACHE_RETRIES). + * can be changed with $wp_object_cache->max_retries + * + * @var int + */ + public $max_retries = 3; + + /** + * sleep between retries (micro-seconds) 1/10-second. + * + * @var int + */ + private $sleep_time = 100000; + + /** + * use delayed writes until shutdown or n records (EAC_OBJECT_CACHE_DELAYED_WRITES). + * can be changed with $wp_object_cache->delayed_writes + * + * @var bool|int + */ + public $delayed_writes = 32; + + /** + * if expiration is not set, use this (EAC_OBJECT_CACHE_DEFAULT_EXPIRE). + * can be changed with $wp_object_cache->default_expire + * -1 = don't cache (persistent), 0 = no expiration, int = seconds to expiration + * + * @var int + */ + public $default_expire = 0; + + /** + * pre-fetch cache misses (EAC_OBJECT_CACHE_PREFETCH_MISSES). + * + * @var bool + */ + private $prefetch_misses = true; + + /** + * the probablity of running maintenance functions (EAC_OBJECT_CACHE_PROBABILITY). + * can be changed with $wp_object_cache->gc_probability + * + * @var int + */ + public $gc_probability = 100; + + /** + * When true, outputs an admin notice with htmlStats(). + * can be changed with $wp_object_cache->display_stats + * + * @var bool + */ + public $display_stats = false; + + /** + * display errors in an admin notice. + * can be changed with $wp_object_cache->display_errors + * + * @var string + */ + public $display_errors = false; + + /** + * log errors in eacDoojigger log. + * can be changed with $wp_object_cache->log_errors + * + * @var string + */ + public $log_errors = false; + + /** + * Holds the cached objects (group => [key => [value=>,expire=>] | false]). + * false = tried but not in persistent cache, don't try again. + * + * @var array + */ + private $L1_cache = array(); + + /** + * Holds db writes objects (group => [key => expire | false]). + * false = to be deleted from persistent cache. + * + * @var array + */ + private $L2_cache = array(); + + /** + * Memory/persistent cache stats + * + * @var int[] + */ + private $cache_stats = array( + 'cache hits' => 0, // total cache hits (memory & db) + 'cache misses' => 0, // total cache misses (memory & db) + 'L1 cache hits' => 0, // cache hits in memory + 'L1 cache (+)' => 0, // in memory with data + 'L1 cache (-)' => 0, // in memory, no data + 'L1 cache misses' => 0, // cache misses in memory + 'L2 cache hits' => 0, // cache hits from sqlite + 'L2 cache misses' => 0, // cache misses from sqlite + 'L2 pre-fetched (+)' => 0, // records pre-fetched by group + 'L2 pre-fetched (-)' => 0, // misses pre-fetched by group + 'L2 selects' => 0, // number of sql selects + 'L2 commits' => 0, // number of sql transaction commits + 'L2 updated' => 0, // number of records updated + 'L2 deleted' => 0, // number of records deleted + ); + + /** + * Cache hits by group (group => count) + * + * @var int[] + */ + private $group_stats = array(); + + /** + * List of global/site-wide cache groups. + * (EAC_OBJECT_CACHE_GLOBAL_GROUPS, wp_cache_add_global_groups) + * + * @var string[] + */ + private $global_groups = array(); + + /** + * List of non-persistent cache groups. + * (EAC_OBJECT_CACHE_NON_PERSISTENT_GROUPS, wp_cache_add_non_persistent_groups) + * + * @var string[] + */ + private $nonp_groups = array(); + + /** + * List of permanent cache groups, no expiration required. + * (EAC_OBJECT_CACHE_PERMANENT_GROUPS, wp_cache_add_permanent_groups) + * + * @var string[] + */ + private $perm_groups = array( + self::GROUP_ID => true, + 'transient' => true, + 'site-transient' => true, + ); + + /** + * List of pre-loaded cache groups. + * (EAC_OBJECT_CACHE_PREFETCH_GROUPS, wp_cache_add_prefetch_groups) + * + * @var string[] + */ + private $prefetch_groups = array( + self::GROUP_ID => true, + ); + + /** + * Recommended style for stats html table. + * + * @var string + */ + public $statsCSS = + "table.wp-object-cache th {text-align: left; font-weight: normal;}". + "table.wp-object-cache th p {font-weight: bold;}". + "table.wp-object-cache td {text-align: right; padding-left: 1em;}"; + + /** + * Set time now. + * + * @var string + */ + private $time_now; + + /** + * The blog prefix to prepend to keys in non-global groups. + * + * @var string + */ + private $blog_id; + + /** + * Holds the value of is_multisite(). + * + * @var bool + */ + private $multisite; + + /** + * The SQLite database object. + * + * @var object + */ + private $db; + + + /* + * constructor methods + */ + + + /** + * Constructor, sets up object properties, SQLite database (wp_cache_init). + * + */ + public function __construct() + { + $this->time_now = time(); + $this->multisite = is_multisite(); + $this->switch_to_blog( get_current_blog_id() ); + + $this->get_defined_options(); + + // we can still function as a memory-only cache on failure + if (! $this->connect_sqlite() ) { + $this->delete_cache_file(); + $this->connect_sqlite(); + } + + // as early as possible, safe on multisite + add_action('muplugins_loaded',function() + { + // because these are non-standard methods, nothing outside calls them + $this->add_permanent_groups(); + $this->add_prefetch_groups(); + $this->load_prefetch_groups(); + $this->import_wp_transients(); + } + ); + + if (is_admin()) + { + $this->display_errors = true; + add_action( 'admin_footer', function() + { + // this gets moved to the top of an admin page + if ($this->display_stats && is_admin_bar_showing()) { + ob_start(); + $this->htmlStats( ($this->display_stats=='sample') ); + $stats = "
Object Cache...".ob_get_clean()."
"; + echo "\n\n"; + echo "
".$stats."
\n"; + } + },1000 + ); + } + } + + + /** + * get defined constants + * + */ + private function get_defined_options(): void + { + // cache directory (/wp-content/cache) + if (defined( 'EAC_OBJECT_CACHE_DIR' ) && is_string( EAC_OBJECT_CACHE_DIR )) { + $this->cache_folder = EAC_OBJECT_CACHE_DIR; + } + + // cache file name (.eac_object_cache.sqlite) + if (defined( 'EAC_OBJECT_CACHE_FILE' ) && is_string( EAC_OBJECT_CACHE_FILE )) { + $this->cache_file = EAC_OBJECT_CACHE_FILE; + } + + // SQLite journal mode (DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF) + if (defined( 'EAC_OBJECT_CACHE_JOURNAL_MODE' ) && is_string( EAC_OBJECT_CACHE_JOURNAL_MODE )) { + $this->journal_mode = EAC_OBJECT_CACHE_JOURNAL_MODE; + } + + // PDO timeout (int) + if (defined( 'EAC_OBJECT_CACHE_TIMEOUT' ) && is_int( EAC_OBJECT_CACHE_TIMEOUT )) { + $this->pdo_timeout = EAC_OBJECT_CACHE_TIMEOUT; + } + + // database retries (int) + if (defined( 'EAC_OBJECT_CACHE_RETRIES' ) && is_int( EAC_OBJECT_CACHE_RETRIES )) { + $this->max_retries = EAC_OBJECT_CACHE_RETRIES; + } + + // delayed writes (true|false|int) + if (defined( 'EAC_OBJECT_CACHE_DELAYED_WRITES' )) { + $this->delayed_writes = EAC_OBJECT_CACHE_DELAYED_WRITES; + } + + // default expiration (-1|0|int) + if (defined( 'EAC_OBJECT_CACHE_DEFAULT_EXPIRE' ) && is_int( EAC_OBJECT_CACHE_DEFAULT_EXPIRE )) { + $this->default_expire = EAC_OBJECT_CACHE_DEFAULT_EXPIRE; + } + + // pre-fetch cache misses (bool) + if (defined( 'EAC_OBJECT_CACHE_PREFETCH_MISSES' ) && is_bool( EAC_OBJECT_CACHE_PREFETCH_MISSES )) { + $this->prefetch_misses = EAC_OBJECT_CACHE_PREFETCH_MISSES; + } + + // maintenance/sampling probability (int) + if (defined( 'EAC_OBJECT_CACHE_PROBABILITY' ) && is_int( EAC_OBJECT_CACHE_PROBABILITY )) { + $this->gc_probability = EAC_OBJECT_CACHE_PROBABILITY; + } + + /* additional constants used... + EAC_OBJECT_CACHE_GLOBAL_GROUPS (array) + EAC_OBJECT_CACHE_NON_PERSISTENT_GROUPS (array) + EAC_OBJECT_CACHE_PERMANENT_GROUPS (array) + EAC_OBJECT_CACHE_PREFETCH_GROUPS (array) + */ + } + + + /** + * open the SQLite database connection + * + */ + private function connect_sqlite(): bool + { + $cacheName = trailingslashit($this->cache_folder) . $this->cache_file; + $create = !file_exists($cacheName); + + $retries = 0; + while ( ++$retries <= $this->max_retries ) { + try { + $this->db = new \PDO("sqlite:{$cacheName}",null,null,[ + PDO::ATTR_TIMEOUT => $this->pdo_timeout, + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ]); + $this->db->exec(" + PRAGMA encoding = 'UTF-8'; + PRAGMA journal_mode = {$this->journal_mode}; + PRAGMA page_size = 4096; + PRAGMA synchronous = OFF; + "); + break; + } catch ( Exception $ex ) { + $this->error_log(__FUNCTION__,$ex); + $this->db = null; + usleep($this->sleep_time); + } + } + + if ( ! $this->db ) return false; + + // new file, create table + if ($create) { + try { + $this->db->exec(" + CREATE TABLE IF NOT EXISTS wp_cache ( + key TEXT NOT NULL COLLATE BINARY PRIMARY KEY, value BLOB, expire INT + ); + CREATE INDEX IF NOT EXISTS expire ON wp_cache (expire); + "); + $this->error_log(__FUNCTION__,"L2 cache created"); + } catch ( Exception $ex ) { + $this->error_log(__FUNCTION__,$ex); + $this->db = null; + return false; + } + } + + return true; + } + + + /* + * readability (no setability) of private properties + */ + + + /** + * Makes private properties readable for backward compatibility. + * + * @since 4.0.0 + * + * @param string $name Property to get. + * @return mixed Property. + */ + public function __get( $name ) { + return $this->$name; + } + + + /** + * Makes private properties checkable for backward compatibility. + * + * @since 4.0.0 + * + * @param string $name Property to check if set. + * @return bool Whether the property is set. + */ + public function __isset( $name ) { + return isset( $this->$name ); + } + + + /* + * SQLite select (one / all) + */ + + + /** + * select a single record from the database. + * + * @param string $blogkey Cache key to check for existence. (blog|key) + * @param string $group Cache group for the key existence check. + * @return array|bool selected row or false; + */ + private function select_one( string $blogkey, string $group ) + { + static $stmt = null; + + if ( ! $this->db ) return false; + + $this->L1_cache[ $group ][ $blogkey ] = false; + + if ( isset( $this->nonp_groups[ $group ] ) ) return false; + + if (is_null($stmt)) { + $stmt = $this->db->prepare( + "SELECT * FROM wp_cache WHERE key = :key AND (expire = 0 OR expire >= {$this->time_now}) LIMIT 1;" + ); + } + + try { + $stmt->bindValue( ':key', $group.'|'.$blogkey, PDO::PARAM_STR ); + $stmt->execute(); + if ($row = $stmt->fetch()) { + $row = $this->select_parse_row( $row ); + } + $this->addStats('L2 selects',1); + $stmt->closeCursor(); + } catch ( Exception $ex ) { + $this->error_log(__FUNCTION__,$ex); + } + + return $row; + } + + + /** + * select multiple records from the database. + * + * @param array $blogkeys keys to select (group => [blogkey,...]). + * @param bool $like use 'key like' not 'key in' + * @return array selected rows. + */ + private function select_all( array $blogkeys, bool $like=false ): array + { + if ( ! $this->db ) return []; + + // get the blogkeys that we need to select from L2 + $selectkeys = []; + foreach ($blogkeys as $group => $keys) { + foreach ($keys as $blogkey) { + $this->L1_cache[ $group ][ $blogkey ] = false; + $selectkeys[] = $group.'|'.$blogkey; + } + } + + if (empty($selectkeys)) return []; + + $selectkeys = array_unique($selectkeys); + + $where = ($like) + ? substr(str_repeat( 'KEY LIKE ? OR ', count($selectkeys)),0,-4) + : 'KEY IN (' . substr(str_repeat('?,', count($selectkeys)),0,-1) . ')'; + + $stmt = $this->db->prepare( + "SELECT * FROM wp_cache WHERE {$where} AND (expire = 0 OR expire >= {$this->time_now});" + ); + + try { + $stmt->execute($selectkeys); + if ($rows = $stmt->fetchAll()) { + foreach ($rows as &$row) { + $row = $this->select_parse_row( $row ); + } + } + $this->addStats('L2 selects',1); + $stmt->closeCursor(); + } catch ( Exception $ex ) { + $this->error_log(__FUNCTION__,$ex); + } + + return ($rows) ? $rows : []; + } + + + /** + * Utilty to parse key from database row, unserialize value, and add to L1 cache. + * sets expire to seconds (not time) and adds to L1 cache. + * + * @param array $row database row (key, value, expire) + * @return array row (key, value, expire, group, blog) + */ + private function select_parse_row( array $row ): array + { + if (preg_match("/^(?.*)\|(?\d{5})\|(?.*)$/", $row['key'], $parts)) { + $row = array_merge($row,array_filter($parts,'is_string',ARRAY_FILTER_USE_KEY)); + $row['value'] = maybe_unserialize($row['value']); + $row['expire'] = (!empty($row['expire'])) ? $row['expire'] - $this->time_now : 0; + // add to the L1 (memory) cache + $blogkey = $row['blog'].'|'.$row['key']; + $this->L1_cache[ $row['group'] ][ $blogkey ] = [ 'value'=>$row['value'], 'expire'=>$row['expire'] ]; + } else { // this shouldn't ever happen + $this->error_log(__FUNCTION__,'invalid key format ['.$key.']'); + } + return $row; + } + + + /* + * API utility methods + */ + + + /** + * Serves as a utility function to determine whether a key is valid. + * + * @param int|string $key Cache key to check for validity. + * @param string $group Where to group the cache contents. Default 'default'. + * @return string|bool combined site|key if the key is valid. + */ + private function get_valid_key( $key, $group ) + { + if ( is_int( $key ) || ( is_string( $key ) && trim( $key ) !== '' ) ) { + $blog = ( $this->multisite && !isset( $this->global_groups[ $group ] ) ) ? $this->blog_id : 0; + return sprintf( "%05d|%s", $blog, $key ); + } + + $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 an integer or a non-empty string, %s given.' ), $type ); + _doing_it_wrong( + sprintf( '%s::%s', __CLASS__, debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 )[1]['function'] ), + $message, + '6.1.0' + ); + + return false; + } + + + /** + * Serves as a utility function to determine whether a key exists in the cache. + * + * @param string $blogkey Cache key to check for existence. (blog|key) + * @param string $group Cache group for the key existence check. + * @param bool $count increment hits/misses + * @param bool $force Optional. Whether to force an update of the local cache + * from the persistent cache. Default false. + * @return bool Whether the key exists in the cache for the given group. + */ + private function key_exists( string $blogkey, string $group, $count = false, $force = false ): bool + { + // if we've updated a key, but not written yet, then we force a persistent load, + // we'll lose that value - so we must ignore the $force flag. + // ( wp_load_alloptions() uses $force ) + + return (/*!$force &&*/ $this->key_exists_memory( $blogkey, $group, $count )) + ? (bool) $this->L1_cache[ $group ][ $blogkey ] + : $this->key_exists_database( $blogkey, $group, $count ); + } + + + /** + * Serves as a utility function to determine whether a key exists in the memory cache. + * + * @param string $blogkey Cache key to check for existence. (blog|key) + * @param string $group Cache group for the key existence check. + * @param bool $count increment L1 hits/misses + * @return int +1 = found w/data, -1 = found no data, 0 not found + */ + private function key_exists_memory( string $blogkey, string $group, $count = false ): int + { + if ( isset( $this->L1_cache[ $group ], $this->L1_cache[ $group ][ $blogkey ] ) ) { + if ($count) $this->addStats('L1 cache hits',1); + if ($this->L1_cache[ $group ][ $blogkey ] !== false) { + if ($count) $this->addStats('L1 cache (+)',1); + return +1; + } else { + if ($count) $this->addStats('L1 cache (-)',1); + return -1; + } + } + + if ($count) $this->addStats('L1 cache misses',1); + return 0; + } + + + /** + * Serves as a utility function to determine whether a key exists in the database cache. + * + * @param string $blogkey Cache key to check for existence. (blog|key) + * @param string $group Cache group for the key existence check. + * @param bool $count increment L2 hits/misses + * @return bool Whether the key exists in the db + */ + private function key_exists_database( string $blogkey, string $group, $count = false ): bool + { + if ( ! $this->db ) return false; + + if ( $row = $this->select_one( $blogkey, $group ) ) { + if ($count) $this->addStats('L2 cache hits',1); + return true; + } else { + if ($count) $this->addStats('L2 cache misses',1); + return false; + } + } + + + /* + * API methods - outside actors manage cache objects (add/set/get/delete) + */ + + + /** + * Adds data to the cache if it doesn't already exist. + * + * @uses WP_Object_Cache::key_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. + * + * @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. + */ + public function add( $key, $data, $group = 'default', $expire = 0 ) + { + if ( wp_suspend_cache_addition() ) return false; + + if (empty( $group )) $group = 'default'; + + if ( ! $blogkey = $this->get_valid_key( $key, $group ) ) return false; + + if ( $this->key_exists( $blogkey, $group, false ) ) return false; + + return $this->set( $key, $data, $group, (int) $expire ); + } + + + /** + * 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. + */ + public function add_multiple( array $data, $group = '', $expire = 0 ) + { + $values = array(); + + // write all in one transaction + $this->set_delayed_writes( true ); + + foreach ( $data as $key => $value ) { + $values[ $key ] = $this->add( $key, $value, $group, $expire ); + } + + $this->set_delayed_writes(); + + return $values; + } + + + /** + * Replaces the contents in the cache, if contents already exist. + * + * @see WP_Object_Cache::set() + * + * @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. + */ + public function replace( $key, $data, $group = 'default', $expire = 0 ) + { + if (empty( $group )) $group = 'default'; + + if ( ! $blogkey = $this->get_valid_key( $key, $group ) ) return false; + + if ( ! $this->key_exists( $blogkey, $group, false ) ) return false; + + return $this->set( $key, $data, $group, (int) $expire ); + } + + + /** + * Replace 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. + */ + public function replace_multiple( array $data, $group = 'default', $expire = 0 ) + { + $values = array(); + + // write all in one transaction + $this->set_delayed_writes( true ); + + foreach ( $data as $key => $value ) { + $values[ $key ] = $this->replace( $key, $value, $group, $expire ); + } + + $this->set_delayed_writes(); + + return $values; + } + + + /** + * 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. + * + * @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. + * @return bool True if contents were set, false if key is invalid. + */ + public function set( $key, $data, $group = 'default', $expire = 0 ) + { + if (empty( $group )) $group = 'default'; + + if ( ! $blogkey = $this->get_valid_key( $key, $group ) ) return false; + + if ( is_object( $data ) ) { + $data = clone $data; + } + + // set default expiration time - transients (perm_groups) don't expire unless explicitly set + $expire = (!empty($expire)) + ? (int)$expire + : (isset( $this->perm_groups[ $group ] ) ? 0 : $this->default_expire); + + // value has not changed (has WordPress already done this?) + if ( ($this->key_exists_memory( $blogkey, $group ) > 0) + && ($data === $this->L1_cache[ $group ][ $blogkey ][ 'value' ]) + && ($expire === $this->L1_cache[ $group ][ $blogkey ][ 'expire' ]) + ) { + return false; + } + + $this->L1_cache[ $group ][ $blogkey ] = [ 'value' => $data, 'expire' => $expire ]; + + // when not to write to db + if ( ! $this->db || $expire < 0 || isset( $this->nonp_groups[ $group ] ) ) { + return true; + } + + // add the record + $this->L2_cache[ $group ][ $blogkey ] = (int)$expire; + $this->maybe_write_cache(); + + return true; + } + + + /** + * 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. + */ + public function set_multiple( array $data, $group = '', $expire = 0 ) + { + $values = array(); + + // write all in one transaction + $this->set_delayed_writes( true ); + + foreach ( $data as $key => $value ) { + $values[ $key ] = $this->set( $key, $value, $group, $expire ); + } + + $this->set_delayed_writes(); + + return $values; + } + + + /** + * Retrieves the cache contents, if it exists. - wp_cache_get() + * + * 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. + */ + public function get( $key, $group = 'default', $force = false, &$found = null ) + { + if (empty( $group )) $group = 'default'; + + if ( ! $blogkey = $this->get_valid_key( $key, $group ) ) return false; + + if ( $this->key_exists( $blogkey, $group, true, $force ) ) { + $found = true; + $this->addStats('cache hits',1,$group); + if ( is_object( $this->L1_cache[ $group ][ $blogkey ][ 'value' ] ) ) { + return clone $this->L1_cache[ $group ][ $blogkey ][ 'value' ]; + } else { + return $this->L1_cache[ $group ][ $blogkey ][ 'value' ]; + } + } + + $this->addStats('cache misses',1); + + $found = false; + return false; + } + + + /** + * 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. + */ + public function get_multiple( array $keys, $group = 'default', $force = false ) + { + // fill array [key => false] + $values = array_fill_keys( (array)$keys, false ); + + if (empty( $group )) $group = 'default'; + + $blogkeys = []; + $selects = 0; + foreach ( $values as $key => &$value ) { + if ( $blogkey = $this->get_valid_key( $key, $group ) ) { + if (/*$force ||*/ ! $this->key_exists_memory($blogkey, $group, true)) { + $blogkeys[ $group ][] = $blogkey; + $selects++; + } else { + $value = $this->L1_cache[ $group ][ $blogkey ][ 'value' ] ?? false; + } + } + } + + if ( $this->db && ! isset( $this->nonp_groups[ $group ] ) ) { + if (!empty($blogkeys)) { + $hits = 0; + foreach ($this->select_all( $blogkeys ) as $row) { + $values[ $row['key'] ] = $row['value']; + $hits++; + } + $this->addStats('L2 cache hits',$hits); + $this->addStats('L2 cache misses',$selects - $hits); + } + } + + $hits = count(array_filter($values, function($v) {return $v !== false;})); + $this->addStats('cache hits',$hits,$group); + $this->addStats('cache misses',count($values) - $hits); + 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. + */ + public function delete( $key, $group = 'default', $deprecated = false ) + { + if (empty( $group )) $group = 'default'; + + if ( ! $blogkey = $this->get_valid_key( $key, $group ) ) return false; + + if ( ! $this->key_exists( $blogkey, $group, false ) ) return false; + + $this->L1_cache[ $group ][ $blogkey ] = false; // not in persistent cache + + // when not to write to db + if ( ! $this->db || isset( $this->nonp_groups[ $group ] ) ) { + return true; + } + + $this->L2_cache[ $group ][ $blogkey ] = false; // to be deleted from table + $this->maybe_write_cache(); + + return true; + } + + + /** + * 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. + */ + public function delete_multiple( array $keys, $group = '' ) + { + $values = array(); + + // delete all in one transaction + $this->set_delayed_writes( true ); + + foreach ( $keys as $key ) { + $values[ $key ] = $this->delete( $key, $group ); + } + + $this->set_delayed_writes(); + + return $values; + } + + + /** + * 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. + */ + public function incr( $key, $offset = 1, $group = 'default' ) + { + if (empty( $group )) $group = 'default'; + + if ( ! $blogkey = $this->get_valid_key( $key, $group ) ) return false; + + $value = max( 0, ( (int) $this->get( $key, $group ) + (int) $offset ) ); + + $expire = ($this->key_exists_memory( $blogkey, $group ) > 0) + ? $this->L1_cache[ $group ][ $blogkey ][ 'expire' ] + : 0; + + $this->set( $key, $value, $group, $expire ); + return $value; + } + + + /** + * 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. + */ + public function decr( $key, $offset = 1, $group = 'default' ) + { + return $this->incr( $key, - $offset, $group ); + } + + + /* + * API methods - flush cache + */ + + + /** + * Clears the object cache of all data. + * SQLite triggers truncate optomizer + * + * @return bool sql result + */ + public function flush(): bool + { + $this->L1_cache = $this->L2_cache = array(); + + if ( ! $this->db ) return false; + + try { + $this->db->beginTransaction(); + $result = $this->db->query("DELETE FROM wp_cache;"); + $this->db->commit(); + $this->error_log(__FUNCTION__,'cache flushed, '. + $result->rowCount()." records deleted"); + $this->addStats('flushed cache',$result->rowCount()); + } catch ( Exception $ex ) { + $this->error_log(__FUNCTION__,$ex); + $this->db->rollBack(); + return false; + } + + return (bool)$result; + } + + + /** + * Removes all cache items in a group. + * + * @param string $group Name of group to remove from cache. + * @return bool sql result + */ + public function flush_group( string $group ): bool + { + static $stmt = null; + + $this->write_cache(); + unset( $this->L1_cache[ $group ] ); + + if ( ! $this->db ) return false; + + if (is_null($stmt)) { + $stmt = $this->db->prepare("DELETE FROM wp_cache WHERE key LIKE :group;"); + } + + try { + $blogkey = $this->get_valid_key('%',$group); + $stmt->bindValue( ':group', $group.'|'.$blogkey, PDO::PARAM_STR ); + $this->db->beginTransaction(); + $stmt->execute(); + $this->db->commit(); + $this->error_log(__FUNCTION__,"cache flushed for '{$group}', ". + $stmt->rowCount()." records deleted"); + $this->addStats("flushed {$group}",$stmt->rowCount()); + } catch ( Exception $ex ) { + $this->error_log(__FUNCTION__,$ex); + $this->db->rollBack(); + return false; + } + + return (bool)$stmt; + } + + + /** + * Removes all cache items tagged with a blog number. + * + * @param string $blog current blog + * @return bool sql result + */ + public function flush_blog( $blog_id = null ): bool + { + if (! $this->multisite) { + return $this->flush(); + } + + static $stmt = null; + + $this->write_cache(); + $this->L1_cache = array(); + + if ( ! $this->db ) return false; + + if (!is_int($blog_id)) $blog_id = get_current_blog_id(); + + if (is_null($stmt)) { + $stmt = $this->db->prepare("DELETE FROM wp_cache WHERE key LIKE :blog;"); + } + + try { + $stmt->bindValue( ':blog', '%|'.sprintf("%05d", $blog_id).'|%', PDO::PARAM_STR ); + $this->db->beginTransaction(); + $stmt->execute(); + $this->db->commit(); + $this->error_log(__FUNCTION__,"cache flushed for blog id {$blog_id}, ". + $stmt->rowCount()." records deleted"); + $this->addStats("flushed blog id {$blog_id}",$stmt->rowCount()); + } catch ( Exception $ex ) { + $this->error_log(__FUNCTION__,$ex); + $this->db->rollBack(); + return false; + } + + return (bool)$stmt; + } + + + /** + * Clears the object cache of all data. + * + * @return bool Always returns true. + */ + public function flush_runtime(): bool + { + $this->write_cache(); + $this->L1_cache = array(); + return true; + } + + + /* + * API methods - manage groups + */ + + + /** + * Sets the list of global/site-wide cache groups. + * from wp-includes/load.php wp_start_object_cache() + * + * @param string|string[] $groups List of groups that are global. + * @return array [group=>true,...] + */ + public function add_global_groups( $groups ): array + { + // EAC_OBJECT_CACHE_GLOBAL_GROUPS + $defined_groups = $this->get_defined_groups('global'); + + $groups = array_fill_keys( (array) $groups, true ); + $this->global_groups = array_merge( $this->global_groups, $defined_groups, $groups ); + + return $this->global_groups; + } + + + /** + * Sets the list of non-persistent cache groups. + * from wp-includes/load.php wp_start_object_cache() + * + * @param string|string[] $groups List of groups that are non-persistent. + * @return array [group=>true,...] + */ + public function add_non_persistent_groups( $groups ): array + { + // EAC_OBJECT_CACHE_NON_PERSISTENT_GROUPS + $defined_groups = $this->get_defined_groups('non_persistent'); + + $groups = array_fill_keys( (array) $groups, true ); + $this->nonp_groups = array_merge( $this->nonp_groups, $defined_groups, $groups ); + + return $this->nonp_groups; + } + + + /** + * Sets the list of permanent cache groups. + * + * @param string|string[] $groups List of groups that can be permanent. + * @return array [group=>true,...] + */ + public function add_permanent_groups( $groups = [] ): array + { + // EAC_OBJECT_CACHE_PERMANENT_GROUPS + $defined_groups = $this->get_defined_groups('permanent'); + + $groups = array_fill_keys( $groups, true ); + $this->perm_groups = array_merge( $this->perm_groups, $defined_groups, $groups ); + + return $this->perm_groups; + } + + + /** + * Sets the list of pre-loaded groups. + * + * @param string|string[] $groups List of groups that are pre-loaded. + * @return array [group=>true,...] + */ + public function add_prefetch_groups( $groups = [] ): array + { + // EAC_OBJECT_CACHE_PREFETCH_GROUPS + $defined_groups = $this->get_defined_groups('prefetch'); + + $groups = array_fill_keys( (array) $groups, true ); + $this->prefetch_groups = array_merge( $this->prefetch_groups, $defined_groups, $groups ); + + return $this->prefetch_groups; + } + + + /** + * Get group keys as array from constant + * + * @param string $constant unique part of group constant name + * @return array [group=>true,...] + */ + private function get_defined_groups( string $constant ): array + { + $groups = []; + $constant = 'EAC_OBJECT_CACHE_'.strtoupper($constant).'_GROUPS'; + if ( defined( $constant ) ) { + $constant = (array) constant($constant); + if ( is_array( $constant ) && ! empty ( $constant ) ) { + $groups = array_fill_keys( $constant, true ); + } + } + return $groups; + } + + + /** + * pre-fetch existing group. + * called after add_global_groups(),add_non_persistent_groups() with EAC_OBJECT_CACHE_PREFETCH_GROUPS + * + */ + private function load_prefetch_groups(): void + { + if ( ! $this->db ) return; + + $blogkeys = []; + foreach (array_keys($this->prefetch_groups) as $group) { + if (! isset( $this->nonp_groups[ $group ] ) ) { + $blogkeys[ $group ] = [ $this->get_valid_key('%',$group) ]; + } + } + + $this->addStats("L2 pre-fetched (+)", count($this->select_all( $blogkeys, true ))); + + // get cache misses from last request - known not to be in sqlite + $this->do_cache_misses(); + } + + + /* + * API methods - multisite + */ + + + /** + * Switches the internal blog ID. + * + * This changes the blog ID used to create keys in blog specific groups. + * + * @param int $blog_id Blog ID. + */ + public function switch_to_blog( $blog_id ) + { + $this->blog_id = $this->multisite ? (int) $blog_id : 0; + } + + + /** + * Resets cache keys. + * + * @deprecated 3.5.0 Use WP_Object_Cache::switch_to_blog() + * @see switch_to_blog() + */ + public function reset() + { + _deprecated_function( __FUNCTION__, '3.5.0', self::CLASS_NAME.'::switch_to_blog()' ); + $this->switch_to_blog( get_current_blog_id() ); + } + + + /* + * API methods - close + */ + + + /** + * close the persistent cache (wp_cache_close) + * + */ + public function close(): void + { + if (! $this->db ) return; + + // find and cache all cache misses - not in sqlite + $this->do_cache_misses(true); + + // count requests (since last flush) + $requests = $this->incr('requests',+1,self::GROUP_ID); + + // maintenance functions (every n requests) + if ($this->gc_probability > 0) + { + $this->gc_probability = $this->gc_probability + ($this->gc_probability % 2); // even number + $probability = ($requests % $this->gc_probability); + + if ($probability == 0) // checkpoint db + { + $this->write_cache(); + $result = $this->db->query('PRAGMA wal_checkpoint(TRUNCATE);'); + } + + if ($probability == (int)($this->gc_probability * .75)) // garbage collection + { + $limit = (is_int($this->delayed_writes) ? $this->delayed_writes : 32); + try { + $this->db->beginTransaction(); + $result = $this->db->query( + "DELETE FROM wp_cache WHERE expire > 0 AND expire < {$this->time_now} LIMIT {$limit};" + ); + $this->db->commit(); + } catch ( Exception $ex ) { + $this->error_log(__FUNCTION__,$ex); + $this->db->rollBack(); + } + } + + if ($probability == (int)($this->gc_probability * .50)) // optimize db + { + $result = $this->db->query('PRAGMA optimize;'); + } + + + if ($probability == (int)($this->gc_probability * .25)) // stats sample + { + $this->set('sample', $this->getStats(true), self::GROUP_ID, 0); + } + } + + $this->write_cache(); + + $this->db = null; + } + + + /* + * internal methods + */ + + + /** + * temporarily set or reset delayed_writes. + * + * @param bool|int $set new value + */ + private function set_delayed_writes($set=null) + { + static $delayed_writes = false; + + if (is_null($set)) { // reset to prior value + $this->delayed_writes = $delayed_writes; + } else { // set to number of adds/deletes or true + $delayed_writes = $this->delayed_writes; + $this->delayed_writes = $set; + } + $this->maybe_write_cache(); + } + + + /** + * Update counters + * + * @param string $countId the counter to update + * @param int|bool $n the count to add (+1) + * @param string $groupId also update the group counter + */ + private function addStats(string $countId, $n, string $groupId=null) + { + if ($countId) { + if (!isset($this->cache_stats[$countId])) { + $this->cache_stats[$countId] = 0; + } + $this->cache_stats[$countId] += (int)$n; + } + if ($groupId) { + if (!isset($this->group_stats[$groupId])) { + $this->group_stats[$groupId] = 0; + } + $this->group_stats[$groupId] += (int)$n; + } + } + + + /** + * write the persistent cache to disk when db cache is full + * + */ + private function maybe_write_cache(): bool + { + if ( $this->delayed_writes !== true ) { + $pending = count($this->L2_cache,COUNT_RECURSIVE) - count($this->L2_cache); + if ($pending >= (int)$this->delayed_writes ) { + return $this->write_cache(); + } + } + return false; + } + + + /** + * write the persistent cache to disk + * + */ + private function write_cache(): bool + { + if (! $this->db || empty($this->L2_cache)) { + $this->L2_cache = array(); + return false; + } + + $write = $delete = array(); + + // find all writes and deletes + foreach ($this->L2_cache as $group => $updates) { + foreach ($updates as $blogkey => $expire) { + if ($expire !== false) { + $write[] = array( + $group.'|'.$blogkey, + maybe_serialize($this->L1_cache[ $group ][ $blogkey ][ 'value' ]), + ( ($expire) ? $this->time_now+$expire : 0 ) + ); + } else { + $delete[] = array( + $group.'|'.$blogkey, + ); + } + } + } + + $this->L2_cache = array(); + + $count = 0; + // replace records + if (!empty($write)) { + $retries = 0; + while ( ++$retries <= $this->max_retries ) { + try { + $stmt = $this->db->prepare( + "REPLACE INTO wp_cache (key, value, expire) VALUES " . + rtrim(str_repeat("(?,?,?),", count($write)),',') + ); + $this->db->beginTransaction(); + $stmt->execute(array_merge(...$write)); + $count += $stmt->rowCount(); + $this->addStats('L2 updated',$stmt->rowCount()); + $this->db->commit(); + $this->addStats('L2 commits',1); + break; + } catch ( Exception $ex ) { + $this->error_log(__FUNCTION__,$ex); + $this->db->rollBack(); + usleep($this->sleep_time); + } + } + } + + // delete records + if (!empty($delete)) { + $retries = 0; + while ( ++$retries <= $this->max_retries ) { + try { + $stmt = $this->db->prepare( + "DELETE FROM wp_cache WHERE key in (" . + rtrim(str_repeat("?,", count($delete)),',').")" + ); + $this->db->beginTransaction(); + $stmt->execute(array_merge(...$delete)); + $count += $stmt->rowCount(); + $this->addStats('L2 deleted',$stmt->rowCount()); + $this->db->commit(); + $this->addStats('L2 commits',1); + break; + } catch ( Exception $ex ) { + $this->error_log(__FUNCTION__,$ex); + $this->db->rollBack(); + usleep($this->sleep_time); + } + } + } + + return (bool)$count; + } + + + /** + * manage cached misses. + * called to load on muplugins, called to save on close/shutdown. + * + * @param $save bool save cache misses + */ + private function do_cache_misses($save=false): void + { + if (! $this->prefetch_misses) return; + + // load (or re-load) prior cache misses into L1 cache + if ($misses = $this->get('cache-misses',self::GROUP_ID)) { + foreach ($misses as $group => $keys) { + if (isset( $this->L1_cache[ $group ] )) { + $keys = array_diff_key($keys, $this->L1_cache[ $group ]); + $this->L1_cache[ $group ] = array_merge($keys, $this->L1_cache[ $group ]); + } else { + $this->L1_cache[ $group ] = $keys; + } + $this->addStats("L2 pre-fetched (-)", count($keys)); + } + } + // remove from cache + $blogkey = $this->get_valid_key('cache-misses',self::GROUP_ID); + unset( $this->L1_cache[ self::GROUP_ID ][ $blogkey ] ); + + // save for next request + if ($save) { + $misses = array(); + foreach ($this->L1_cache as $group => $keys) { + if ($keys = array_filter( $keys, function($v) {return $v === false;} )) { + $misses[$group] = $keys; + } + } + $this->set('cache-misses', $misses, self::GROUP_ID, HOUR_IN_SECONDS); + } + } + + + /** + * Delete the L2 cache file(s). + * Since we load early, WP_Filesystem is probably not available + * + */ + public function delete_cache_file(): void + { + $this->db = null; + + $cacheName = trailingslashit($this->cache_folder) . $this->cache_file; + foreach ( [ '', '-journal', '-shm', '-wal' ] as $ext ) { + if (file_exists($cacheName.$ext)) { + unlink($cacheName.$ext); + } + } + $this->error_log(__FUNCTION__,"L2 cache deleted"); + } + + + /** + * Error logging. + * + * Writes and/or displays error message. + * + * @param string $source (function) + * @param string|object $message message string or exception object + */ + private function error_log($source,$message): void + { + try { + $class = 'warning'; + $trace = ''; + + if (is_object($message)) { + $class = 'error'; + $message = $message->getCode().' '.$message->getMessage(); + ob_start(); + debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + $trace = PHP_EOL . ob_get_clean(); + } + + if ($this->display_errors && is_admin() && function_exists('is_admin_bar_showing') && is_admin_bar_showing()) { + echo "

WP Object Cache: ".$message."

"; + } + + $message = "WP_object_cache->".$source.' : '.$message.$trace; + error_log($message); + + if ($this->log_errors && function_exists('eacDoojigger')) { + eacDoojigger()->logError($message,self::CLASS_NAME); + } + } catch (Throwable $e) {} + } + + + /* + * API methods - counts/stats + */ + + + /** + * Echoes the stats of the caching (similar to WP_Object_Cache::stats()). + * Called by outside actors (e.g. debug bar) + * + * Gives the cache hits, and cache misses. Also prints every cached group, + * key and the data. + */ + public function stats(): void + { + $stats = $this->getStats(false); + + $ratio = $this->cache_hit_ratio($this->cache_stats['cache hits'],$this->cache_stats['cache misses']); + echo "

"; + echo "Cache Hits: ".number_format($this->cache_stats['cache hits'],0)."
"; + echo "Cache Misses: ".number_format($this->cache_stats['cache misses'])."
"; + echo "Cache Ratio: {$ratio}"; + echo "

\n"; + + echo "

Cache Counts:

    "; + foreach ($stats['cache'] as $group => $cache) { + if ($cache && $cache[0]) { + echo '
  • ' . esc_html( $group ) . + ' - ' . number_format( $cache[0], 0 ); + } + } + + echo "
\n"; + echo "

Cache Groups:

    "; + foreach ($stats['cache-groups'] as $group => $cache) { + if ($cache && $cache[0]) { + echo '
  • ' . esc_html( $group ) . + ' - ' . number_format( $cache[0], 0 ). + ' ( ' . number_format( $cache[1] / KB_IN_BYTES, 2 ) . 'k )
  • '; + } + } + echo "
\n"; + + echo "

".self::CLASS_NAME." v".EACDOOJIGGER_OBJECT_CACHE."

\n"; + } + + + /** + * Echos the stats of the caching, formatted table. + * + * Gives the cache hits, and cache misses. Also prints every cached group, + * key and the data. + * + * @param bool $last use last sampling + * @param bool $full flush cache and get database stats + */ + public function htmlStats($last = false, $full = true): void + { + $stats = ($last) ? $this->getLastSample() : $this->getStats($full); + + echo "\n
"; + + if (isset($stats['id'])) { + echo "

"; + foreach ($stats['id'] as $name => $value) { + echo "{$name}: {$value}"."
"; + } + echo "

"; + } + + echo "\n"; + + if (isset($stats['cache'])) { + echo "\n"; + foreach ($stats['cache'] as $name => $value) { + if ($value && $value[0]) { + echo ''. + ''. + ''. + ''; + } + } + } + + if (isset($stats['cache-groups'])) { + echo "\n"; + foreach ($stats['cache-groups'] as $name => $value) { + if ($value && $value[0]) { + echo ''. + ''. + ''. + ''; + } + } + } + + if (isset($stats['database-groups'])) { + echo "\n"; + foreach ($stats['database-groups'] as $name => $value) { + if ($value && $value[0]) { + echo ''. + ''. + ''. + ''; + } + } + } + + echo "\n

Cache Counts:

'.esc_html( $name ).''.number_format($value[0], 0).''.$value[1].'

L1 (In-Memory) Cache Groups:

'.esc_html( $name ).'' .number_format( $value[0], 0) . ' ~'.number_format( $value[1] / KB_IN_BYTES, 2 ) . 'k +'.number_format( $value[2], 0 ) . '

L2 (Persistent) Cache Groups:

'.esc_html( $name ).'' .number_format( $value[0], 0) . ' ~'.number_format( $value[1] / KB_IN_BYTES, 2 ) . 'k
\n"; + } + + + /** + * Returns the stats of the caching. + * + * Gives the cache hits, and cache misses. Also prints every cached group, + * key and the data. + * + * @param bool $full flush cache and get database stats + * @return array + */ + public function getStats($full=true): array + { + // so outside actors don't force a cache write + if ($full) $this->write_cache(); + + $stats = array(); + $stats['id'] = array( + self::CLASS_NAME => EACDOOJIGGER_OBJECT_CACHE, + 'cache file' => ($this->db) + ? '~/'.trailingslashit(basename($this->cache_folder)) . $this->cache_file + : 'memory-only', + 'sample time' => wp_date('c'), + ); + if (isset($_SERVER['HTTP_HOST'],$_SERVER['REQUEST_URI'])) { + $stats['id']['url'] = sprintf('%s://%s%s', + (is_ssl()) ? 'https' : 'http', + $_SERVER['HTTP_HOST'], + $_SERVER['REQUEST_URI']); + } + + // addStats counters + $stats['cache'] = array(); + foreach ($this->cache_stats as $name => $count) { + $stats['cache'][$name] = [$count,'']; + } + // add cache hit ratios + $stats['cache']['cache hits'][1] = + $this->cache_hit_ratio($this->cache_stats['cache hits'],$this->cache_stats['cache misses']); + $stats['cache']['L1 cache hits'][1] = + $this->cache_hit_ratio($this->cache_stats['L1 cache hits'],$this->cache_stats['L1 cache misses']); + $stats['cache']['L2 cache hits'][1] = + $this->cache_hit_ratio($this->cache_stats['L2 cache hits'],$this->cache_stats['L2 cache misses']); + + // current cache contents + $stats['cache-groups'] = array(); + foreach ( $this->L1_cache as $group => $cache ) { + $cache = array_filter($cache, function($v){return $v !== false;}); + if (!empty($cache)) { + $count = count($cache); + $size = strlen( serialize( $cache ) ); + $stats['cache-groups'][$group] = [$count, $size, $this->group_stats[$group] ?? 0]; + } + } + ksort($stats['cache-groups']); + $stats['cache-groups']['Total'] = [ + array_sum(array_column($stats['cache-groups'],0)), + array_sum(array_column($stats['cache-groups'],1)), + array_sum(array_column($stats['cache-groups'],2)) + ]; + + // database contents - all groups + if ($full && $this->db) { + $blog_id = sprintf("%05d", $this->blog_id); + $stats['database-groups'] = array(); + if ($result = $this->db->query(" + SELECT SUBSTR(key,0,INSTR(key,'|')) as name, + SUBSTR(key,INSTR(key,'|')+1,5) as blog, + COUNT(*) as count, + SUM(LENGTH(key)+2 + LENGTH(value)+4 + 8+2) as size + FROM wp_cache WHERE blog IN ('00000','{$blog_id}') + AND (expire = 0 OR expire >= {$this->time_now}) GROUP BY name;")) + { + while ($row = $result->fetch()) { + $stats['database-groups'][ $row['name'] ] = [$row['count'], $row['size']]; + } + $result->closeCursor(); + ksort($stats['database-groups']); + $stats['database-groups']['Total'] = [ + array_sum(array_column($stats['database-groups'],0)), + array_sum(array_column($stats['database-groups'],1)) + ]; + } + } + + return $stats; + } + + + /** + * Returns the cache hit ratio (formatted) + * + * @param int $hits number of hits + * @param int $misses number of misses + * @return string formatted cache hit ratio + */ + private function cache_hit_ratio(int $hits, int $misses): string + { + return ($hits > 0) + ? number_format( ($hits / ($hits + $misses)) * 100, 2 ) . '%' + : '0.00%'; + } + + + /** + * Returns the stats from the last sample saved. + * + * @param string $febe - front-end ('fe') or back-end ('be') + */ + public function getLastSample( $febe = 'fe' ): array + { + if ( $row = $this->get( "sample-{$febe}", self::GROUP_ID ) ) { + return $row; + } + return $this->getStats(true); + } + + + /* + * MySQL transients + */ + + + /** + * Import existing MySQL transients + * + */ + private function import_wp_transients(): void + { + global $wpdb; + + // see if we've done this already + if ( $row = $this->get( 'transients', self::GROUP_ID ) ) { + return; + } + + // write all in one transaction + $this->set_delayed_writes( true ); + + // import transients from options table + + $optionSQL = + "SELECT option_name as name, option_value as value". + " FROM {$wpdb->options} WHERE option_name LIKE %s AND option_name NOT LIKE %s"; + + $transients = $wpdb->get_results( + $wpdb->prepare($optionSQL,'_transient_%','_transient_timeout_%') + ); + + if ($transients && !is_wp_error($transients)) { + // so we don't try to use this cache + wp_using_ext_object_cache( false ); + foreach ($transients as $row) { + $this->add_wp_transient($row,'transient'); + } + wp_using_ext_object_cache( true ); + } + + // import site transients from options or sitemeta table + + $siteSQL = ($this->multisite) + ? "SELECT meta_key as name, meta_value as value". + " FROM {$wpdb->sitemeta} WHERE meta_key LIKE %s AND meta_key NOT LIKE %s" + : $optionSQL; + + $transients = $wpdb->get_results( + $wpdb->prepare($siteSQL,'_site_transient_%','_site_transient_timeout_%') + ); + + if ($transients && !is_wp_error($transients)) { + // so we don't try to use this cache + wp_using_ext_object_cache( false ); + foreach ($transients as $row) { + $this->add_wp_transient($row,'site-transient'); + } + wp_using_ext_object_cache( true ); + } + + $this->set('transients', [ wp_date('c'),$this->cache_stats['transients imported'] ], self::GROUP_ID, 0); + $this->set_delayed_writes(); + } + + + /** + * load a single transient from WP + * + * @param object $record transient record + * @param string $group 'transient' or 'site-transient' + */ + private function add_wp_transient(object $record, string $group): void + { + $key = str_replace(['_site_transient_','_transient_'],'',$record->name); + + if ($group == 'transient') { + $expire = get_option('_transient_timeout_'.$key,0); + // delete_transient($key); + } else { + $expire = get_site_option('_site_transient_timeout_'.$key,0); + // delete_site_transient($key); + } + + if ($expire) { + if ($expire <= $this->time_now) return; + $expire = $this->time_now - $expire; + } + + $this->set($key, maybe_unserialize($record->value), $group, $expire); + $this->addStats('transients imported',1); + } +} + + +/* + * + * global wp functions (wp-include/cache.php) + * WP_PLUGIN_DIR not yet set + */ + +require __DIR__.'/plugins/eacobjectcache/src/wp-cache.php'; diff --git a/src/wp-cache.php b/src/wp-cache.php new file mode 100644 index 0000000..2de89be --- /dev/null +++ b/src/wp-cache.php @@ -0,0 +1,516 @@ +add( $key, $data, $group, (int) $expire ); +} + +/** + * Adds multiple values to the cache in one call. + * + * @since 6.0.0 + * + * @see WP_Object_Cache::add_multiple() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param array $data Array of keys and values 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 either + * true on success, or false if cache key and group already exist. + */ +function wp_cache_add_multiple( array $data, $group = '', $expire = 0 ) { + global $wp_object_cache; + + return $wp_object_cache->add_multiple( $data, $group, $expire ); +} + +/** + * Replaces the contents of the cache with new data. + * + * @since 2.0.0 + * + * @see WP_Object_Cache::replace() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int|string $key The key for the cache data that should be replaced. + * @param mixed $data The new data to store in the cache. + * @param string $group Optional. The group for the cache data that should be replaced. + * Default empty. + * @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. + */ +function wp_cache_replace( $key, $data, $group = '', $expire = 0 ) { + global $wp_object_cache; + + return $wp_object_cache->replace( $key, $data, $group, (int) $expire ); +} + +/** + * Replace multiple values to the cache in one call. + * + * @since not in WordPress + * + * @see WP_Object_Cache::replace_multiple() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param array $data Array of keys and values 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 either + * true on success, or false if cache key and group already exist. + */ +function wp_cache_replace_multiple( array $data, $group = '', $expire = 0 ) { + global $wp_object_cache; + + return $wp_object_cache->replace_multiple( $data, $group, $expire ); +} + +/** + * Saves the data to the cache. + * + * Differs from wp_cache_add() and wp_cache_replace() in that it will always write data. + * + * @since 2.0.0 + * + * @see WP_Object_Cache::set() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int|string $key The cache key to use for retrieval later. + * @param mixed $data The contents to store in the cache. + * @param string $group Optional. Where to group the cache contents. Enables the same key + * to be used across groups. Default empty. + * @param int $expire Optional. When to expire the cache contents, in seconds. + * Default 0 (no expiration). + * @return bool True on success, false on failure. + */ +function wp_cache_set( $key, $data, $group = '', $expire = 0 ) { + global $wp_object_cache; + + return $wp_object_cache->set( $key, $data, $group, (int) $expire ); +} + +/** + * Sets multiple values to the cache in one call. + * + * @since 6.0.0 + * + * @see WP_Object_Cache::set_multiple() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param array $data Array of keys and values 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 either + * true on success, or false on failure. + */ +function wp_cache_set_multiple( array $data, $group = '', $expire = 0 ) { + global $wp_object_cache; + + return $wp_object_cache->set_multiple( $data, $group, $expire ); +} + +/** + * Retrieves the cache contents from the cache by key and group. + * + * @since 2.0.0 + * + * @see WP_Object_Cache::get() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int|string $key The key under which the cache contents are stored. + * @param string $group Optional. Where the cache contents are grouped. Default empty. + * @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. + */ +function wp_cache_get( $key, $group = '', $force = false, &$found = null ) { + global $wp_object_cache; + + return $wp_object_cache->get( $key, $group, $force, $found ); +} + +/** + * Retrieves multiple values from the cache in one call. + * + * @since 5.5.0 + * + * @see WP_Object_Cache::get_multiple() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param array $keys Array of keys under which the cache contents are stored. + * @param string $group Optional. Where the cache contents are grouped. Default empty. + * @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. + */ +function wp_cache_get_multiple( $keys, $group = '', $force = false ) { + global $wp_object_cache; + + return $wp_object_cache->get_multiple( $keys, $group, $force ); +} + +/** + * Removes the cache contents matching key and group. + * + * @since 2.0.0 + * + * @see WP_Object_Cache::delete() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int|string $key What the contents in the cache are called. + * @param string $group Optional. Where the cache contents are grouped. Default empty. + * @return bool True on successful removal, false on failure. + */ +function wp_cache_delete( $key, $group = '' ) { + global $wp_object_cache; + + return $wp_object_cache->delete( $key, $group ); +} + +/** + * Deletes multiple values from the cache in one call. + * + * @since 6.0.0 + * + * @see WP_Object_Cache::delete_multiple() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param array $keys Array of keys under which the cache to 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. + */ +function wp_cache_delete_multiple( array $keys, $group = '' ) { + global $wp_object_cache; + + return $wp_object_cache->delete_multiple( $keys, $group ); +} + +/** + * Increments numeric cache item's value. + * + * @since 3.3.0 + * + * @see WP_Object_Cache::incr() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int|string $key The key for the cache contents that should be incremented. + * @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 empty. + * @return int|false The item's new value on success, false on failure. + */ +function wp_cache_incr( $key, $offset = 1, $group = '' ) { + global $wp_object_cache; + + return $wp_object_cache->incr( $key, $offset, $group ); +} + +/** + * Decrements numeric cache item's value. + * + * @since 3.3.0 + * + * @see WP_Object_Cache::decr() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @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 empty. + * @return int|false The item's new value on success, false on failure. + */ +function wp_cache_decr( $key, $offset = 1, $group = '' ) { + global $wp_object_cache; + + return $wp_object_cache->decr( $key, $offset, $group ); +} + +/** + * Removes all cache items. + * + * @since 2.0.0 + * + * @see WP_Object_Cache::flush() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @return bool True on success, false on failure. + */ +function wp_cache_flush() { + global $wp_object_cache; + + return $wp_object_cache->flush(); +} + +/** + * Removes all cache items from the in-memory runtime cache. + * + * @since 6.0.0 + * + * @see WP_Object_Cache::flush() + * + * @return bool True on success, false on failure. + */ +function wp_cache_flush_runtime() { + global $wp_object_cache; + + return $wp_object_cache->flush_runtime(); +} + +/** + * Removes all cache items in a group, if the object cache implementation supports it. + * + * Before calling this function, always check for group flushing support using the + * `wp_cache_supports( 'flush_group' )` function. + * + * @since 6.1.0 + * + * @see WP_Object_Cache::flush_group() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param string $group Name of group to remove from cache. + * @return bool True if group was flushed, false otherwise. + */ +function wp_cache_flush_group( $group ) { + global $wp_object_cache; + + return $wp_object_cache->flush_group( $group ); +} + +/** + * Removes all cache items for a blog, if the object cache implementation supports it. + * + * Before calling this function, always check for blog flushing support using the + * `wp_cache_supports( 'flush_blog' )` function. + * + * @param int $blog id of blog to remove from cache (default get_current_blog_id()). + * @return bool True if blog was flushed, false otherwise. + */ +function wp_cache_flush_blog( $blog_id = null ) { + global $wp_object_cache; + + return $wp_object_cache->flush_blog( $blog_id ); +} + +/** + * Determines whether the object cache implementation supports a particular feature. + * + * @since 6.1.0 + * + * @param string $feature Name of the feature to check for. Possible values include: + * 'add_multiple', 'set_multiple', 'get_multiple', 'delete_multiple', + * 'flush_runtime', 'flush_group'. + * @return bool True if the feature is supported, false otherwise. + */ +function wp_cache_supports( $feature ) { + switch ( $feature ) { + case 'add_multiple': + case 'set_multiple': + case 'get_multiple': + case 'replace_multiple': + case 'delete_multiple': + case 'flush_runtime': + case 'flush_group': + case 'flush_blog': + case 'prefetch_groups': + case 'permanent_groups': + return true; + + default: + return false; + } +} + +/** + * Closes the cache. + * + * This function has ceased to do anything since WordPress 2.5. The + * functionality was removed along with the rest of the persistent cache. + * + * This does not mean that plugins can't implement this function when they need + * to make sure that the cache is cleaned up after WordPress no longer needs it. + * + * @since 2.0.0 + * + * @return true Always returns true. + */ +function wp_cache_close() { + global $wp_object_cache; + + $wp_object_cache->close(); +} + +/** + * Adds a group or set of groups to the list of global groups. (wp_start_object_cache) + * + * @since 2.6.0 + * + * @see WP_Object_Cache::add_global_groups() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param string|string[] $groups A group or an array of groups to add. + */ +function wp_cache_add_global_groups( $groups ) { + global $wp_object_cache; + + $wp_object_cache->add_global_groups( $groups ); +} + +/** + * Adds a group or set of groups to the list of non-persistent groups. (wp_start_object_cache) + * + * @since 2.6.0 + * + * @param string|string[] $groups A group or an array of groups to add. + */ +function wp_cache_add_non_persistent_groups( $groups ) { + global $wp_object_cache; + + $wp_object_cache->add_non_persistent_groups( $groups ); +} + +/** + * Non-Standard - Adds a group or set of groups that can have no expiration. + * + * @param string|string[] $groups A group or an array of groups to add. + */ +function wp_cache_add_permanent_groups( $groups ) { + global $wp_object_cache; + + $wp_object_cache->add_permanent_groups( $groups ); +} + +/** + * Non-Standard - Adds a group or set of groups to the list of pre-loaded groups. + * + * @param string|string[] $groups A group or an array of groups to add. + */ +function wp_cache_add_prefetch_groups( $groups ) { + global $wp_object_cache; + + $wp_object_cache->add_prefetch_groups( $groups ); +} + +/** + * Switches the internal blog ID. + * + * This changes the blog id used to create keys in blog specific groups. + * + * @since 3.5.0 + * + * @see WP_Object_Cache::switch_to_blog() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int $blog_id Site ID. + */ +function wp_cache_switch_to_blog( $blog_id ) { + global $wp_object_cache; + + $wp_object_cache->switch_to_blog( $blog_id ); +} + +/** + * Resets internal cache keys and structures. + * + * If the cache back end uses global blog or site IDs as part of its cache keys, + * this function instructs the back end to reset those keys and perform any cleanup + * since blog or site IDs have changed since cache init. + * + * This function is deprecated. Use wp_cache_switch_to_blog() instead of this + * function when preparing the cache for a blog switch. For clearing the cache + * during unit tests, consider using wp_cache_init(). wp_cache_init() is not + * recommended outside of unit tests as the performance penalty for using it is high. + * + * @since 3.0.0 + * @deprecated 3.5.0 Use wp_cache_switch_to_blog() + * @see WP_Object_Cache::reset() + * + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + */ +function wp_cache_reset() { + _deprecated_function( __FUNCTION__, '3.5.0', 'wp_cache_switch_to_blog()' ); + + global $wp_object_cache; + + $wp_object_cache->reset(); +} + +/** + * set an object reference + * + * Contributed by Philipp Stracker + * https://developer.wordpress.org/reference/classes/wp_object_cache/ + */ +/* +if (!function_exists('wp_cache_set_ref')) +{ + function wp_cache_set_ref( $key, $data, $group = '', $expire = 0 ) { + return wp_cache_set( $key, [ 'ref' => $data ], $group, $expire ); + } +} +*/ + +/** + * get an object reference + * + * Contributed by Philipp Stracker + * https://developer.wordpress.org/reference/classes/wp_object_cache/ + */ +/* +if (!function_exists('wp_cache_set_ref')) +{ + function wp_cache_get_ref( $key, $group = '', $force = false, &$found = null ) { + $wrapper = wp_cache_get( $key, $group, $force, $found ); + if ( is_array( $wrapper ) && array_key_exists( 'ref', $wrapper ) ) { + return $wrapper['ref']; + } + return $wrapper; + } +} +*/