From: Chuck Scott Date: Tue, 23 Oct 2018 20:24:08 +0000 (-0400) Subject: Preliminary final version for first production release of usage stats capabilities. X-Git-Tag: v2.0.0~7 X-Git-Url: http://cvs2.gaslightmedia.com/gitweb/?a=commitdiff_plain;h=fa8a98a2c7587d2070dc982a3159d31ee9aecc6d;p=WP-Plugins%2Fglm-serverstats.git Preliminary final version for first production release of usage stats capabilities. --- diff --git a/.gitignore b/.gitignore index 0658ee7..c31f365 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ # Don't save smarty cache directories or files misc/smarty/** .project - +.gitignore +.buildpath +.settings diff --git a/.settings/org.eclipse.php.core.prefs b/.settings/org.eclipse.php.core.prefs new file mode 100644 index 0000000..6f2a8be --- /dev/null +++ b/.settings/org.eclipse.php.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +include_path=1;/media/server16/dev.gaslightmedia.com/wp-includes diff --git a/activate.php b/activate.php old mode 100644 new mode 100755 index 4e3351d..ca7338b --- a/activate.php +++ b/activate.php @@ -46,6 +46,30 @@ class glmServerStatsPluginActivate die(); } + // If no cron schedue is set, add it now to start at 30 min after the hour during the next hour. + $cronTimestamp = wp_next_scheduled( 'glm_serverstats_cron' ); + trigger_error("Next Scheduled = $cronTimestamp

