From: Steve Sutton Date: Tue, 17 Sep 2019 19:22:47 +0000 (-0400) Subject: Updates for notifications X-Git-Tag: v4.1.0^2~3 X-Git-Url: http://cvs2.gaslightmedia.com/gitweb/index.cgi?a=commitdiff_plain;h=09606b93fad6569a7d5dc48ac398d5ba03da184b;p=WP-Plugins%2Fglm-serverstats.git Updates for notifications Creating cache tables for the plugin. Store the messages into the cache table and store the dismissed notices into a table. Use a transient to only check the cache every 20 minutes at most. --- diff --git a/classes/GlmServerStats.php b/classes/GlmServerStats.php new file mode 100644 index 0000000..6a83692 --- /dev/null +++ b/classes/GlmServerStats.php @@ -0,0 +1,253 @@ + + * @copyright 2013 Gaslight Media + * @license Gaslight Media + * @version SVN: (0.1) + * @link <> + */ + +/** + * Toolkit_Package_database + * + * Description of database + * + * @category Toolkit + * @package Package + * @author Steve Sutton + * @copyright 2013 Gaslight Media + * @license Gaslight Media + * @release Release: (0.1) + * @link <> + */ +class GlmServerStats +{ + public $wpdb; + public $prefix; + public $dbVersionOption; + public $userId; + public $cacheTableName = 'glm_notice_message_cache'; + public $userDismissTableName = 'glm_notice_user_dismiss'; + + /** + * Clas constructor for the database + * + * @param type $wpdb Wordpress db object + */ + public function __construct( $wpdb ) + { + $this->wpdb = $wpdb; + $this->userId = \get_current_user_id(); + \register_activation_hook( + GLM_SERVERSTATS_PLUGIN_PATH . 'index.php', + array( $this, 'install' ) + ); + \add_action( 'plugins_loaded', array( $this, 'glm_notice_db_check' ) ); + + $this->dbVersionOption = 'glmServerStatsDbVersion'; + $this->prefix = $this->wpdb->prefix . 'ServerStats_'; + } + + /** + * Install the database tables needed for jobs + */ + public function install() + { + $collate = $this->wpdb->get_charset_collate(); + + $sql = "CREATE TABLE {$this->prefix}{$this->cacheTableName} ( + id INT NOT NULL AUTO_INCREMENT, + status TINYINT(1) NULL, + title TINYTEXT NULL, + dashboard_message TEXT NULL, + message TEXT NULL, + created DATETIME NOT NULL, + updated DATETIME NOT NULL, + PRIMARY KEY (id), + INDEX(updated) + ) {$collate}"; + include_once ABSPATH . 'wp-admin/includes/upgrade.php'; + \dbDelta( $sql ); + + $sql = "CREATE TABLE {$this->prefix}{$this->userDismissTableName} ( + id INT NOT NULL AUTO_INCREMENT, + user_id INT NOT NULL, + message_id INT NOT NULL, + PRIMARY KEY (id), + INDEX(user_id), + INDEX(message_id) + ) {$collate}"; + \dbDelta( $sql ); + + \update_option( $this->dbVersionOption, GLM_SERVERSTATS_PLUGIN_DB_VERSION ); + } + + /** + * DB Version update check to update the database tables + */ + public function glm_notice_db_check() + { + if ( GLM_SERVERSTATS_PLUGIN_DB_VERSION != \get_option( $this->dbVersionOption ) ) { + $this->install(); + } + } + + public function getNotices( $id = null ) + { + $where = ''; + $notices = array(); + if ( !$this->userId ) { + return $notices; + } + if ( $id ) { + $where = " AND T.id = $id "; + } + $notices = $this->wpdb->get_results( + "SELECT T.* + FROM {$this->prefix}{$this->cacheTableName} T + WHERE T.status = 10 + $where + AND NOT (SELECT count(*) + FROM {$this->prefix}{$this->userDismissTableName} U + WHERE U.user_id = {$this->userId} + AND U.message_id = T.id) + ORDER BY T.updated DESC", + ARRAY_A + ); + return $notices; + } + + public function getLastUpdatedTime() + { + return $this->wpdb->get_var( + "SELECT max(updated) FROM {$this->prefix}{$this->cacheTableName}" + ); + } + + /** + * Update the cache table from remote relay. + */ + public function updateCache() + { + // If the update transient exists don't get anything from the relay. + if ( false === ( get_transient( 'ServerStatCacheUpdate' ) ) ) { + trigger_error( 'running updateCache' ); + $lastUpdate = $this->getLastUpdatedTime(); + $timestamp = 0; + if ( $lastUpdate ) { + $timestamp = strtotime( $lastUpdate ); + } + + $fetchUrl = GLM_SERVERSTATS_PLUGIN_RELAY_URL; + if ( $timestamp ) { + $fetchUrl .= '&option=since×tamp=' . $timestamp; + } else { + $fetchUrl .= '&option=full'; + } + $notices = array(); + $response = \wp_remote_get( $fetchUrl ); + $message_data = \wp_remote_retrieve_body( $response ); + $status = \wp_remote_retrieve_response_code( $response); + + if ( $status == 200 ) { + $notices = json_decode( $message_data, true ); + } + + set_transient( 'ServerStatCacheUpdate', true, 20 * MINUTE_IN_SECONDS ); + + if ( !empty( $notices ) ) { + trigger_error( 'updating cache', E_USER_NOTICE ); + foreach ( $notices as $notice ) { + $this->cacheNotice( $notice ); + } + } else { + trigger_error( 'no new ones found', E_USER_NOTICE ); + } + } + + } + + public function cacheNotice( $notice ) + { + // Check to see if the notice is already cached. + $isCached = $this->wpdb->get_var( + "SELECT id + FROM {$this->prefix}{$this->cacheTableName} + WHERE id = {$notice['id']}" + ); + if ( $isCached ) { + // Update this cache. + $this->wpdb->update( + $this->prefix . $this->cacheTableName, + array( + 'id' => $notice['id'], + 'status' => $notice['status']['value'], + 'title' => $notice['title'], + 'dashboard_message' => $notice['dashboard_message'], + 'message' => $notice['message'], + 'updated' => $notice['updated']['mysql_datetime'] + ), + array( 'id' => $isCached ), + array( + '%d', // id + '%d', // status + '%s', // title + '%s', // dashboard_message + '%s', // message + '%s' // updated + ), + array( + '%d' + ) + ); + return false; + } else { + // Store this in cache. + $this->wpdb->insert( + $this->prefix . $this->cacheTableName, + array( + 'id' => $notice['id'], + 'status' => $notice['status']['value'], + 'title' => $notice['title'], + 'dashboard_message' => $notice['dashboard_message'], + 'message' => $notice['message'], + 'created' => date('Y-m-d H:i:s'), + 'updated' => $notice['updated']['mysql_datetime'] + ), + array( + '%d', // id + '%d', // status + '%s', // title + '%s', // dashboard_message + '%s', // message + '%s', // created + '%s' // updated + ) + ); + } + + } + + public function dismissNotice( $message_id ) + { + $this->wpdb->insert( + $this->prefix . $this->userDismissTableName, + array( + 'user_id' => $this->userId, + 'message_id' => $message_id + ), + array( + '%d', + '%d' + ) + ); + } + +} diff --git a/defines.php b/defines.php index 579e453..920bb17 100755 --- a/defines.php +++ b/defines.php @@ -37,7 +37,7 @@ define('GLM_SERVERSTATS_PLUGIN_NAME', 'Gaslight Media - Server Data Usage Plugin define('GLM_SERVERSTATS_PLUGIN_SHORT_NAME', 'ServerStats'); define('GLM_SERVERSTATS_PLUGIN_SLUG', 'glm-serverstats'); define('GLM_SERVERSTATS_PLUGIN_RELAY_URL', 'https://www.gaslightmedia.com/wp-admin/admin-ajax.php?action=glm_members_admin_ajax&glm_action=relay'); -// define('GLM_SERVERSTATS_PLUGIN_RELAY_URL', 'http://develop.localhost/wp-admin/admin-ajax.php?action=glm_members_admin_ajax&glm_action=relay'); +//define('GLM_SERVERSTATS_PLUGIN_RELAY_URL', 'http://localhost/wp-admin/admin-ajax.php?action=glm_members_admin_ajax&glm_action=relay'); define('GLM_SERVERSTATS_PLUGIN_RELAY_LATEST', 'glm_serverstats_relay_latest_' . $user_id); define('GLM_SERVERSTATS_PLUGIN_RELAY_LATEST_VERSION', 'glm_serverstats_relay_latest_version'); define('GLM_SERVERSTATS_PLUGIN_RELAY_LATEST_TIMEOUT', '20 minutes'); diff --git a/index.php b/index.php index eb79f9f..ca59584 100755 --- a/index.php +++ b/index.php @@ -30,6 +30,8 @@ if (!defined('ABSPATH')) { define('GLM_SERVERSTATS_PLUGIN_VERSION', '4.0.2'); +define('GLM_SERVERSTATS_PLUGIN_DB_VERSION', '0.0.1'); + // Required to be able to get user capabilities when being called as a filter from the main plugin require_once ABSPATH . 'wp-includes/pluggable.php'; @@ -40,6 +42,10 @@ require_once 'defines.php'; require_once GLM_SERVERSTATS_PLUGIN_LIB_PATH.'/smartyTemplateSupport.php'; +// Grab the database class +require_once GLM_SERVERSTATS_PLUGIN_PATH . '/classes/GlmServerStats.php'; +$serverStatsDb = new \GlmServerStats\GlmServerStats( $wpdb ); + // Connect to bandwidth database and get all settings for this site $bwdb = false; $websiteSettings = bandwidthDataConnect(GLM_SERVERSTATS_PLUGIN_HOSTNAME); @@ -214,15 +220,15 @@ function glmServerStatsAjax() * model and the view. * */ -function serverStatsController($model, $isAjax = false) +function serverStatsController( $model, $isAjax = false ) { - if (GLM_SERVERSTATS_PLUGIN_DEBUG) { - $debugStartTime = microtime(true); + if ( GLM_SERVERSTATS_PLUGIN_DEBUG ) { + $debugStartTime = microtime( true ); trigger_error("GLM Usage Controller Start: Model = $model", E_USER_NOTICE ); } - if (GLM_SERVERSTATS_PLUGIN_DEBUG && !$isAjax) { + if ( GLM_SERVERSTATS_PLUGIN_DEBUG && !$isAjax ) { trigger_error("GLM Usage Plugin Debug Enabled: *** Turn off for production *** - See defines.php", E_USER_NOTICE ); } @@ -231,15 +237,15 @@ function serverStatsController($model, $isAjax = false) glmServerStatsScripts(); // Load and execute the specified model - require_once GLM_SERVERSTATS_PLUGIN_MODEL_PATH.'/'.$model.'.php'; - $Model = new $model(); + require_once GLM_SERVERSTATS_PLUGIN_MODEL_PATH . '/' . $model . '.php'; + $Model = new $model(); $results = $Model->model(); // If there's a redirect request, run that (this controler can only do one level of redirect) if (isset($results['redirect'])) { $model = $results['redirect']; require_once GLM_SERVERSTATS_PLUGIN_MODEL_PATH.'/'.$model.'.php'; - $Model = new $model(); + $Model = new $model(); $results = $Model->model(); } diff --git a/js/notice-update.js b/js/notice-update.js index dbf76c2..a0299a4 100644 --- a/js/notice-update.js +++ b/js/notice-update.js @@ -1,11 +1,13 @@ jQuery(document).on( 'click', '.glm-serverstatus-notice .notice-dismiss', function() { - console.log( 'clicked on dismissed' ); - + // Get id of the message being dismissed. + var message_id = jQuery(this).parent('.glm-serverstatus-notice').data('id'); + console.log( 'message_id:', message_id ); jQuery.ajax({ url: ajaxurl, data: { - action: 'my_dismiss_glm_notice' + action: 'my_dismiss_glm_notice', + message_id: message_id } }) -}) +}); diff --git a/models/glmInfoNotifications.php b/models/glmInfoNotifications.php index 1a6068c..b3b9d4b 100644 --- a/models/glmInfoNotifications.php +++ b/models/glmInfoNotifications.php @@ -13,6 +13,8 @@ * @link http://dev.gaslightmedia.com/ */ +require_once GLM_SERVERSTATS_PLUGIN_PATH . '/classes/GlmServerStats.php'; + /* * This class provides support for the reporting of server bandwidth stats * for simple day and month values as well as detailed lists of values for @@ -23,6 +25,9 @@ class glmInfoNotifications { public function model() { + global $wpdb; + $serverStatsDb = new \GlmServerStats\GlmServerStats( $wpdb ); + // Initiate Variables. $messages = false; $view_type = 'main'; @@ -37,40 +42,25 @@ class glmInfoNotifications case 'view': $url .= '&option=view'; if ( isset( $_REQUEST['id'] ) && $id = filter_var( $_REQUEST['id'], FILTER_VALIDATE_INT ) ) { - $url .= '&id=' . $id; + $messages = $serverStatsDb->getNotices( $id ); } break; case 'full': - $url .= '&option=full'; - $view_type = 'list'; - break; - case 'latest': default: - $url .= '&option=latest'; + $messages = $serverStatsDb->getNotices(); + $view_type = 'list'; break; - } - - // echo '
$url: ' . print_r( $url, true ) . '
'; - - // Get the messages from the main plugin. - $fetchData = wp_remote_get( $url ); - $messageData = wp_remote_retrieve_body( $fetchData ); - $status = wp_remote_retrieve_response_code( $fetchData); + break; - if ( $status == 200 ) { - $messages = json_decode( $messageData, true ); - } else { } - // echo '
$messages: ' . print_r( $messages, true ) . '
'; - // Compile template data $templateData = array( 'messages' => $messages, - 'status' => $status, + 'status' => true, 'view_type' => $view_type, 'admin_url' => admin_url('admin.php'), ); diff --git a/setup/adminHooks.php b/setup/adminHooks.php index 903a407..696c286 100644 --- a/setup/adminHooks.php +++ b/setup/adminHooks.php @@ -77,26 +77,20 @@ if ( $user_is_admin || $user_is_editor ) { $latest = get_option( GLM_SERVERSTATS_PLUGIN_RELAY_LATEST, false ); $latest_data = unserialize( $latest ); - // trigger_error( print_r( $latest_data, true ), E_USER_NOTICE ); // check latest for time if too old then fetch latest and update time. $stale_time = strtotime( '-' . GLM_SERVERSTATS_PLUGIN_RELAY_LATEST_TIMEOUT ); - // trigger_error( '$stale_time: ' . $stale_time . ' $catched time: ' . $latest_data['cached'], E_USER_NOTICE ); // If you have a cache then check to see if that cache is older than GLM_SERVERSTATS_PLUGIN_RELAY_LATEST_TIMEOUT. // If it is then set fetch_latest to true. if ( $latest ) { if ( !empty( $latest_data['cached'] ) && $latest_data['cached'] <= $stale_time ) { $fetch_latest = true; - // trigger_error( '$latest found but expired', E_USER_NOTICE ); } else if ( empty( $latest_data['cached'] ) ) { $fetch_latest = true; - // trigger_error( '$latest found but no cached time', E_USER_NOTICE ); } } else { $fetch_latest = true; - // trigger_error( 'No $latest found', E_USER_NOTICE ); } - // trigger_error( '$fetch_latest: ' . $fetch_latest, E_USER_NOTICE ); // If fetch_latest then grab the newest from Relay. if ( $fetch_latest ) { @@ -127,8 +121,6 @@ if ( $user_is_admin || $user_is_editor ) { } else { $latest_version = false; } - // trigger_error( '$latest_version: ' . $latest_version, E_USER_NOTICE ); - // trigger_error( '$latest_data[version]: ' . $latest_data['version'], E_USER_NOTICE ); // Need to check the latest version with what we have cached. // If our version is the same then we're ok. Don't delete the dismiss option. if ( !empty( $latest_data ) && !empty( $latest_data['version'] ) && $latest_version == $latest_data['version'] ) { @@ -136,7 +128,6 @@ if ( $user_is_admin || $user_is_editor ) { } else { // If there's a new update then delete the dismiss option. delete_option( GLM_SERVERSTATS_PLUGIN_RELAY_DISMISS ); - // trigger_error( "Delete option relay dismiss: " . GLM_SERVERSTATS_PLUGIN_RELAY_DISMISS , E_USER_NOTICE ); } $latest_data = array( @@ -163,37 +154,46 @@ if ( $user_is_admin || $user_is_editor ) { } ); - $latest = get_option( GLM_SERVERSTATS_PLUGIN_RELAY_LATEST, false ); - if ( $latest ) { - $latest_data = unserialize( $latest ); - if ( $latest_data['title'] && $latest_data['dashboard_message'] ) { - if ( empty( get_option( GLM_SERVERSTATS_PLUGIN_RELAY_DISMISS ) ) ) { - add_action( - 'admin_notices', - function(){ - $page = isset( $_REQUEST['page'] ) ? $_REQUEST['page'] : ''; - if ( $page === 'glm-info-main-menu' ) { - return false; - } - echo '
'; - // Grab the cached notice. - $latest = get_option( GLM_SERVERSTATS_PLUGIN_RELAY_LATEST, false ); - $latest_data = unserialize( $latest ); - - echo '
'; - echo '

