From: Steve Sutton Date: Tue, 4 Jun 2019 14:56:06 +0000 (-0400) Subject: Add glmLock trait X-Git-Tag: v2.12.4~1^2~16 X-Git-Url: http://cvs2.gaslightmedia.com/gitweb/?a=commitdiff_plain;h=a5a4bc6e64857ffc6881b88ee27f33593fca7f20;p=WP-Plugins%2Fglm-member-db.git Add glmLock trait Trait to use for locking processes. --- diff --git a/classes/glmLockTrait.php b/classes/glmLockTrait.php new file mode 100644 index 00000000..71c7d5a3 --- /dev/null +++ b/classes/glmLockTrait.php @@ -0,0 +1,57 @@ + 'defaultLockName', + 'timeout' => 30, + 'wait' => false, + ); + $config = array_merge( $defaultConfig, $config ); + + // Check for currently running process + $myId = rand(); + + // Try to get any current DB Lock + $lockName = $config['lockName']; + $lock = get_option( $lockName ); + + // If another instance is doing a database update + // (If we got something back that's a 2 el array that doesn't have my ID and hasn't expired) + if ( $lock && is_array( $lock ) && count( $lock ) == 2 && $lock[0] != $myId && $lock[1] > microtime( true ) ) { + trigger_error('GlmLock::requestLock() - Lock Name: '.$config['lockName'].' - Instance: '.$myId.'. - Another instance is processing', E_USER_NOTICE ); + return false; + } else { + trigger_error('GlmLock::requestLock() - Lock Name: '.$config['lockName'].' - Instance: '.$myId.' - This instance trying to lock', E_USER_NOTICE ); + + // Add our ID and timeout then wait a second + add_option( $lockName, array( $myId, ( microtime( true ) + $config['timeout'] ) ) ); + sleep( 1 ); + + // Make sure this instance has the lock + $lock = get_option( $lockName ); + if ( $lock && is_array( $lock ) && count( $lock ) == 2 && $lock[0] == $myId && $lock[1] > microtime( true ) ) { + return $lock; + } else { + return false; + } + } + + return $lock; + } + + public function requestUnLock( $config ) + { + // Setup Default config + $defaultConfig = array( + 'lockName' => 'defaultLockName', + ); + $config = array_merge( $defaultConfig, $config ); + + delete_option( $config['lockName'] ); + trigger_error('GlmLock::requestUnLock() - Lock Name: '.$config['lockName'].' - Removed', E_USER_NOTICE ); + } +} diff --git a/index.php b/index.php index 5a37a4d0..1c38dd52 100755 --- a/index.php +++ b/index.php @@ -361,6 +361,9 @@ require_once GLM_MEMBERS_PLUGIN_PATH . '/lib/smartyTemplateSupport.php'; // Load Script and Style Registry require_once GLM_MEMBERS_PLUGIN_PATH . '/classes/scriptRegistry.php'; +// Load GlmLock Trait +require_once GLM_MEMBERS_PLUGIN_PATH . '/classes/glmLockTrait.php'; + // Check all database tables for all registered add-ons, allow install/update, and add various items if (glmCheckDatabase('install')) {