",E_USER_NOTICE); + + if (!$cronTimestamp) { + + // Create a random time during the day that's not in the first and last 30 minutes. + $minutes = random_int(30, 1310); + $hour = intval($minutes/60); + $min = $minutes - ($hour*60); + + // Build start time to use the above time starting on the first of next month + $startTime = mktime($hour, $min, 0, date('m')+1, 1, date('Y')); + + trigger_error('No Cron Set: Scheduling glm_cron to start @ '.date('r', $startTime), E_USER_NOTICE); + + // Schedule glm_serverstats_cron to run monthly at that time + wp_schedule_event( $startTime, 'monthly', 'glm_serverstats_cron' ); + + } + + } + + } diff --git a/classes/serverBandwidthSupport.php b/classes/serverBandwidthSupport.php old mode 100644 new mode 100755 index ae3dd0e..53012f7 --- a/classes/serverBandwidthSupport.php +++ b/classes/serverBandwidthSupport.php @@ -30,12 +30,61 @@ class glmServerStatsBandwidthSupport */ public $bwdb = false; /** - * Web site ID + * Default Website * - * @var $siteId + * @var $website + * @access public + */ + public $website = false; + /** + * Default Website ID + * + * @var $siteiId * @access public */ public $siteId = false; + /** + * Target Traffic + * + * @var $target + * @access public + */ + public $target = false; + /** + * Target Disk Use + * + * @var $disk_target + * @access public + */ + public $disk_target = false; + /** + * GLM Contact E-Mail + * + * @var $glm_contact + * @access public + */ + public $glm_contact = false; + /** + * Customer Contact E-Mail + * + * @var $cust_contact + * @access public + */ + public $cust_contact = false; + /** + * Connected to Database + * + * @var $connected + * @access public + */ + public $connected = false; + /** + * Connect error + * + * @var $connectError + * @access public + */ + public $connectError = false; /** * Sort full list by * @@ -46,45 +95,91 @@ class glmServerStatsBandwidthSupport public function __construct() { + } /* - * Connect to desired database or trigger error if unable to connect. + * Connect to desired database * - * @param string $host Hostname of database server - * @param string $user Username for database - * @param string $pass Password for database - * @param string $database Name of database - * @param string $website Website name in database + * Gets host, user, password, and database name from a WP option + * that was saved by the configure page. * * @return string Error message. If blank, then no error. */ - public function bandwidthDataConnect($host, $user, $pass, $database, $website) + public function bandwidthDataConnect() { + $this->connected = false; + // Initialize MySQLi $this->bwdb = mysqli_init(); // Set a short timeout $this->bwdb->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5); + // Get current bandwidth configuration + $config = get_option(GLM_SERVERSTATS_PLUGIN_CONFIG_OPTION); + + if ($config === false) { + $this->connectError = 'GLM Bandwidth not configured.'; + return false; + } + // Connect to MySQL - $this->bwdb->real_connect($host, $user, $pass, $database); + $res = $this->bwdb->real_connect( + $config['db_host'], + $config['db_user'], + $config['db_pass'], + $config['db_name'] + ); // If there was an error connecting - if ($this->bwdb->connect_errno) { - return mysqli_connect_error(); + if (!$res) { + $this->connectError = mysqli_connect_error(); + } else { + $this->connected = true; + + // Get Website Settings + $settings = $this->bandwidthGetWebsiteSettingsFromName($config['website']); + + // Save them in class parameters + $this->website = $config['website']; + $this->siteId = $settings['websitepk']; + $this->target = $settings['target']; + $this->disk_target = $settings['disk_target']; + $this->glm_contact = $settings['glm_contact']; + $this->cust_contact = $settings['cust_contact']; + } - // Get index for this site (site ID) - $this->bandwidthGetWebsiteID($website); + return $this->connected; - if (!$this->siteId) { - return "Website Name not found: ".$website; - } + } - return ''; + /* + * Get Web site ID from Web site name. + * + * The Website ID is the index used to find bandwidth data for a + * particular Web site + */ + public function bandwidthGetWebsiteSettingsFromName($name) + { + + $sql = " + SELECT * + FROM website + WHERE name = '$name' + ;"; + $websiteResult = $this->bwdb->query($sql); + if (!$websiteResult) { + trigger_error("Get website settings failed: " . mysqli_error($bwdb) ); + } + $website = mysqli_fetch_assoc($websiteResult); + if (!$website){ + trigger_error("Website '$name' not found."); + } + return $website; } /* @@ -93,7 +188,7 @@ class glmServerStatsBandwidthSupport * The Website ID is the index used to find bandwidth data for a * particular Web site */ - public function bandwidthGetWebsiteID($website) + public function bandwidthGetWebsiteID($website, $showUsage = false) { // Get Website ID @@ -115,6 +210,89 @@ class glmServerStatsBandwidthSupport return $this->siteId; } + /* + * Get list of sites in bandwidth database + * + * @return array Array of Websites + * + * Restults are ordered by name of the Website with any + * site names that are only an IP address listed at the end of the array. + * + * array( + * 'websitepk' => ID of record, + * 'name' => Hostname of site, + * 'active' => Active flag, + * 'target' => Target Bandwidth consumption / Month in MB + * ) + * + * Or false if no data or failure. + * + */ + public function bandwidthGetSites() + { + + // Check for good database connection + if ($this->bwdb == false) { + return false; + } + + // Get list of Websites + $sql = " + SELECT * + FROM website + ORDER BY (name +0) ASC ,name ASC + ;"; + $result = $this->bwdb->query($sql); + + if (!$result) { + return false; + } + + $sites = array(); + while ($row = $result->fetch_assoc()) { + $sites[] = $row; + } + + $result->close(); + + return $sites; + } + + + /* + * Get bandwidth stats for the Last Month + */ + public function bandwidthLastMonthAllSites($sortBy = 'target_percent DESC') + { + $stats = array(); + + // Get stats for last month in Gigabytes + $firstDayOfMonth = date('Y-m-01', strtotime(date('Y-m-01').' -1 month')); + $lastDayOfMonth = date('Y-m-t', strtotime($firstDayOfMonth)); + $sql = " + SELECT R.websitefk as id, + W.name as name, + W.target, + W.disk_target, + COALESCE ( SUM(R.bytesin)/1000000000, 0 ) as data_in, + COALESCE ( SUM(R.bytesout)/1000000000, 0 ) as data_out, + COALESCE ( SUM(total)/1000000000, 0 ) as data_total, + (COALESCE ( SUM(total)/1000000000, 0 ) / W.target) * 100 as target_percent + FROM rollup R, website W + WHERE W.websitepk = R.websitefk + AND date BETWEEN '$firstDayOfMonth' AND '$lastDayOfMonth' + GROUP BY R.websitefk + ORDER BY $sortBy + "; + $lastMonthStats = $this->bwdb->query($sql); + $lastMonthStats->data_seek(0); + while ($row = $lastMonthStats->fetch_assoc()) { + $stats[$row['id']] = $row; + } + + return $stats; + } + /* * Get bandwidth stats for the current day, and month for all sites */ @@ -133,26 +311,29 @@ class glmServerStatsBandwidthSupport if ($this->bwdb == false) { return false; } - - // Get stats so far for today in Megabytes +//This one done + // Get stats for yesterday in Megabytes for traffic and Gigabytes for Storage + $yesterday = date('Y-m-d 0:0:0.0', strtotime(date('Y-m-d')." - 1day")); $today = date('Y-m-d 0:0:0.0'); - $tomorrow = date('Y-m-d 0:0:0.0', strtotime(date('Y-m-d')." + 1day")); $sql = " SELECT B.websitefk as id, W.name as name, - COALESCE ( SUM(B.bytesin)/1000000, 0 ) as data_in, - COALESCE ( SUM(B.bytesout)/1000000, 0 ) as data_out, - COALESCE ( SUM(B.total)/1000000, 0 ) as data_total - FROM bytes B, website W - WHERE W.websitepk = B.websitefk - AND time BETWEEN '$today' AND '$tomorrow' + COALESCE ( SUM(B.bytesin)/1000000, 0 ) as traffic_in, + COALESCE ( SUM(B.bytesout)/1000000, 0 ) as traffic_out, + COALESCE ( SUM(B.total)/1000000, 0 ) as traffic_total, + COALESCE ( max(B.total)/1000000, 0 ) as storage_total + FROM bytes B, rollup R, website W + WHERE B.websitefk = W.websitepk + AND R.websitefk = W.websitepk + AND B.time BETWEEN '$yesterday' AND '$today' + AND R.date = '$yesterday' GROUP BY B.websitefk ORDER BY W.name ;"; - $todayStats = $this->bwdb->query($sql); - $todayStats->data_seek(0); - while ($row = $todayStats->fetch_assoc()) { - $stats[$row['id']]['today'] = $row; + $yesterdayStats = $this->bwdb->query($sql); + $yesterdayStats->data_seek(0); + while ($row = $yesterdayStats->fetch_assoc()) { + $stats[$row['id']]['yesterday'] = $row; } // Get stats for this month in Gigabytes @@ -252,6 +433,7 @@ class glmServerStatsBandwidthSupport */ public function bandwidthGetStats() { + $stats = array(); // Check for good database connection @@ -260,19 +442,22 @@ class glmServerStatsBandwidthSupport } // Get stats so far for today in Megabytes + $yesterday = date('Y-m-d 0:0:0.0', strtotime(date('Y-m-d')." - 1day")); $today = date('Y-m-d 0:0:0.0'); - $tomorrow = date('Y-m-d 0:0:0.0', strtotime(date('Y-m-d')." + 1day")); $sql = " SELECT - COALESCE ( SUM(bytesin)/1000000, 0 ) as data_in, - COALESCE ( SUM(bytesout)/1000000, 0 ) as data_out, - COALESCE ( SUM(total)/1000000, 0 ) as data_total - FROM bytes - WHERE websitefk = ".$this->siteId." - AND time BETWEEN '$today' AND '$tomorrow' + COALESCE ( SUM(B.bytesin)/1000000, 0 ) as data_in, + COALESCE ( SUM(B.bytesout)/1000000, 0 ) as data_out, + COALESCE ( SUM(B.total)/1000000, 0 ) as data_total, + COALESCE ( MAX(R.diskusage)/1000000, 0 ) as storage + FROM bytes B, rollup R + WHERE B.websitefk = ".$this->siteId." + AND R.websitefk = ".$this->siteId." + AND B.time BETWEEN '$yesterday' AND '$today' + AND R.date = '$yesterday' ;"; $todayStats = $this->bwdb->query($sql); - $stats['today'] = $todayStats->fetch_array(MYSQLI_ASSOC); + $stats['yesterday'] = $todayStats->fetch_array(MYSQLI_ASSOC); // Get stats for this month in Gigabytes $firstDayOfMonth = date('Y-m-01'); @@ -281,7 +466,8 @@ class glmServerStatsBandwidthSupport SELECT COALESCE ( SUM(bytesin)/1000000000, 0 ) as data_in, COALESCE ( SUM(bytesout)/1000000000, 0 ) as data_out, - COALESCE ( SUM(total)/1000000000, 0 ) as data_total + COALESCE ( SUM(total)/1000000000, 0 ) as data_total, + COALESCE ( MAX(diskusage)/1000000, 0 ) as storage FROM rollup WHERE websitefk = ".$this->siteId." AND date BETWEEN '$firstDayOfMonth' AND '$lastDayOfMonth' @@ -296,7 +482,8 @@ class glmServerStatsBandwidthSupport SELECT COALESCE ( SUM(bytesin)/1000000000, 0 ) as data_in, COALESCE ( SUM(bytesout)/1000000000, 0 ) as data_out, - COALESCE ( SUM(total)/1000000000, 0 ) as data_total + COALESCE ( SUM(total)/1000000000, 0 ) as data_total, + COALESCE ( max(diskusage)/1000000000, 0 ) as storage FROM rollup WHERE websitefk = ".$this->siteId." AND date BETWEEN '$firstDayOfMonth' AND '$lastDayOfMonth' @@ -329,10 +516,10 @@ class glmServerStatsBandwidthSupport // Produce data for specified intervals switch ($graphType) { - case 'twoDay': + case 'oneDay': // Get data for today in Megabytes (10 min intervals) - $startOfYesterday = date('Y-m-d 0:0:0', strtotime($refDate.' - 1day')); + $startOfYesterday = date('Y-m-d 00:10:00', strtotime($refDate)); $endOfToday = date('Y-m-d 23:59:59', $refDateTime); $bandwidth['start'] = $startOfYesterday; $bandwidth['end'] = $endOfToday; @@ -459,38 +646,59 @@ class glmServerStatsBandwidthSupport break; - default: + case 'twoYearStorage': - die("Graph Type not specified or valid."); - break; + // Get stats for this year and last year in Gigabytes + $firstMonth = date('Y-01-01', strtotime($refDate.' -1 year')); + $lastMonth = date('Y-12-31', $refDateTime); + $bandwidth['start'] = $firstMonth; + $bandwidth['end'] = $lastMonth; + $sql = " + SELECT date as time, + COALESCE ( MAX(diskusage)/1000000, 0 ) as storage + FROM rollup + WHERE websitefk = $siteId + AND date BETWEEN '$firstMonth' AND '$lastMonth' + GROUP BY YEAR(date), MONTH(date) + ORDER BY date ASC + "; - } + $twoYearStorageData = $this->bwdb->query($sql); + $twoYearStorageData->data_seek(0); + while ($row = $twoYearStorageData->fetch_assoc()) { + $time = date('Y-m', strtotime($row['time'])); + $bandwidth['disk_space'][$time] = $row['storage']; + } - return $bandwidth; + // Also get the target disk space consumed + $sql = " + SELECT * + FROM website + WHERE websitepk = $siteId + ;"; + $targetRes = $this->bwdb->query($sql); + $target = false; + $siteName = ''; - } + if ($targetRes) { + $targetData = mysqli_fetch_assoc($targetRes); + $diskTarget = $targetData['disk_target']; + $siteName = $targetData['name']; + } - /* - * Store target monthly (billed) bandwidth in "target" in "website" table. - */ - public function bandwidthSetTarget($website, $target) - { + $bandwidth['disk_target'] = $diskTarget; + $bandwidth['site_name'] = $siteName; - // Get the Website ID for the supplied website name - $websiteId = $this->bandwidthGetWebsiteID($website); + break; - // Make sure both Website ID and Target are integers - $target = intval( $target - 0 ); + default: - // Write target value to specified Website record - $sql = " - UPDATE website - SET target = $target - WHERE websitepk = $websiteId - ;"; - $this->bwdb->query($sql); + die("Graph Type not specified or valid."); + break; - return; + } + + return $bandwidth; } @@ -499,11 +707,11 @@ class glmServerStatsBandwidthSupport * * @return array Array of configuration data for this plugin */ - public function initConfig () + public function getConfig() { // Check if configuration fields have been initialized. - $config = get_option('glmServerStatsConfigData'); + $config = get_option(GLM_SERVERSTATS_PLUGIN_CONFIG_OPTION); // If we have a stored config, return that if ($config) { @@ -512,70 +720,56 @@ class glmServerStatsBandwidthSupport // We don't have a config option, so create a default one. $config = array( - 'active' => true, - 'db_name' => 'bandwidth', - 'db_host' => 'bandwidth.gaslightmedia.com', - 'db_user' => 'bandwidthRO', - 'db_pass' => ',Wv4W*~^bL_vF3F4PbGsS', - 'website' => 'www.gaslightmedia.com', - 'target' => '10000' + 'active' => true, + 'db_name' => 'bandwidth', + 'db_host' => 'bandwidth.gaslightmedia.com', + 'db_user' => 'bandwidthRO', + 'db_pass' => ',Wv4W*~^bL_vF3F4PbGsS', + 'website' => 'www.gaslightmedia.com' ); - add_option('glmServerStatsConfigData', $config); + add_option(GLM_SERVERSTATS_PLUGIN_CONFIG_OPTION, $config); return $config; + } /* - * Check if the target bandwidth needs to be updated - * - * This can happen in there's another plug-in also managing target - * bandwidth for the selected site. + * Get stats and check if the target traffic has been exceeded * - * @param $config array Array containing access configuration + * @return array Stats array plus trafficDiff sub array */ - public function checkTargetBandwidth($config) + public function getStatsAndCheckTargetExceeded() { - // Try to connect to the bandwidth database - $res = $this->bandwidthDataConnect( - $config['db_host'], - $config['db_user'], - $config['db_pass'], - $config['db_name'], - $config['website'] - ); - - // If we can't connect, then nothing to update - if ($res != '') { - return $config; - } - - // Try to get a stored bandwidth target - $sql = " - SELECT target - FROM website - WHERE websitepk = $this->siteId - ;"; - $targetRes = $this->bwdb->query($sql); - if ($targetRes) { - - // We have a result, so get the target value - $targetData = mysqli_fetch_assoc($targetRes); - if ($targetData['target']) { - - // We have a target value so make sure that's in the option - $target = $targetData['target']; - $config['target'] = $targetData['target']; + $stats = $this->bandwidthGetStats(); - update_option('glmServerStatsConfigData', $config); + // Compare the taget in Megabytes to the acutal traffic in Gigabytes + $diff = ($stats['lastMonth']['data_total']) - $this->target; + $percent = ($stats['lastMonth']['data_total'] / $this->target) * 100; + $stats['trafficDiff'] = [ + 'target' => $this->target, + 'lastMonth' => $stats['lastMonth']['data_total'], + 'traffic' => $diff, + 'percent' => $percent, + 'exceeded' => $diff > 0 + ]; - } - } - - return $config; + return $stats; } + /* + * Check if user has "Provider" permissions. + * + * Provider permissions are required to make any changes to the target and contact settings for a Website. + * + * To have "Provider" permissions, this plugin must be installed on a specific development or production site + * and be able to connect to the server usage statistics database. + */ + public function isProvider() + { + return ($this->connected && (strpos(GLM_SERVERSTATS_SITE_BASE_URL, '192.168.44.80') !== false || strpos(GLM_SERVERSTATS_SITE_BASE_URL, 'www.gaslightmedia.com') !== false)); + } } diff --git a/deactivate.php b/deactivate.php old mode 100644 new mode 100755 index e73d494..93f26e7 --- a/deactivate.php +++ b/deactivate.php @@ -34,6 +34,21 @@ class glmServerStatsPluginDeactivate public function __construct() { + // Make sure the current user has this capability + if (! current_user_can('activate_plugins')) { + die(); + } + + // Delete the cron + $cronTimestamp = wp_next_scheduled( 'glm_serverstats_cron' ); + if ($cronTimestamp) { + + trigger_error("GLM Usage Plugin Deactivating: Unscheduling Cron",E_USER_NOTICE); + + wp_unschedule_event($cronTimestamp, 'glm_serverstats_cron'); + + } + } } diff --git a/defines.php b/defines.php old mode 100644 new mode 100755 index 98175c6..2d14a4d --- a/defines.php +++ b/defines.php @@ -12,7 +12,7 @@ if (!defined('ABSPATH')) { } define('GLM_SERVERSTATS_SITE_TITLE', get_bloginfo( 'name' )); -define('GLM_SERVERSTATS_PLUGIN_NAME', 'Gaslight Media ServerStats (serverstats)'); +define('GLM_SERVERSTATS_PLUGIN_NAME', 'Gaslight Media Server Data Usage'); 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'); @@ -74,3 +74,6 @@ define('GLM_SERVERSTATS_PLUGIN_VIEW_PATH', GLM_SERVERSTATS_PLUGIN_PATH.'/views') // Update Server define('GLM_SERVERSTATS_PLUGIN_UPDATE_SERVER', 'http://www.gaslightmedia.com/update_server'); + +// Other +define('GLM_SERVERSTATS_PLUGIN_CONFIG_OPTION', 'glmServerStatsConfigData'); \ No newline at end of file diff --git a/index.php b/index.php old mode 100644 new mode 100755 index 2972732..9399b4f --- a/index.php +++ b/index.php @@ -1,8 +1,8 @@ bandwidthDataConnect(); + + // Use default website unless another is specified by an admin user. + $websiteIn = filter_input( INPUT_GET, 'website', FILTER_SANITIZE_STRING); + if (current_user_can('administrator') && $websiteIn) { + $this->website = trim($websiteIn); + $this->siteId = $this->bandwidthGetWebsiteID($this->website); + } + + } /* @@ -50,61 +62,90 @@ class adminServerStats extends glmServerStatsBandwidthSupport { $haveStats = false; - $connectError = ''; $thisDate = false; $thisDateTime = false; $thisMonth = false; $thisMonthTime = false; $websiteId = false; + $websites = false; + + // Check for a selected site or use website in config + $config = $this->getConfig(); + $selectedSite = filter_input(INPUT_GET, 'selected_site', FILTER_SANITIZE_STRING); + $selectedSiteId = filter_input(INPUT_GET, 'site_id', FILTER_SANITIZE_INT); + if (!$selectedSite) { + $selectedSite = $config['website']; + } + + $this->siteId = $this->bandwidthGetWebsiteID($selectedSite); - // Get current bandwidth configuration - $config = get_option('glmServerStatsConfigData'); + if ($this->connected) { - if ($config != false) { + // If user is an admin, then get a list of Websites with Bandwidth Stats + if ($this->isProvider()) { - // Connect to the bandwidth database - $err = $this->bandwidthDataConnect( - $config['db_host'], - $config['db_user'], - $config['db_pass'], - $config['db_name'], - $config['website'] - ); + // Get sort order + switch ($_REQUEST['site_sort']) { + case 'site_name': + $sortBy = 'name'; + $site_sort = 'site_name'; + break; - // Check for connection error - if ($err != '') { - $connectError = $err; - } else { + case 'data_total': + $sortBy = 'data_total DESC'; + $site_sort = 'data_total'; + break; - // Get the current bandwidth stats - $stats = $this->bandwidthGetStats(); + default: + $sortBy = 'target_percent DESC'; + $site_sort = 'target_percent'; + break; + } + + // Get list of sites in the bandwidth database + $websites = $this->bandwidthLastMonthAllSites($sortBy); - if ($stats != false) { + } - // Build summary info - $thisDate = date('m/d/Y'); - $thisDateTime = strtotime($thisDate); - $thisMonth = date('m/Y'); - $thisMonthTime = strtotime(date('m/01/Y')); - $websiteId = $this->siteId; + // Get bandwidth stats for the current site + $stats = $this->getStatsAndCheckTargetExceeded(); - $haveStats = true; + if ($stats != false) { - } + // Build summary info + $thisDateTime = strtotime('yesterday'); + $thisDate = date('m/d/Y', $thisDateTime); + $thisMonthTime = strtotime(date('m/01/Y')); + $thisMonth = date('m/Y'); + $websiteId = $this->siteId; + + $haveStats = true; } + } + // echo "