Gaslight Media Notification:
'; - echo '

'.$latest_data['title'].'
'; - echo wpautop( $latest_data['dashboard_message'] ); - echo '

'; - echo '

More Details

'; - echo '
'; - }, 10, 1 + function glmServerAddNotice( $notice ) + { + add_action( + 'admin_notices', + function() use ($notice) { + printf( + '
+
+

Gaslight Media Notification

+

+ %s
+ %s +

+
+ More Details +
', + $notice['id'], + $notice['title'], + wpautop( $notice['dashboard_message'] ), + admin_url( 'admin.php' ) . '?page=glm-info-main-menu&option=view&id=' . $notice['id'] ); - } + }, 10, 1 + ); + } + $serverStatsDb->updateCache(); + + // Get all notices. + $notices = $serverStatsDb->getNotices(); + $onNoticesPage = false; + if ( isset( $_REQUEST['page'] ) && $_REQUEST['page'] === 'glm-info-main-menu' ) { + $onNoticesPage = true; + } + if ( !empty( $notices ) && !$onNoticesPage ) { + foreach ( $notices as $notice ) { + glmServerAddNotice( $notice ); } } + add_action( 'admin_enqueue_scripts', function(){ wp_enqueue_script( 'glm-serverstats-notice-update', @@ -204,8 +204,11 @@ if ( $user_is_admin || $user_is_editor ) { ); } ); - add_action( 'wp_ajax_my_dismiss_glm_notice', function(){ - // Set option for dismissing notices. - update_option( GLM_SERVERSTATS_PLUGIN_RELAY_DISMISS, 1, true ); + add_action( 'wp_ajax_my_dismiss_glm_notice', function() use ($serverStatsDb) { + trigger_error( 'wp_ajax_my_dismiss_glm_notice', E_USER_NOTICE ); + trigger_error( print_r($_REQUEST, true), E_USER_NOTICE ); + if ( isset( $_REQUEST['message_id'] ) && $id = filter_var( $_REQUEST['message_id'], FILTER_VALIDATE_INT ) ) { + $serverStatsDb->dismissNotice( $id ); + } } ); } diff --git a/setup/standardTemplateParams.php b/setup/standardTemplateParams.php index 5544f37..4fc99a6 100644 --- a/setup/standardTemplateParams.php +++ b/setup/standardTemplateParams.php @@ -26,3 +26,4 @@ $smarty->templateAssign('thisPage', (isset($_REQUEST['page']) ? $_REQUEST['page' $smarty->templateAssign('glmWordpresBasePluginPath', GLM_SERVERSTATS_PLUGIN_PATH ); $smarty->templateAssign('thisYear', date ( 'Y' ) ); $smarty->templateAssign('adminUrl', GLM_SERVERSTATS_PLUGIN_ADMIN_URL); +$smarty->templateAssign('glmFromContact', array('email' => 'plugins@gaslightmedia.com')); diff --git a/views/glmInfoNotifications.html b/views/glmInfoNotifications.html index 8f7e750..5a8ef8f 100644 --- a/views/glmInfoNotifications.html +++ b/views/glmInfoNotifications.html @@ -1,38 +1,60 @@ {* GLM Notification Menu Page *} -
+{include file='header.html'} -

GLM Notifications

+

GLM Notifications

- +{* Grid Start *} +{$ui = [ + 'sectionColor' => '#ffE', + 'nowrap' => true +]} +{include file="ui/f6/grid-start.html"} -
+See All Notifications - {if $messages} - {if $view_type == 'main'} - {foreach $messages as $m} -
-
{$m.updated.datetime}
-

{$m.title}

- {$m.message} -
- {/foreach} - {else} +{$dateFormat = "%m/%d/%Y"} + +
+ + {if $messages} + {if $view_type == 'main'} + {foreach $messages as $m} +
+
{$m.updated.datetime|date_format:$dateFormat}
+

{$m.title}

+ {$m.message} +
+ {/foreach} + {else} + + + + + + {foreach $messages as $m} - + + + + + {/foreach} - {/if} - {else} -

There are currently no messages.

+
Updated Date Title Dashboard Message
{$m.updated.datetime|date_format:$dateFormat} {$m.title} {$m.dashboard_message|strip_tags}
{/if} - -
+ {else} +
+
+

You're all caught up!

+
+
+ {/if}
+ +{* Grid End *} +{$ui = [ + 'noFoundationInit' => true +]} +{include file="ui/f6/grid-end.html"} + +{include file='footer.html'}