Preliminary final version for first production release of usage stats capabilities.
authorChuck Scott <cscott@gaslightmedia.com>
Tue, 23 Oct 2018 20:24:08 +0000 (16:24 -0400)
committerChuck Scott <cscott@gaslightmedia.com>
Tue, 23 Oct 2018 20:24:08 +0000 (16:24 -0400)
17 files changed:
.gitignore
.settings/org.eclipse.php.core.prefs [new file with mode: 0644]
activate.php [changed mode: 0644->0755]
classes/serverBandwidthSupport.php [changed mode: 0644->0755]
deactivate.php [changed mode: 0644->0755]
defines.php [changed mode: 0644->0755]
index.php [changed mode: 0644->0755]
lib/smartyTemplateSupport.php
misc/Documentation/Plugin Overview and Documentation [new file with mode: 0755]
models/adminServerStats.php [changed mode: 0644->0755]
models/adminServerStatsConfig.php [changed mode: 0644->0755]
models/ajaxServerBandwidthGraphs.php [changed mode: 0644->0755]
models/ajaxServerUsageTargetCheck.php [new file with mode: 0755]
setup/adminMenus.php [changed mode: 0644->0755]
setup/standardTemplateParams.php
views/adminServerStats.html [changed mode: 0644->0755]
views/adminServerStatsConfig.html [changed mode: 0644->0755]

index 0658ee7..c31f365 100644 (file)
@@ -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 (file)
index 0000000..6f2a8be
--- /dev/null
@@ -0,0 +1,2 @@
+eclipse.preferences.version=1
+include_path=1;/media/server16/dev.gaslightmedia.com/wp-includes
old mode 100644 (file)
new mode 100755 (executable)
index 4e3351d..ca7338b
@@ -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<P>",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' );
+
+        }
+
+
     }
 
+
+
 }
old mode 100644 (file)
new mode 100755 (executable)
index ae3dd0e..53012f7
@@ -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));
 
+    }
 }
old mode 100644 (file)
new mode 100755 (executable)
index e73d494..93f26e7
@@ -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');
+
+        }
+
     }
 
 }
old mode 100644 (file)
new mode 100755 (executable)
index 98175c6..2d14a4d
@@ -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
old mode 100644 (file)
new mode 100755 (executable)
index 2972732..9399b4f
--- a/index.php
+++ b/index.php
@@ -1,8 +1,8 @@
 <?php
 /**
- * Plugin Name: GLM ServerStats - Stand Alone
+ * Plugin Name: GLM Bandwidth
  * Plugin URI: http://www.gaslightmedia.com/
- * Description: Gaslight Media Server Stats Display.
+ * Description: Gaslight Media Website Bandwidth Display and Reporting
  * Version: 1.1.1
  * Author: Gaslight Media
  * Author URI: http://www.gaslightmedia.com/
@@ -10,7 +10,7 @@
  */
 
 /**
- * Gaslight Media ServerStats - Stand Alone
+ * Gaslight Media - GLM Bandwidth
  * Index
  *
  * PHP version 5.5
@@ -220,3 +220,27 @@ function glmServerStatsPluginDeactivate ()
 }
 register_deactivation_hook(__FILE__, 'glmServerStatsPluginDeactivate');
 
+
+
+/*
+ * Activate cron to check for Excess Usage
+ *
+ * This cron runs once a month on the first day of the month to check is this site has
+ * exceeded the target usage.
+ *
+ * The time of the day that this runs is chosen randomly to spread the load across the day
+ * due avoid all sites running this cron at the same time. 23:30 to 00:30 is excluded.
+ */
+
+// Called by WordPress each hour on the half hour. (see activate.php)
+add_action('glm_serverstats_cron', 'do_glm_serverstats_cron');
+function do_glm_serverstats_cron() {
+
+    trigger_error('GLM Serverstats Cron Called', E_USER_NOTICE);
+
+    wp_remote_get(admin_url().'admin-ajax.php?action=glm_server_stats&glm_action=ajaxServerUsageTargetCheck');
+
+}
+
+
+
index b2811d2..e64c0f3 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 
 /**
- * Gaslight Media Server Stats - Stand Alone
+ * Gaslight Media - GLM Bandwidth
  * Smarty Templates Support Class
  *
  * PHP version 5.5
diff --git a/misc/Documentation/Plugin Overview and Documentation b/misc/Documentation/Plugin Overview and Documentation
new file mode 100755 (executable)
index 0000000..8c55d06
--- /dev/null
@@ -0,0 +1,54 @@
+Plugin Overview and Documentation
+=================================
+
+Overview
+--------
+
+Objectives
+
+Provide GLM customers with information on the data and disk usage of their Website and how that compares to the level of service selected. Notify GLM and GLM Customer when the target levels under their level of service is reached.
+
+Functional Outline
+------------------
+
+* Front-End
+    None
+* Admin
+    * Configuration
+    * Usage Report
+        * Website Selection (Administrators Only)
+        * Brief Stats
+        * Explanation of Reports
+        * Graphs
+            * Date selection
+            * Printing
+            * Yesterday: 
+                Usage graph for last full day
+            * Last and Current Month: 
+                Usage graph from beginning of the previous month to the last reported day of the current month
+            * Last and Current Year:
+                Usage graph from the beginning of the previous year to the last reported month of the current year
+            * Disk Storage:
+                Disk storage graph from the beginning of the previous year to the last reported month of the current year
+* Internal
+    * Cron
+        * Setup
+            * WP Cron schedue is setup on activation to run on the first of each month at a random time of the day
+            * Random time does not includee first or last 30 minutes of the day
+            * WordPress calls "glm_serverstats_cron" action added in /index.php file at scheduled time  
+        * Cron Tasks
+            * Actions
+                * WordPress calls 'glm_serverstats_cron' action in /index.php
+                * 'glm_serverstats_cron' action calls 'do_glm_serverstats_cron' function in /index.php
+                * 'do_glm_serverstats_cron' does wp_remote_get to URL
+                    admin_url().'admin-ajax.php?action=glm_server_stats&glm_action=ajaxServerUsageTargetCheck
+                * Class 'ajaxServerUsageTargetCheck' is instatiated and model() called
+                    * Checks if any targets are expceeded
+                    * If so, sends E-Mail to the the GLM and Customer contact E-Mail addresses set in Configuration page
+                        * Lists what has been exceeded
+                        * Provides URL to admin useage report
+        
+How-To
+------
+
+        
\ No newline at end of file
old mode 100644 (file)
new mode 100755 (executable)
index 1c69557..43c8d09
@@ -1,6 +1,6 @@
 <?php
 /**
- * Gaslight Media Server Stats - Stand Alone
+ * Gaslight Media - GLM Bandwidth
  *
  * PHP version 5.5
  *
@@ -12,7 +12,7 @@
  * @link     http://dev.gaslightmedia.com/
  */
 