".print_r($websites,1)."
"; + // Compile template data $templateData = array( - 'haveStats' => $haveStats, - 'connectError' => $connectError, - 'serverStats' => $stats, - 'thisDate' => $thisDate, - 'thisDateTime' => $thisDateTime, - 'thisMonth' => $thisMonth, - 'thisMonthTime' => $thisMonthTime, - 'websiteId' => $this->siteId, + 'baseURL' => admin_url(), + 'reportDate' => date('m/d/Y'), + 'haveStats' => $haveStats, + 'connected' => $this->connected, + 'connectError' => $this->connectError, + 'serverStats' => $stats, + 'thisDate' => $thisDate, + 'thisDateTime' => $thisDateTime, + 'thisMonth' => $thisMonth, + 'thisMonthTime' => $thisMonthTime, + 'website' => $this->website, + 'websiteId' => $this->siteId, + 'target' => $this->target, + 'websites' => $websites, + 'isProvider' => $this->isProvider(), + 'site_sort' => $site_sort, + 'selectedSite' => $selectedSite ); // Return status, suggested view, and data to controller diff --git a/models/adminServerStatsConfig.php b/models/adminServerStatsConfig.php old mode 100644 new mode 100755 index aa30a33..131d363 --- a/models/adminServerStatsConfig.php +++ b/models/adminServerStatsConfig.php @@ -1,6 +1,6 @@ bandwidthDataConnect(); } /* @@ -49,65 +50,134 @@ class adminServerStatsConfig extends glmServerStatsBandwidthSupport public function model() { - $dbError = False; - $settingsUpdated = false; - $settingsUpdateError = false; + $connectError = False; + $connectionUpdated = false; + $settingsUpdated = false; + $settingsUpdateError = false; + $websites = false; + $selectedSite = false; + $settings = false; // If an update was submitted + $option = 'none'; if (isset($_REQUEST['option'])) { + $option = $_REQUEST['option']; + } + + // If this is a connection update, store that + if ($option == 'update_connection') { // Filter the input data $config = filter_input_array( INPUT_POST, - array( - 'db_name' => FILTER_SANITIZE_STRING, - 'db_host' => FILTER_SANITIZE_STRING, - 'db_user' => FILTER_SANITIZE_STRING, - 'db_pass' => FILTER_SANITIZE_STRING, - 'website' => FILTER_SANITIZE_STRING, - 'target' => FILTER_VALIDATE_INT, - ) + array( + 'db_name' => FILTER_SANITIZE_STRING, + 'db_host' => FILTER_SANITIZE_STRING, + 'db_user' => FILTER_SANITIZE_STRING, + 'db_pass' => FILTER_SANITIZE_STRING, + 'website' => FILTER_SANITIZE_STRING + ) ); - $config['active'] = (isset($_REQUEST['active']) && $_REQUEST['active'] == 'on'); // Update the WordPress option where we store the configuration for this plugin - update_option('glmServerStatsConfigData', $config); - - // Test database connection and warn user if not functional - $res = $this->bandwidthDataConnect( - $config['db_host'], - $config['db_user'], - $config['db_pass'], - $config['db_name'], - $config['website'] - ); + update_option(GLM_SERVERSTATS_PLUGIN_CONFIG_OPTION, $config); - // If there was an error connecting to the database - report the error - if ($res != '') { - $dbError = $res." "; - } else { - // Store Target Value in "bandwidth" table for monthly billed usage level - $this->bandwidthSetTarget($config['website'], $config['target']); - } + // Otherwise get existing connection configuration + } else { + $config = $this->getConfig(); + } - $settingsUpdated = true; + // Connect to database + $connected = $this->bandwidthDataConnect(); + + // If we can connect to the database + if ($connected) { + $websiteId = $this->siteId; + if ($option == 'update_connection') { + $connectionUpdated = true; + } + // If we can't, get the reason why } else { + $connectError = $this->connectError; + } - // Create or get configuration parameters for bandwidth stats - $config = $this->initConfig(); + // Check for a selected site or use website in config + $selectedSite = filter_input(INPUT_GET, 'selected_site', FILTER_SANITIZE_STRING); + if (!$selectedSite) { + $selectedSite = $config['website']; + } - // Check if target bandwidth needs to be updated - $config = $this->checkTargetBandwidth($config); + // If it's OK for the user to update the settings for this site + if ($this->isProvider()) { + + if ($option == 'update_site') { + + // Update the website table with certain values + $settings = filter_input_array( INPUT_POST, + array( + 'target' => FILTER_VALIDATE_FLOAT, + 'disk_target' => FILTER_VALIDATE_FLOAT, + 'glm_contact' => FILTER_VALIDATE_EMAIL, + 'cust_contact' => FILTER_VALIDATE_EMAIL + ) + ); + $sql = " + UPDATE website + SET target = ".$settings['target'].", + disk_target = ".$settings['disk_target'].", + glm_contact = '".$settings['glm_contact']."', + cust_contact = '".$settings['cust_contact']."' + WHERE name = '$selectedSite' + "; + $this->bwdb->query($sql); + + // Update our class parameters + $this->target = $settings['target']; + $this->disk_target = $settings['disk_target']; + $this->glm_contact = $settings['glm_contact']; + $this->cust_contact = $settings['glm_contact']; - } + } + + // Get sort order + switch ($_REQUEST['site_sort']) { + case 'site_name': + $sortBy = 'name'; + $site_sort = 'site_name'; + break; + + case 'data_total': + $sortBy = 'data_total DESC'; + $site_sort = 'data_total'; + break; + + default: + $sortBy = 'target_percent DESC'; + $site_sort = 'target_percent'; + break; + } + + // Get list of sites in the bandwidth database + $websites = $this->bandwidthLastMonthAllSites($sortBy); + + // Get the settings for the currently selected site + $settings = $this->bandwidthGetWebsiteSettingsFromName($selectedSite); + + } // if OK to update site settings // Compile template data $templateData = array_merge( $config, array( - 'dbError' => $dbError, + 'isProvider' => $this->isProvider(), + 'connectionUpdated' => $connectionUpdated, + 'connectError' => $connectError, 'settingsUpdated' => $settingsUpdated, - 'settingsUpdateError' => $settingsUpdateError + 'settingsUpdateError' => $settingsUpdateError, + 'site_sort' => $site_sort, + 'websites' => $websites, + 'selectedSite' => $selectedSite, + 'settings' => $settings ) ); diff --git a/models/ajaxServerBandwidthGraphs.php b/models/ajaxServerBandwidthGraphs.php old mode 100644 new mode 100755 index 51d4afd..43f1caa --- a/models/ajaxServerBandwidthGraphs.php +++ b/models/ajaxServerBandwidthGraphs.php @@ -1,6 +1,6 @@ bandwidthDataConnect(); - // Connect to the bandwidth database - $this->bandwidthDataConnect( - $config['db_host'], - $config['db_user'], - $config['db_pass'], - $config['db_name'], - $config['website'] - ); - - $this->target = $config['target']; + // Use default website unless another is specified by an admin user. + $websiteIn = filter_input( INPUT_GET, 'website', FILTER_SANITIZE_STRING); + if (current_user_can('administrator') && $websiteIn) { + $this->website = trim($websiteIn); + $this->siteId = $this->bandwidthGetWebsiteID($this->website); + } } @@ -65,7 +68,7 @@ class ajaxServerBandwidthGraphs extends glmServerStatsBandwidthSupport * * This model action does not return, it simply does it's work then calls die(); * - * @param $actionData + * @param $actionDataalert('{$thisUrl}?page={$thisPage}&website=' + site); * * Echos JSON string as response and does not return */ @@ -74,16 +77,6 @@ class ajaxServerBandwidthGraphs extends glmServerStatsBandwidthSupport $graphType = $_REQUEST['graphType']; - $siteId = false; - if (isset($_REQUEST['siteId'])) { - $siteId = $_REQUEST['siteId']-0; - } - - $noTarget = false; - if (isset($_REQUEST['noTarget'])) { - $noTarget = true; - } - // Set reference Date $refDate = date('m/d/Y'); if (isset($_REQUEST['refDate'])) { @@ -92,27 +85,33 @@ class ajaxServerBandwidthGraphs extends glmServerStatsBandwidthSupport $interval = 1; $useTarget = false; + $useDiskTarget = false; switch($graphType) { - case 'twoDay': - $interval = 8; - $title = 'Server bandwidth usage by 10 minute Intervals in Megabytes'; + case 'oneDay': + $interval = 3; + $title = '5 Minute Traffic in Megabytes'; break; case 'twoMonth': $interval = 2; - $title = 'Server bandwidth usage by 1 day intervals in Gigabytes'; + $title = 'Daily Traffic in Gigabytes'; break; case 'twoYear': $interval = 1; $useTarget = true; - $title = 'Server bandwidth usage by 1 month Intervals in Gigabytes'; + $title = 'Monthly Traffic in Gigabytes'; + break; + case 'twoYearStorage': + $interval = 1; + $useDiskTarget = true; + $title = 'Monthly Disk Space Used in Gigabytes'; break; default: - die("Invalid bandwidth graph type: $graphType"); + die("Invalid usage graph type: $graphType"); break; } // Get bandwidth data for today - $data = $this->bandwidthGetGraphData($graphType, $siteId, $refDate); + $data = $this->bandwidthGetGraphData($graphType, $this->siteId, $refDate); // Load PHPGraphLib require_once GLM_SERVERSTATS_PLUGIN_LIB_PATH.'/phpgraphlib-master/phpgraphlib.php'; @@ -124,10 +123,11 @@ class ajaxServerBandwidthGraphs extends glmServerStatsBandwidthSupport $graph->setMinMaxY(1); // Set minimum top value to Y axis $graph->setXValuesInterval($interval); $graph->setXValuesHorizontal(false); - $graph->setLineColor("blue", "red", "green"); + $graph->setLineColor("blue", "red", "green", "gray"); $graph->setDataPointSize(4); $graph->setTextColor("black"); // $graph->setBackgroundColor('249,249,249'); + $graph->setGrid(true); $graph->setLine(true); $graph->setBars(false); $graph->setDataPoints(false); @@ -136,18 +136,22 @@ class ajaxServerBandwidthGraphs extends glmServerStatsBandwidthSupport $graph->addData($data['data_in']); $graph->addData($data['data_out']); - // Check if we received a target value with our graph data - if ($useTarget && isset($data['target']) && $data['target'] > 0) { - $this->target = $data['target']; - $noTarget = false; + if ($graphType != 'oneDay') { + $graph->addData($data['disk_space']); } - // Set target bandwidth line. Must be set after data sets - if ($useTarget && !$noTarget) { - $graph->setGoalLine(($this->target/1000), "black", "dashed"); + // Check if we received a target value with our graph data and if so display it + $targetValue = 0; + if ($useTarget && $this->target) { + $graph->setGoalLine(($this->target), "purple", "dashed"); + $title .= ' - Target: '.$this->target.' Gigabytes'; + } + if ($useDiskTarget && $this->disk_target) { + $graph->setGoalLine(($this->disk_target), "purple", "dashed"); + $title .= ' - Target: '.$this->disk_target.' Gigabytes'; } - $graph->setTitle(' Site: '.$data['site_name'].' '.$title.' From '.substr($data['start'],0,10).' Through '.substr($data['end'],0,10)); + $graph->setTitle($data['site_name'].' '.$title.' From '.substr($data['start'],0,10).' Through '.substr($data['end'],0,10)); $graph->createGraph(); // Ajax processing ends here diff --git a/models/ajaxServerUsageTargetCheck.php b/models/ajaxServerUsageTargetCheck.php new file mode 100755 index 0000000..5bdc424 --- /dev/null +++ b/models/ajaxServerUsageTargetCheck.php @@ -0,0 +1,184 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version 1.0.0 + */ + +// Load Management Server Stats data abstract +require_once GLM_SERVERSTATS_PLUGIN_CLASS_PATH.'/serverBandwidthSupport.php'; + +/* + * Server Stats Bandwidth Graphs Class + */ +class ajaxServerUsageTargetCheck extends glmServerStatsBandwidthSupport +{ + + /** + * Target Monthly Bandwidth + * + * @var $target + * @access public + */ + public $target; + + /* + * Constructor + * + * This contructor sets up this model. At this time that only includes + * storing away the WordPress data object. + * + * @return object Class object + * + */ + public function __construct() + { + + // Connect to Bandwidth Database selected in the Configure page + $this->bandwidthDataConnect(); + + // Use default website unless another is specified by an admin user. + $websiteIn = filter_input( INPUT_GET, 'website', FILTER_SANITIZE_STRING); + if (current_user_can('administrator') && $websiteIn) { + $this->website = trim($websiteIn); + $this->siteId = $this->bandwidthGetWebsiteID($this->website); + } + + } + + /* + * Perform Model Action + * + * This modelAction takes an AJAX request to produce a bandwidth graph and + * output it. + * + * This model action does not return, it simply does it's work then calls die(); + * + * @param $actionDataalert('{$thisUrl}?page={$thisPage}&website=' + site); + * + * Echos JSON string as response and does not return + */ + public function model() + { + + trigger_error('GLM Usage: Cron triggered Usage Target Check', E_USER_NOTICE); + + $stats = $this->getStatsAndCheckTargetExceeded(); + + // If traffic had exceeded target + if ($stats['trafficDiff']['exceeded']) { + + $month = date('M Y', strtotime('now -1 month')); + + // If GLM contact provided + if (trim($this->glm_contact) != '') { + + $mesg = ' +

