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.
--- /dev/null
+<?php
+namespace GlmServerStats;
+/**
+ * database.php
+ *
+ * PHP version 5.3
+ *
+ * @category Toolkit
+ * @package Package
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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'
+ )
+ );
+ }
+
+}
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');
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';
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);
* 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 );
}
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();
}
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
}
})
-})
+});
* @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
{
public function model()
{
+ global $wpdb;
+ $serverStatsDb = new \GlmServerStats\GlmServerStats( $wpdb );
+
// Initiate Variables.
$messages = false;
$view_type = 'main';
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 '<pre>$url: ' . print_r( $url, true ) . '</pre>';
-
- // 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 '<pre>$messages: ' . print_r( $messages, true ) . '</pre>';
-
// Compile template data
$templateData = array(
'messages' => $messages,
- 'status' => $status,
+ 'status' => true,
'view_type' => $view_type,
'admin_url' => admin_url('admin.php'),
);
$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 ) {
} 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'] ) {
} 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(
}
);
- $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 '<div class="glm-serverstatus-notice updated notice is-dismissible">';
- // Grab the cached notice.
- $latest = get_option( GLM_SERVERSTATS_PLUGIN_RELAY_LATEST, false );
- $latest_data = unserialize( $latest );
-
- echo '<div style="display:inline-block;clear: left;">';
- echo '<p><b>Gaslight Media Notification: </b><br>';
- echo '<p><b>'.$latest_data['title'].'</b><br>';
- echo wpautop( $latest_data['dashboard_message'] );
- echo '</p></div>';
- echo '<p><a href="' . admin_url( 'admin.php' ) . '?page=glm-info-main-menu">More Details</a></p>';
- echo '</div>';
- }, 10, 1
+ function glmServerAddNotice( $notice )
+ {
+ add_action(
+ 'admin_notices',
+ function() use ($notice) {
+ printf(
+ '<div data-id="%d" class="glm-serverstatus-notice updated notice notice-info is-dismissible">
+ <div style="display:inline-block;clear: left;">
+ <h2>Gaslight Media Notification</h2>
+ <p>
+ <b>%s</b><br>
+ %s
+ </p>
+ </div>
+ <a href="%s">More Details</a>
+ </div>',
+ $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',
);
} );
- 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 );
+ }
} );
}
$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'));
{* GLM Notification Menu Page *}
-<div class="wrap">
+{include file='header.html'}
- <h1>GLM Notifications</h1>
+<h2>GLM Notifications</h2>
- <ul>
- <li>
- <a href="{$thisUrl}?page={$thisPage}&glm_action=index&option=full">Show All</a>
- </li>
- </ul>
+{* Grid Start *}
+{$ui = [
+ 'sectionColor' => '#ffE',
+ 'nowrap' => true
+]}
+{include file="ui/f6/grid-start.html"}
- <div id="glm-info-container">
+<a class="button primary" href="{$thisUrl}?page={$thisPage}&glm_action=index&option=full">See All Notifications</a>
- {if $messages}
- {if $view_type == 'main'}
- {foreach $messages as $m}
- <div class="glm-info-message">
- <div style="float: right; width: 200px;text-align: right;">{$m.updated.datetime}</div>
- <h2>{$m.title}</h2>
- {$m.message}
- </div>
- {/foreach}
- {else}
+{$dateFormat = "%m/%d/%Y"}
+
+<div id="glm-info-container" class="cell small-12">
+
+ {if $messages}
+ {if $view_type == 'main'}
+ {foreach $messages as $m}
+ <div class="glm-info-message">
+ <div>{$m.updated.datetime|date_format:$dateFormat}</div>
+ <h2>{$m.title}</h2>
+ {$m.message}
+ </div>
+ {/foreach}
+ {else}
+ <table id="glm-notices" class="hover">
+ <tr>
+ <th> Updated Date </th>
+ <th> Title </th>
+ <th> Dashboard Message </th>
+ </tr>
{foreach $messages as $m}
- <ul id="glm-notices">
- <li>
- <strong><a href="{$admin_url}?page={$thisPage}&glm_action=index&option=view&id={$m.id}">{$m.title}</a> {$m.updated.datetime}</strong>
- </li>
- </ul>
+ <tr>
+ <td width="150"> {$m.updated.datetime|date_format:$dateFormat} </td>
+ <td> <a href="{$admin_url}?page={$thisPage}&glm_action=index&option=view&id={$m.id}">{$m.title}</a> </td>
+ <td> {$m.dashboard_message|strip_tags} </td>
+ </tr>
{/foreach}
- {/if}
- {else}
- <p>There are currently no messages.</p>
+ </table>
{/if}
-
- </div>
+ {else}
+ <div class="glm-info-message">
+ <div class="text-center">
+ <h3>You're all caught up!</h3>
+ </div>
+ </div>
+ {/if}
</div>
+
+{* Grid End *}
+{$ui = [
+ 'noFoundationInit' => true
+]}
+{include file="ui/f6/grid-end.html"}
+
+{include file='footer.html'}