-// Load Management Server Stats data abstract
+// Load Management Bandwidth data abstract
 require_once GLM_SERVERSTATS_PLUGIN_CLASS_PATH.'/serverBandwidthSupport.php';
 
 /**
@@ -37,6 +37,18 @@ class adminServerStats extends glmServerStatsBandwidthSupport
     */
     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);
+        }
+
+
     }
 
     /*
@@ -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 "<pre>".print_r($websites,1)."</pre>";
+
         // 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
old mode 100644 (file)
new mode 100755 (executable)
index aa30a33..131d363
@@ -1,6 +1,6 @@
 <?php
 /**
- * Gaslight Media Server Stats - Stand Alone
+ * Gaslight Media - GLM Bandwidth
  *
  * PHP version 5.5
  *
@@ -16,7 +16,7 @@
 require_once GLM_SERVERSTATS_PLUGIN_CLASS_PATH.'/serverBandwidthSupport.php';
 
 /**
- * GLM Server Stats Config Class
+ * GLM Bandwidth Config Class
  *
  * PHP version 5
  *
@@ -37,6 +37,7 @@ class adminServerStatsConfig extends glmServerStatsBandwidthSupport
     */
     public function __construct()
     {
+        $this->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
             )
         );
 
old mode 100644 (file)
new mode 100755 (executable)
index 51d4afd..43f1caa
@@ -1,6 +1,6 @@
 <?php
 /**
- * Gaslight Media Server Stats - Stand Alone
+ * Gaslight Media = GLM Bandwidth
  * Server Bandwidth Stats by AJAX
  *
  * PHP version 5.5
@@ -28,6 +28,13 @@ class ajaxServerBandwidthGraphs  extends glmServerStatsBandwidthSupport
      * @access public
      */
     public $target;