Gaslight Media:

+

A Website has exceeded the agreed target traffic for '.$month.'.

+ + + + + +
Website:'.$this->website.'
Target:'.sprintf('%.3f', $this->target).' Gigabytes
Over Target:'.sprintf('%.3f', $stats['trafficDiff']['traffic']).' Gigabytes
Percent Over:'.sprintf('%.0f', $stats['trafficDiff']['percent']).'%
+

Sincerely,

+

Gaslight Media

+ '; + + $this->sendHtmlEmail($this->glm_contact, 'info@gaslightmedia.com', 'Gaslight Media Server Usage Report', $mesg); + } + + // If customer contact provided + if (trim($this->cust_contact) != '') { + + $mesg = ' +

Dear Gaslight Media Website Owner:

+

Congradulations, your Website has exceeded the traffic target for '.$month.'.

+ + + + + +
Website:'.$this->website.'
Target:'.sprintf('%.3f', $this->target).' Gigabytes
Over Target:'.sprintf('%.3f', $stats['trafficDiff']['traffic']).' Gigabytes
Percent Over:'.sprintf('%.0f', $stats['trafficDiff']['percent']).'%
+

+ This is good because it means your Website is getting more traffic! +

+

+ Unlike other hosting providers, Gaslight Media doesn\'t automatically increase your monthly hosting fees simply because your Website exceeded the + agreed-upon service level for one month. Instead, we see this as an oportunity to look at your current and future needs first. If + you\'re likely to continue exceeding this traffic target, we can talk about a change in your hosting ageement to make sure you continue to + serve your Website users effectively. +

