From 52e239066bb367725923a0e1d196992366afef23 Mon Sep 17 00:00:00 2001
From: Kathleen Murtagh <kmurtagh@saymedia.com>
Date: Tue, 8 Nov 2011 11:23:07 -0800
Subject: [PATCH] Issue #1335708: Recording daycount when calculating and recording totalcount in node_counter

---
 google_analytics_counter.module |   16 ++++++++++++++--
 1 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/google_analytics_counter.module b/google_analytics_counter.module
index c5acaa1..8de8f0b 100644
--- a/google_analytics_counter.module
+++ b/google_analytics_counter.module
@@ -265,8 +265,11 @@ function google_analytics_counter_get_sum_per_path($path) {
      */
 
     $sum_of_pageviews = 0;
+    $pageviews_today = 0;
     $countdays = 0;
     $lookingforfirsthit = TRUE;
+    $date_today = date('Ymd', time());
+    $date_yesterday = date('Ymd', (time() - (24*60*60)));
     foreach ($rows as $date) {
       // In case some error message appears, set zero and get out.
       if (!is_numeric($date['pageviews'])) {
@@ -279,6 +282,15 @@ function google_analytics_counter_get_sum_per_path($path) {
         $countdays++;
         $lookingforfirsthit = FALSE;
       }
+      if ($date['date'] == $date_today) {
+        $pageviews_today += $date['pageviews'];
+      }
+      if ($date['date'] == $date_yesterday && date('G', time() < '12')) {
+        // Add in half of yesterday's count for half of today, to prevent early
+        // morning oddities with popularity.  It would be better to get the last
+        // 24 hours, but would require another query to get hourly data.
+        $pageviews_today += (round($date['pageviews'] / 2));
+      }
     }
 
     // We need to store the count, days of counting, and also the absolute time of caching as well.
@@ -307,11 +319,11 @@ function google_analytics_counter_get_sum_per_path($path) {
       if ($nid !== FALSE AND $sum_of_pageviews <> 0) {
         // This is a node, so update the node's counters.
         // We don't do anything with daycount here
-        db_query('UPDATE {node_counter} SET daycount = 0, totalcount = %d, timestamp = %d WHERE nid = %d', $sum_of_pageviews, time(), $nid);
+        db_query('UPDATE {node_counter} SET daycount = %d, totalcount = %d, timestamp = %d WHERE nid = %d', $pageviews_today, $sum_of_pageviews, time(), $nid);
         // If we affected 0 rows, this is the first time viewing the node.
         if (!db_affected_rows()) {
           // We must create a new row to store counters for the new node.
-          db_query('INSERT INTO {node_counter} (nid, daycount, totalcount, timestamp) VALUES (%d, 0, %d, %d)', $nid, $sum_of_pageviews, time());
+          db_query('INSERT INTO {node_counter} (nid, daycount, totalcount, timestamp) VALUES (%d, %d, %d, %d)', $nid, $pageviews_today, $sum_of_pageviews, time());
         }
       }
     }
-- 
1.7.3.4