+    /**
+     * Disk Target
+     *
+     * @var $disk_target
+     * @access public
+     */
+    public $disk_target;
 
     /*
      * Constructor
@@ -41,19 +48,15 @@ class ajaxServerBandwidthGraphs  extends glmServerStatsBandwidthSupport
     public function __construct()
     {
 
-        // Get current bandwidth configuration
-        $config = get_option('glmServerStatsConfigData');
+        // Connect to Bandwidth Database selected in the Configure page
+        $this->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 (executable)
index 0000000..5bdc424
--- /dev/null
@@ -0,0 +1,184 @@
+<?php
+/**
+ * Gaslight Media = GLM Bandwidth
+ * Server Bandwidth Stats by AJAX
+ *
+ * PHP version 5.5
+ *
+ * @category glmWordPressPlugin
+ * @package  glmServerStats
+ * @author   Chuck Scott <cscott@gaslightmedia.com>
+ * @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 = '
+                    <p>Gaslight Media:</p>
+                    <p>A Website has exceeded the agreed target traffic for '.$month.'.</p>
+                    <table>
+                        <tr><th align="left">Website:</th><td>'.$this->website.'</td>
+                        <tr><th align="left">Target:</th><td>'.sprintf('%.3f', $this->target).' Gigabytes</td></tr>
+                        <tr><th align="left">Over Target:</th><td>'.sprintf('%.3f', $stats['trafficDiff']['traffic']).' Gigabytes</td></tr>
+                        <tr><th align="left" style="padding-right: 1em;">Percent Over:</th><td>'.sprintf('%.0f', $stats['trafficDiff']['percent']).'%</td></tr>
+                    </table>
+                    <p>Sincerely,</p>
+                    <p>Gaslight Media</p>
+                ';
+
+                $this->sendHtmlEmail($this->glm_contact, 'info@gaslightmedia.com', 'Gaslight Media Server Usage Report', $mesg);
+            }
+
+            // If customer contact provided
+            if (trim($this->cust_contact) != '') {
+
+                $mesg = '
+                    <p>Dear Gaslight Media Website Owner:</p>
+                    <p>Congradulations, your Website has exceeded the traffic target for '.$month.'.</p>
+                    <table>
+                        <tr><th align="left">Website:</th><td>'.$this->website.'</td>
+                        <tr><th align="left">Target:</th><td>'.sprintf('%.3f', $this->target).' Gigabytes</td></tr>
+                        <tr><th align="left">Over Target:</th><td>'.sprintf('%.3f', $stats['trafficDiff']['traffic']).' Gigabytes</td></tr>
+                        <tr><th align="left" style="padding-right: 1em;">Percent Over:</th><td>'.sprintf('%.0f', $stats['trafficDiff']['percent']).'%</td></tr>
+                    </table>
+                    <p>
+                        This is good because it means your Website is getting more traffic!
+                    </p>
+                    <p>
+                        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.
+                    </p>
+                    <p>
+                        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.
+                    </p>
+                    <p>Sincerely,</p>
+                    <p>
+                        Gaslight Media<br>
+                        120 E. Lake Street<br>
+                        Petoskey, MI 49770<br>
+                        231-487-0692
+                    </p>
+                ';
+
+                $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 "
+                <H2>Server Usage E-Mail - Development Mode</h2>
+                From: $from<br>
+                To: $to<br>
+                Reply-To: $from<br>
+                Subject: $subject<br>
+
+                $msg
+                <hr>
+                <p>&nbsp;</p>
+            ";
+            return;
+        }
+
+        $header = [
+            'Content-type: text/html;charset=utf-8',
+            "From: $from",
+            "Reply-To: $from"
+        ];
+
+        wp_mail( $to, $subject, $msg, $header );
+
+    }
+
+}
old mode 100644 (file)
new mode 100755 (executable)
index 439547f..4fd2a7e
@@ -1,6 +1,6 @@
 <?php
 /**
- * Gaslight Media Server Stats - Stand Alone
+ * Gaslight Media - GLM Bandwidth
  *
  * PHP version 5.5
  *
@@ -15,8 +15,8 @@
 $mainServerStatsMenuSlug = 'glm-server-stats-main-menu';
 if (current_user_can('editor') || current_user_can('administrator')) {
     add_menu_page(
-        "GLM Bandwidth",
-        'GLM Bandwidth',
+        "GLM Data Usage",
+        'GLM Data Usage',
         'edit_pages',
         $mainServerStatsMenuSlug,
         function() {
@@ -39,7 +39,7 @@ if (current_user_can('editor') || current_user_can('administrator')) {
 }
 
 // Add a sub-submeu for server Stats - For admin users only
-if (current_user_can('administrator')) {
+    if (current_user_can('administrator') && (strpos(GLM_SERVERSTATS_SITE_BASE_URL, '192.168.44.80') !== false || strpos(GLM_SERVERSTATS_SITE_BASE_URL, 'www.gaslightmedia.com') !== false)) {
     add_submenu_page(
         $mainServerStatsMenuSlug,
         'Configure',
index 76d9bb9..162319e 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * Gaslight Media Server Stats - Stand Alone
+ * Gaslight Media - GLM Bandwidth
  * Standard Template Parameters
  *
  * PHP version 5.5
old mode 100644 (file)
new mode 100755 (executable)
index e1e3a01..e789fb6
 {include file='header.html'}
 
-<h2>
-    Server Bandwidth
-</h2>   
-{if $haveStats}
-<div style="width: 800px;">
-    <p>
-        <b>Server Bandwidth</b> is the amount of data sent and received by this Web site.  
-    </p><p>
-        <b>Incoming</b> data (red) is related to requests to display a page on the site and any 
-        images or files uploaded, including in your administration area.
-    </p><p>
-        <b>Outgoing</b> 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.
-    </p><p>
-        <b>Total</b> data (blue) is the total of Incoming and Outgoing data and is the value used
-        to set the <b>Target</b> bandwidth for billing purposes. The target bandwidth is per-month
-        and is indicated as a dotted line on the "2 Years" graph included below. 
-    </p><p>
-        Server Bandwidth is displayed below in <b>Megabytes</b> (Millions of bytes) and <b>Gigabytes</b>
-        (Billions of bytes). A byte is roughly equivalent to one character.
-    </p>  
-   
-</div>
-<p>&nbsp;</p>
-<table class="glm-admin-table" style="font-size: 1.5em;">
-    <tr>
-        <th>Today: </th>
-        <td>
-            {$serverStats.today.data_total|round:3} Megabytes<br>
-        </td>
-    </tr><tr>
-        <th>This Month: </th>
-        <td>
-            {$serverStats.thisMonth.data_total|round:3} Gigabytes<br>
-        </td>
-    </tr><tr>
-        <th>Last Month: </th>
-        <td>
-            {$serverStats.lastMonth.data_total|round:3} Gigabytes
-        </td>
-    </tr>
-</table>
+    <style>
+        /* Some styles are set in the print area to make them available in the print window */
+        .pseudoPick {
+            height: 150px; 
+            padding-left: 2px; 
+            overflow-y: auto; 
+            overflow-x: hidden;
+            display: inline-block;
+            margin-top: 1em;
+            border: 1px #ddd solid;
+        }
+        .pseudoPickOption {
+            text-decoration: none;
+            
+            line-height: .2em;
+        }
+        .pseudoPickOption:hover {
+            background-color: #0568B3 !important;
+            color: white;
+        }
+    </style>
+{if !$connected}
 