+

+ Please contact us if you have any questions about this or other concerns. Otherwise, we\'ll contact you soon to talk about the + good performance of your Website and discuss plans for the future. +

+

Sincerely,

+

+ Gaslight Media
+ 120 E. Lake Street
+ Petoskey, MI 49770
+ 231-487-0692 +

+ '; + + $this->sendHtmlEmail($this->cust_contact, 'info@gaslightmedia.com', 'Gaslight Media Server Usage Report', $mesg); + } + + } + + // Ajax processing ends here + wp_die(); + + } + + /** + * sendHtmlEmail + * + * Create html email and send using wp_mail. + * + * @param string $to To email address + * @param string $from From E-Mail address + * @param string $subject Subject line for the email + * @param string $htmlMessage Html message for the email + * + * @access public + * @return void + */ + public function sendHtmlEmail( $to, $from, $subject, $msg ) + { + + if (GLM_SERVERSTATS_PLUGIN_HOST == 'DEVELOPMENT') { + echo " +

Server Usage E-Mail - Development Mode

+ From: $from
+ To: $to
+ Reply-To: $from
+ Subject: $subject
+ + $msg +
+

 

+ "; + return; + } + + $header = [ + 'Content-type: text/html;charset=utf-8', + "From: $from", + "Reply-To: $from" + ]; + + wp_mail( $to, $subject, $msg, $header ); + + } + +} diff --git a/setup/adminMenus.php b/setup/adminMenus.php old mode 100644 new mode 100755 index 439547f..4fd2a7e --- a/setup/adminMenus.php +++ b/setup/adminMenus.php @@ -1,6 +1,6 @@ - Server Bandwidth - -{if $haveStats} -
-

- Server Bandwidth is the amount of data sent and received by this Web site. -

- Incoming data (red) is related to requests to display a page on the site and any - images or files uploaded, including in your administration area. -

- Outgoing data (green) is related to the pages sent to users of your site, including - all images, and files requested by the site user and all information displayed while using - your administration area. -

- Total data (blue) is the total of Incoming and Outgoing data and is the value used - to set the Target bandwidth for billing purposes. The target bandwidth is per-month - and is indicated as a dotted line on the "2 Years" graph included below. -

- Server Bandwidth is displayed below in Megabytes (Millions of bytes) and Gigabytes - (Billions of bytes). A byte is roughly equivalent to one character. -

- -
-

 

- - - - - - - - - - - -
Today: - {$serverStats.today.data_total|round:3} Megabytes
-
This Month: - {$serverStats.thisMonth.data_total|round:3} Gigabytes
-
Last Month: - {$serverStats.lastMonth.data_total|round:3} Gigabytes -
+ +{if !$connected} - -
-
-

 

- Date Selected: - - -     
Print
-
-
-


-


-


-
Color Key: Incoming, Outgoing, Total
-
-
+

Server Data Usage Unavailable

+

{$connectError}

+ + {if $isProvider} +

Please check GLM Server Usage configuration menu!

+ {else} +