-<!-- Server Bandwidth Stats -->
-<div style="width: 1100px;">
-    <center>
-        <p>&nbsp;</p>
-        Date Selected: 
-        <input type="hidden" autofocus="true">
-        <input data-id="graphDate" type="text" name="graph_date" value="{$thisDate}" class="glm-form-text-input-small glm-date-input recurrence-input" placeholder="Click to Select Date/Time" tabindex="2">
-        &nbsp;&nbsp;&nbsp;&nbsp;<div class="button button-secondary graph-print" data-areaToPrint="StatsPrintArea">Print</div>
-    </center>
-    <div id="StatsPrintArea" class="PrintArea" style="padding: 10px;">
-        <p><img id="twoDayImg" src="{$ajaxUrl}?action=glm_server_stats&glm_action=ajaxServerBandwidthGraphs&graphType=twoDay"><br></p>
-        <p><img id="twoMonthImg" src="{$ajaxUrl}?action=glm_server_stats&glm_action=ajaxServerBandwidthGraphs&graphType=twoMonth"><br></p>
-        <p><img id="twoYearImg" src="{$ajaxUrl}?action=glm_server_stats&glm_action=ajaxServerBandwidthGraphs&graphType=twoYear"><br></p>
-        <center>Color Key: <span style="color: red;">Incoming</span>, <span style="color: green;">Outgoing</span>, <span style="color: blue;">Total</span></center>
-    </div>
-</div>
+    <h1>Server Data Usage Unavailable</h1>
+    <h4>{$connectError}</h4>
+    
+  {if $isProvider}
+    <p>Please check GLM Server Usage configuration menu!</p>
+  {else}
+    <p>Please contact your system administrator for assistance.</p>
+  {/if}
+{else}
 
-<script src="{$jsUrl}/PrintArea/jquery.PrintArea.js" type="text/JavaScript" language="javascript"></script>
+    <h1>
+        Gaslight Media Server Usage    
+    </h1>
+    <hr>
+    
+  {if !$haveStats}
+    <h3 class="glm-error">This application has not been configured. Please ask Gaslight Media this for your Website.</h3>
+    <p><b>Error:</b> {$connectError}</p>
+  {else}    
 