Please contact your system administrator for assistance.

+ {/if} +{else} - +

+ Gaslight Media Server Usage +

+
+ + {if !$haveStats} +

This application has not been configured. Please ask Gaslight Media this for your Website.

+

Error: {$connectError}

+ {else} - + + + {/if} - }); - -{else} -

Server Bandwidth has not been configured. Please ask system administrator to configure this plugin.

-

Error: {$connectError}

{/if} + {include file='footer.html'} diff --git a/views/adminServerStatsConfig.html b/views/adminServerStatsConfig.html old mode 100644 new mode 100755 index 58d979d..a30a859 --- a/views/adminServerStatsConfig.html +++ b/views/adminServerStatsConfig.html @@ -1,64 +1,148 @@ {include file='header.html'} + +
- {if $settingsUpdated}

Settings Updated

{/if} - {if $settingsUpdateError}Settings Update Error{/if} - - {if $dbError != ''} -

Unable to test database connection!

-

Error reported: {$dbError}

- {/if} -

Server Bandwidth Statistics Configuration

+

Server Usage Statistics Configuration

- + + - - - +
+ + + + - + + +
+ {if $connectionUpdated}

Settings Updated

{/if} + +
+

Database Connection

+ {if $connectionUpdateError}
Error {$connectionUpdateError}{/if} +
Database Name: - + {if !$db_name}

Database Name not provided or invalid!

{/if}
Database Server Hostname: - +
Database Username: - +
Database Password: - +
Website Name:Default Website Name: - -
This is the name of the Website as it's listed in the server stats database. Normally does include 'www'. + +
+ This is the Website that is reported by default for this site. It needs to be identical to the name used in the usage statistics database. + If in doubt, contact Gaslight Media engineering. +
+{if $connectError} +

Unable to connect to database! Please check connection settings.

+{/if} + +
+ +{if !$connectError && $isProvider} +
+ + + + + + + + + {if $selectedSite} + + + + + - - + + + + + + + + + + {/if}

 

Site Selection (service provider only)

Select Site to Configure +

+ Sort by: + Total Traffic + Percent of Target + Site Name +

+ +

 

Settings for Selected Site (service provider only)

Monthly Target Traffic: + +
Monthly target traffic is entered in Gigabytes.
Monthly Target Bandwidth: - -
Monthly target bandwidth is entered in Megabytes without any fractions. +
Target Disk Space Used: + +
Disk Space is entered in Gigabytes.
Gaslight Media Contact E-Mail: + +
E-mail address of Gaslight Media contact who will receive over-target E-Mail. +
Customer Contact E-Mail: + +
E-mail address of customer contact who will receive over-target E-Mail. +
- + {if $selectedSite} + + {/if}
+{/if} +