-<script type="text/javascript">
-    jQuery(document).ready(function($) {
+  {if $isProvider}
+    <form href="#">
+        <h3>Select a site to display (service provider only)</h3>    
+        <p>
+        Sort by:&nbsp;&nbsp;
+        <input type="radio" name="site_sort" {if $site_sort == 'target_percent'} checked="checked"{/if} onClick="location.href='{$thisUrl}?page={$thisPage}&site_sort=target_percent&selected_site={$selectedSite}';">Percent of Target&nbsp;&nbsp;
+        <input type="radio" name="site_sort" {if $site_sort == 'data_total'} checked="checked"{/if} onClick="location.href='{$thisUrl}?page={$thisPage}&site_sort=data_total&selected_site={$selectedSite}';">Total Traffic&nbsp;&nbsp;
+        <input type="radio" name="site_sort" {if $site_sort == 'site_name'} checked="checked"{/if} onClick="location.href='{$thisUrl}?page={$thisPage}&site_sort=site_name&selected_site={$selectedSite}';">Site Name
+        </p>
+    </form>
+        <div class="pseudoPick">
+            <pre style="text-decoration: underline;">Website                                                Last Month             Target                  </pre>
+    {foreach $websites as $site}
+            <pre class="pseudoPickOption"></span>{if $site.name == $selectedSite}<a name="selectedSite"></a>{/if}<a href="{$thisUrl}?page={$thisPage}&selected_site={$site.name}&site_id={$site.id}&site_sort={$site_sort}" class="pseudoPickOption" {if $site.name == $selectedSite}onClick="return false;"{/if}><span{if $site.name == $selectedSite} style="background-color: LightGray;"{/if}>{$site.name|string_format:"%-50s"} {$site.data_total|string_format:"%6.1f"} Gigabytes   {$site.target|string_format:"%8.1f"} Gigabytes   <span {if $site.target_percent > 80}style="color: red;"{/if}>{$site.target_percent|string_format:"%6.0f"}%</span></span></a></pre> 
+<!-- 
+            <pre class="pseudoPickOption"></span>{if $site.name == $selectedSite}<a name="selectedSite"></a>{/if}<a href="{$thisUrl}?page={$thisPage}&selected_site={$site.name}&site_sort={$site_sort}" class="pseudoPickOption" {if $site.name == $selectedSite}onClick="return false;"{/if}><span{if $site.name == $selectedSite} style="background-color: LightGray;"{/if}>{$site.name|string_format:"%-50s"} {$site.data_total|string_format:"%6.1f"} Gigabytes   {$site.target|string_format:"%8.1f"} Gigabytes   <span {if $site.target_percent > 80}style="color: red;"{/if}>{$site.target_percent|string_format:"%6.0f"}%</span></span></a></pre> 
+-->
+    {/foreach}
+        </div>
+  {/if}
+    <!-- Server Data Usage Stats -->
+    <div style="width: 95%;">
+        <center>
+            <p>&nbsp;</p>
+            Date Selected: 
+            <input type="hidden" autofocus="true">
+            <input data-id="graphDate" type="text" name="graph_date" value="{$thisDate}" class="glm-form-text-input-small glm-date-input recurrence-input" placeholder="Click to Select Date/Time" tabindex="2">
+            &nbsp;&nbsp;&nbsp;&nbsp;<div class="button button-secondary graph-print" data-areaToPrint="StatsPrintArea">Print</div>
+            &nbsp;&nbsp;&nbsp;&nbsp;<span class="button button-secondary" id="guideButton">Explanation of Usage and Graphs</span>
+            <table id="usageGuide" class="glmbw-table" style="margin-top: 3em;"> 
+                <tbody>
+                    <tr>
+                        <td>Traffic</td> 
+                        <td style="padding-bottom: 1em;">
+                            The data sent and received by this Web site.
+                            Traffic is displayed below in <b>Megabytes</b> or <b>Gigabytes</b>. 
+                            A byte is roughly equivalent to one character, a Megabyte is roughly one Million characters, 
+                            and a Gigabyte is roughtly one Trillion characters.
+                        </td>  
+                    </tr>
+                    <tr>
+                        <td style="color: red;">Incoming</td> 
+                        <td style="padding-bottom: 1em;">
+                            Requests from a user for Web pages or other data sent to the Website including any 
+                            uploaded images or files.
+                        </td>
+                    </tr>
+                    <tr>
+                        <td style="color: green;">Outgoing</td>
+                        <td style="padding-bottom: 1em;">
+                            Data sent to users of your site including all Web pages, images, and files requested 
+                            by the user. Note that this line may be covered by the Total (blue) line where they are the same.
+                        </td>
+                    </tr>
+                    <tr>
+                        <td style="color: blue;">Total</td> 
+                        <td style="padding-bottom: 1em;">
+                            Total of all incoming and outgoing data. This is the value that is compared to the 
+                            the <b>Target</b> data traffic for billing purposes. 
+                        </td> 
+                    </tr>
+                    <tr>
+                        <td style="color: purple; white-space: nowrap;">Traffic Target</td>
+                        <td style="padding-bottom: 1em;">
+                            The maximum total monthly traffic expected for your Website. 
+                            You are billed based on this target. If your "Total" traffic regularly exceeds this, you will be contacted
+                            to discuss increasing this target. This value is represented by the dotted line on the 
+                            "Monthly Traffic" graph.
+                        </td>
+                    </tr>
+                    <tr>
+                        <td style="color: gray; white-space: nowrap;">Disk Space Used&nbsp;&nbsp;</td> 
+                        <td style="padding-bottom: 1em;">
+                            The greatest amount of server disk space consumed by this Web site and all associated data during the measurement period. 
+                            Disk Space Used is displayed in <b>Gigabytes</b>. 
+                        </td>  
+                    </tr>
+                    <tr>
+                        <td style="color: purple; white-space: nowrap;">Disk Space Target</td>
+                        <td style="padding-bottom: 1em;">
+                            The maximum disk storage space your Website is expected to use. 
+                            You are billed for data storage based on this target. If the "Disk Space Used" regularly exceeds this, you will be contacted
+                            to discuss increasing this target. This value is represented by the dotted line on the 
+                            "Monthly Disk Space Used" graph.
+                        </td>
+                    </tr>
+                </tbody>
+            </table>
+    
+            <div id="StatsPrintArea" class="PrintArea" style="padding: 10px;">
+                <style>
+                    .glmbw-table{
+                    }
+                    .glmbw-table th {
+                        font-weight: bold;
+                        text-align: left;
+                        vertical-align: top;
+                        white-space: nowrap;
+                    }
+                    .glmbw-table .glmbw-th-light {
+                        font-weight: bold;
+                        text-align: left;
+                        vertical-align: top;
+                        white-space: nowrap;
+                    }
+                    .glmbw-table td {
+                        font-weight: normal;
+                        text-align: left;
+                        vertical-align: top;
+                    }
+                    .glmbw-image {
+                        max-width: 90%;
+                        height: auto;
+                        width: auto\9; /* IE8 */
+                    }
+                </style>
+                <center>
+                    <table class="glmbw-table">
+                        <h2>Server Usage for {$website} - {$reportDate}</h2>
+                        <tr>
+                            <th>&nbsp;</th><th>Traffic</th><th>Storage</th></tr>
+                        <tr>
+                            <th>Yesterday: </th>
+                            <td>
+                                {$serverStats.yesterday.data_total|string_format:"%.3f"} Megabytes<br>
+                            </td>
+                            <td>
+                                {$serverStats.yesterday.storage|string_format:"%.3f"} Gigabytes
+                            </td>
+                        </tr>
+                        <tr>
+                            <th>This Month: </th>
+                            <td>
+                                {$serverStats.thisMonth.data_total|string_format:"%.3f"} Gigabytes<br>
+                            </td>
+                            <td>
+                                {$serverStats.thisMonth.storage|string_format:"%.3f"} Gigabytes
+                            </td>
+                        </tr>
+                        <tr>
+                            <th>Last Month: </th>
+                            <td{if $serverStats.trafficDiff.exceeded} style="color: red;"{/if}>
+                                {$serverStats.lastMonth.data_total|string_format:"%.3f"} Gigabytes
+                            </td>
+                            <td>
+                                {$serverStats.lastMonth.storage|string_format:"%.3f"} Gigabytes
+                            </td>
+                        </tr>
+                        <tr>
+                            <th>Monthly Traffic Target: </th>
+                            <td>
+                                {$target|string_format:"%.3f"} Gigabytes
+                            </td>
+                            <td>
+                                &nbsp;
+                            </td>
+                        </tr>
+                    {if $serverStats.trafficDiff.exceeded}
+                        <tr>
+                            <td colspan="2" style="padding-top: 1em; color: red;">Total Traffic Target exceeded by {$serverStats.trafficDiff.traffic|string_format:"%.3f"} Gigabytes ({$serverStats.trafficDiff.percent|string_format:"%.0f"}%).</td>
+                        </tr>
+                    {/if}        
+                    </table>
+                    <h4>
+                        Color Key: <span style="color: maroon;">Target</span>, <span style="color: gray;">Storage</span>, <span style="color: red;">Incoming</span>, <span style="color: green;">Outgoing</span>, <span style="color: blue;">Total</span><br>                     
+                    </h4>
+                    <p><img id="twoDayImg" src="{$assetsUrl}/graph.png" class="glmbw-image"><br></p>
+                    <p><img id="twoMonthImg" src="{$assetsUrl}/graph.png" class="glmbw-image"><br></p>
+                    <p><img id="twoYearImg" src="{$assetsUrl}/graph.png" class="glmbw-image"><br></p>
+                    <p><img id="twoYearStorageImg" src="{$assetsUrl}/graph.png" class="glmbw-image"><br></p>
+                </center>
+            </div>
+        </center>
+    </div>
+    
+    <script src="{$jsUrl}/PrintArea/jquery.PrintArea.js" type="text/JavaScript" language="javascript"></script>
+    
+    <script type="text/javascript">
+        jQuery(document).ready(function($) {
 
-        // Date Only Pickers
-        $('.glm-date-input').datetimepicker({
-            format: 'm/d/Y',
-            lang: 'en',
-            step: 15,
-            opened: false,
-            closeOnWithoutClick: true,
-            timepicker: false,
-            onChangeDateTime:function(dp,$input){
-                updateGraphs($input.val());
-                
-            }
-        });
-        
-        function updateGraphs(d) {
-            $('#twoDayImg').attr('src', '{$ajaxUrl}?action=glm_server_stats&glm_action=ajaxServerBandwidthGraphs&graphType=twoDay&refDate=' + d);
-            $('#twoMonthImg').attr('src', '{$ajaxUrl}?action=glm_server_stats&glm_action=ajaxServerBandwidthGraphs&graphType=twoMonth&refDate=' + d);
-            $('#twoYearImg').attr('src', '{$ajaxUrl}?action=glm_server_stats&glm_action=ajaxServerBandwidthGraphs&graphType=twoYear&refDate=' + d);
-        }
-        
-        $(".graph-print").click(function(){
-            var areaToPrint = $(this).attr('data-areaToPrint');
-            var position = $(this).offset();
-            $('#' + areaToPrint).printArea({
-                mode:       'popup',        //printable window is either iframe or browser popup
-                popHt:      1200,            // popup window height
-                popWd:      1200,            // popup window width
-                popX:       200,            // popup window screen X position
-                popY:       200,            //popup window screen Y position
-                popTitle:   'Graph Print Window',   // popup window title element
-                popClose:   true,           // popup window close after printing
-                extraCss:   '',             // Comma separated list of extra css to include
-                extraHead:  '',             // Comma separated list of extra elements to be appended to head tag
-                strict:     false           // strict or looseTransitional html 4.01 document standard or undefined to not include at all only for popup option
+            // Toggle guide contents
+            $('#guideButton').on('click', function() {
+                $('#usageGuide').toggle();
+            })
+            $('#usageGuide').hide();
+            
+            // Date Only Pickers
+            $('.glm-date-input').datetimepicker({
+                format: 'm/d/Y',
+                lang: 'en',
+                step: 15,
+                opened: false,
+                closeOnWithoutClick: true,
+                timepicker: false,
+                onChangeDateTime:function(dp,$input){
+                    updateGraphs($input.val());
+                }
             });
-       });
+            
+            function updateGraphs(d) {
+                $('#twoDayImg').attr('src', '{$assetsUrl}/graph.png');
+                $('#twoMonthImg').attr('src', '{$assetsUrl}/graph.png');
+                $('#twoYearImg').attr('src', '{$assetsUrl}/graph.png');
+                $('#twoDayImg').attr('src', '{$ajaxUrl}?action=glm_server_stats&glm_action=ajaxServerBandwidthGraphs&website={$selectedSite}&graphType=oneDay&refDate=' + d);
+                $('#twoMonthImg').attr('src', '{$ajaxUrl}?action=glm_server_stats&glm_action=ajaxServerBandwidthGraphs&website={$selectedSite}&graphType=twoMonth&refDate=' + d);
+                $('#twoYearImg').attr('src', '{$ajaxUrl}?action=glm_server_stats&glm_action=ajaxServerBandwidthGraphs&website={$selectedSite}&graphType=twoYear&refDate=' + d);
+                $('#twoYearStorageImg').attr('src', '{$ajaxUrl}?action=glm_server_stats&glm_action=ajaxServerBandwidthGraphs&website={$selectedSite}&graphType=twoYearStorage&refDate=' + d);
+            }
+            
+            $(".graph-print").click(function(){
+                var areaToPrint = $(this).attr('data-areaToPrint');
+                var position = $(this).offset();
+                $('#' + areaToPrint).printArea({
+                    mode:       'popup',        //printable window is either iframe or browser popup
+                    popHt:      1200,            // popup window height
+                    popWd:      1100,            // popup window width
+                    popX:       200,            // popup window screen X position
+                    popY:       200,            //popup window screen Y position
+                    popTitle:   'Server Usage',   // popup window title element
+                    popClose:   false,           // popup window close after printing
+                    extraCss:   '',             // Comma separated list of extra css to include
+                    extraHead:  '',             // Comma separated list of extra elements to be appended to head tag
+                    strict:     false           // strict or loose Transitional html 4.01 document standard or undefined to not include at all only for popup option
+                });
+           });
+
+           // Do an initial load of usage graphs
+           updateGraphs('{$thisDate}');
+
+           location.href='#selectedSite';
 
-        // Display selected graph dialog box
-        $('.dialog-button').click( function() {
-            $(".graph-dialog").dialog("close");
-            var graph = $(this).attr('data-type');
-            $('#' + graph).dialog("open");
-            return false;
         });
+    </script>
+  {/if}
 
-    });
-</script>
-{else}
-    <h3 class="glm-error">Server Bandwidth has not been configured. Please ask system administrator to configure this plugin.</h3>
-    <p><b>Error:</b> {$connectError}</p>
 {/if}
 
+
 {include file='footer.html'}
old mode 100644 (file)
new mode 100755 (executable)
index 58d979d..a30a859
 {include file='header.html'}
 
+    <style>
+        .pseudoPick {
+            
+            height: 150px; 
+            padding-left: 2px; 
+            overflow-y: auto; 
+            overflow-x: hidden;
+            display: inline-block;
+            margin-top: 1em;
+            border: 1px #ddd solid;
+        }
+        .pseudoPickOption {
+            text-decoration: none;
+            line-height: .2em;
+        }
+        .pseudoPickOption:hover {
+            background-color: #0568B3 !important;
+            color: white;
+        }
+    </style>
+
     <!--  Server Settings  -->
     <div id="glm-table-serverstats-server" class="glm-settings-table">
 
-    {if $settingsUpdated}<h2 class="glm-notice glm-flash-updated glm-right">Settings Updated</h2>{/if}
-    {if $settingsUpdateError}<span class="glm-error glm-flash-updated glm-right">Settings Update Error</span>{/if}
-
-    {if $dbError != ''}
-        <h2 class="glm-error">Unable to test database connection!</h2>
-        <p><b>Error reported:</b> {$dbError}</p>
-    {/if}
-        <h2>Server Bandwidth Statistics Configuration</h2>
+        <h2>Server Usage Statistics Configuration</h2>
         <form action="{$thisUrl}?page={$thisPage}" method="post" enctype="multipart/form-data">
-            <input type="hidden" name="option" value="submit">
+            <input type="hidden" name="option" value="update_connection">
+            <input type="hidden" name="selected_site" value="{$selectedSite}">
 
-            <table class="glm-admin-table">
-
-                <!-- Settings for talking with the Bandwidth Database -->
+            <table class="glm-admin-table" style="width: 95%">
+                <tr>
+                    <td>
+                        {if $connectionUpdated}<h2 class="glm-notice glm-flash-updated">Settings Updated</h2>{/if}
+                        
+                    </td>
+                    <th>
+                        <h2>Database Connection</h2>
+                        {if $connectionUpdateError}<br><span class="glm-error">Error {$connectionUpdateError}{/if}
+                    </th>
+                </tr>
                 <tr>
                     <th class="glm-required">Database Name:</th>
                     <td {if !$db_name}class="glm-form-bad-input glm-form-bad-input-misc"{/if}>
-                        <input type="text" name="db_name" value="{$db_name}" class="glm-form-text-input-medium">
+                        <input type="text" name="db_name" value="{$db_name}" class="glm-form-text-input-medium" placeholder="Provided by GLM Engineering">
                         {if !$db_name}<p>Database Name not provided or invalid!</p>{/if}
                     </td>
                 </tr>
                 <tr>
                     <th class="glm-required">Database Server Hostname:</th>
                     <td {if !$db_host}class="glm-form-bad-input glm-form-bad-input-misc"{/if}>
-                        <input type="text" name="db_host" value="{$db_host}" class="glm-form-text-input-medium">
+                        <input type="text" name="db_host" value="{$db_host}" class="glm-form-text-input-medium" placeholder="Provided by GLM Engineering">
                     </td>
                 </tr>
                 <tr>
                     <th class="glm-required">Database Username:</th>
                     <td {if !$db_user}class="glm-form-bad-input glm-form-bad-input-misc"{/if}>
-                        <input type="text" name="db_user" value="{$db_user}" class="glm-form-text-input-medium">
+                        <input type="text" name="db_user" value="{$db_user}" class="glm-form-text-input-medium" placeholder="Provided by GLM Engineering'.">
                     </td>
                 </tr>
                 <tr>
                     <th class="glm-required">Database Password:</th>
                     <td {if !$db_pass}class="glm-form-bad-input glm-form-bad-input-misc"{/if}>
-                        <input type="text" name="db_pass" value="{$db_pass}" class="glm-form-text-input-medium">
+                        <input type="text" name="db_pass" value="{$db_pass}" class="glm-form-text-input-medium" placeholder="Provided by GLM Engineering'.">
                     </td>
                 </tr>
                 <tr>
-                    <th class="glm-required">Website Name:</th>
+                    <th class="glm-required">Default Website Name:</th>
                     <td {if !$website}class="glm-form-bad-input glm-form-bad-input-misc"{/if}>
-                        <input type="text" name="website" value="{$website}" class="glm-form-text-input-medium">
-                        <br>This is the name of the Website as it's listed in the server stats database. Normally does include 'www'.
+                        <input type="text" name="website" value="{$website}" class="glm-form-text-input-medium" placeholder="i.e. www.gaslightmedia.com'.">
+                        <br>
+                        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.
+                    </td>
+                </tr>
+            </table>
+{if $connectError}
+            <h2 class="glm-error">Unable to connect to database! Please check connection settings.</h2>
+{/if}            
+            <input type="submit" value="Update Database Connection" class="button-primary">
+        </form>
+
+{if !$connectError && $isProvider}
+        <form action="{$thisUrl}?page={$thisPage}&selected_site={$selectedSite}" method="post" enctype="multipart/form-data">
+            <input type="hidden" name="option" value="update_site">
+            <input type="hidden" name="selected_site" value="{$selectedSite}">
+            <table class="glm-admin-table" style="width: 100%">
+                <tr><td colspan="2"><hr></td></tr>
+                <tr><td>&nbsp;</td><th><h2>Site Selection (service provider only)</h2></th></tr>
+                <tr>
+                    <th>Select Site to Configure</th>
+                    <td>
+                        <p>
+                            Sort by: 
+                            <input type="radio" name="site_sort" value="data_total" {if $site_sort == 'data_total'} checked="checked"{/if} onClick="location.href='{$thisUrl}?page={$thisPage}&site_sort=data_total&selected_site={$site.name}';">Total Traffic
+                            <input type="radio" name="site_sort" value="target_percent" {if $site_sort == 'target_percent'} checked="checked"{/if} onClick="location.href='{$thisUrl}?page={$thisPage}&site_sort=target_percent&selected_site={$site.name}';">Percent of Target
+                            <input type="radio" name="site_sort" value="site_name" {if $site_sort == 'site_name'} checked="checked"{/if} onClick="location.href='{$thisUrl}?page={$thisPage}&site_sort=site_name&selected_site={$site.name}';">Site Name
+                        </p>
+                        <div class="pseudoPick">
+                            <pre style="text-decoration: underline;">Website                                                Last Month             Target                  </pre>
+                      {foreach $websites as $site}
+                            <pre class="pseudoPickOption"></span>{if $site.name == $selectedSite}<a name="selectedSite"></a>{/if}<a href="{$thisUrl}?page={$thisPage}&selected_site={$site.name}&site_sort={$site_sort}" class="pseudoPickOption" {if $site.name == $selectedSite}onClick="return false;"{/if}><span{if $site.name == $selectedSite} style="background-color: LightGray;"{/if}>{$site.name|string_format:"%-50s"} {$site.data_total|string_format:"%6.1f"} Gigabytes   {$site.target|string_format:"%8.1f"} Gigabytes   <span {if $site.target_percent > 80}style="color: red;"{/if}>{$site.target_percent|string_format:"%6.0f"}%</span></span></a></pre> 
+                      {/foreach}
+                        </div>
+                    </td>
+    {if $selectedSite}          
+                <tr><td colspan="2"><hr></td></tr>          
+                <tr><td>&nbsp;</td><th><h2>Settings for Selected Site (service provider only)</h2></th></tr>
+                <tr>
+                    <th class="glm-required">Monthly Target Traffic:</th>
+                    <td>
+                        <input type="text" name="target" value="{$settings.target|string_format:"%.1f"}" class="glm-form-text-input-medium" placeholder="i.e. 2.000 for 2 Gigabytes">
+                        <br>Monthly target traffic is entered in Gigabytes.
                     </td>
                 </tr>
                 <tr>
-                    <th class="glm-required">Monthly Target Bandwidth:</th>
-                    <td {if !$target}class="glm-form-bad-input glm-form-bad-input-misc"{/if}>
-                        <input type="text" name="target" value="{$target}" class="glm-form-text-input-medium">
-                        <br>Monthly target bandwidth is entered in Megabytes without any fractions.
+                    <th class="glm-required">Target Disk Space Used:</th>
+                    <td>
+                        <input type="text" name="disk_target" value="{$settings.disk_target|string_format:"%.1f"}" class="glm-form-text-input-medium" placeholder="i.e. 2.000 for 2 Gigabytes">
+                        <br>Disk Space is entered in Gigabytes.
                     </td>
                 </tr>
+                <tr>
+                    <th class="glm-required">Gaslight Media Contact E-Mail:</th>
+                    <td>
+                        <input type="text" name="glm_contact" value="{$settings.glm_contact}" class="glm-form-text-input-medium">
+                        <br>E-mail address of Gaslight Media contact who will receive over-target E-Mail.
+                    </td>
+                </tr>
+                <tr>
+                    <th class="glm-required">Customer Contact E-Mail:</th>
+                    <td>
+                        <input type="text" name="cust_contact" value="{$settings.cust_contact}" class="glm-form-text-input-medium">
+                        <br>E-mail address of customer contact who will receive over-target E-Mail.
+                    </td>
+                </tr>
+    {/if}                
             </table>
-            <input type="submit" value="Update Settings" class="button-primary">
+    {if $selectedSite}
+            <input type="submit" value="Update Site Settings" class="button-primary">
+    {/if}
         </form>
+{/if}
+        
     </div>
     <script type="text/javascript">
 
             // Flash certain elements for a short time after display
             $(".glm-flash-updated").fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500);
 
+            location.href='#selectedSite';
+            
+                
         });
     </script>