From 4e22a0d5e4b60941d41071f059aac80cbaf38fbf Mon Sep 17 00:00:00 2001
From: Yassine Doghri <yassine@doghri.fr>
Date: Thu, 14 Apr 2022 14:33:53 +0000
Subject: [PATCH] fix: use UTC_TIMESTAMP() to get current utc date instead of
 NOW() in sql queries

---
 app/Controllers/EpisodeController.php                |  2 +-
 app/Controllers/MapController.php                    |  2 +-
 app/Controllers/PodcastController.php                |  4 ++--
 .../Migrations/2020-06-05-190000_add_platforms.php   |  6 ++++--
 ...ew.php => 2020-12-25-150000_add_credits_view.php} |  6 ++----
 app/Database/Seeds/FakePodcastsAnalyticsSeeder.php   |  2 +-
 app/Database/Seeds/FakeWebsiteAnalyticsSeeder.php    |  2 +-
 app/Models/EpisodeCommentModel.php                   |  2 +-
 app/Models/EpisodeModel.php                          | 12 ++++++------
 app/Models/PodcastModel.php                          |  6 +++---
 app/Models/PostModel.php                             |  2 +-
 modules/Admin/Controllers/EpisodeController.php      |  4 ++--
 ...12-01-210000_add_analytics_podcasts_procedure.php |  2 +-
 ...-12-01-210000_add_analytics_website_procedure.php |  2 +-
 modules/Fediverse/Controllers/ActorController.php    |  2 +-
 modules/Fediverse/Controllers/PostController.php     |  2 +-
 modules/Fediverse/Models/ActivityModel.php           |  2 +-
 modules/Fediverse/Models/ActorModel.php              |  4 ++--
 modules/Fediverse/Models/PostModel.php               | 12 ++++++------
 modules/WebSub/Controllers/WebSubController.php      |  4 ++--
 20 files changed, 40 insertions(+), 40 deletions(-)
 rename app/Database/Migrations/{2020-12-25-150000_add_credit_view.php => 2020-12-25-150000_add_credits_view.php} (91%)

diff --git a/app/Controllers/EpisodeController.php b/app/Controllers/EpisodeController.php
index f2642152dd..ebfedc22d5 100644
--- a/app/Controllers/EpisodeController.php
+++ b/app/Controllers/EpisodeController.php
@@ -274,7 +274,7 @@ class EpisodeController extends BaseController
                     ->from(config('Fediverse')->tablesPrefix . 'posts')
                     ->where('episode_id', $this->episode->id);
             })
-            ->where('`published_at` <= NOW()', null, false)
+            ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
             ->orderBy('published_at', 'ASC');
 
         $pageNumber = (int) $this->request->getGet('page');
diff --git a/app/Controllers/MapController.php b/app/Controllers/MapController.php
index 79fa7d5261..be153a33cd 100644
--- a/app/Controllers/MapController.php
+++ b/app/Controllers/MapController.php
@@ -43,7 +43,7 @@ class MapController extends BaseController
         $cacheName = 'episodes_markers';
         if (! ($found = cache($cacheName))) {
             $episodes = (new EpisodeModel())
-                ->where('`published_at` <= NOW()', null, false)
+                ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                 ->where('location_geo is not', null)
                 ->findAll();
             $found = [];
diff --git a/app/Controllers/PodcastController.php b/app/Controllers/PodcastController.php
index 6af8890e03..1242e91040 100644
--- a/app/Controllers/PodcastController.php
+++ b/app/Controllers/PodcastController.php
@@ -287,11 +287,11 @@ class PodcastController extends BaseController
         if ($this->podcast->type === 'serial') {
             // podcast is serial
             $episodes = model(EpisodeModel::class)
-                ->where('`published_at` <= NOW()', null, false)
+                ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                 ->orderBy('season_number DESC, number ASC');
         } else {
             $episodes = model(EpisodeModel::class)
-                ->where('`published_at` <= NOW()', null, false)
+                ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                 ->orderBy('published_at', 'DESC');
         }
 
diff --git a/app/Database/Migrations/2020-06-05-190000_add_platforms.php b/app/Database/Migrations/2020-06-05-190000_add_platforms.php
index 7e9da4d5c9..70d5217845 100644
--- a/app/Database/Migrations/2020-06-05-190000_add_platforms.php
+++ b/app/Database/Migrations/2020-06-05-190000_add_platforms.php
@@ -41,8 +41,10 @@ class AddPlatforms extends Migration
                 'null' => true,
             ],
         ]);
-        $this->forge->addField('`created_at` timestamp NOT NULL DEFAULT NOW()');
-        $this->forge->addField('`updated_at` timestamp NOT NULL DEFAULT NOW() ON UPDATE NOW()');
+        $this->forge->addField('`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP()');
+        $this->forge->addField(
+            '`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP()'
+        );
         $this->forge->addPrimaryKey('slug');
         $this->forge->createTable('platforms');
     }
diff --git a/app/Database/Migrations/2020-12-25-150000_add_credit_view.php b/app/Database/Migrations/2020-12-25-150000_add_credits_view.php
similarity index 91%
rename from app/Database/Migrations/2020-12-25-150000_add_credit_view.php
rename to app/Database/Migrations/2020-12-25-150000_add_credits_view.php
index 631c507516..62b8415be9 100644
--- a/app/Database/Migrations/2020-12-25-150000_add_credit_view.php
+++ b/app/Database/Migrations/2020-12-25-150000_add_credits_view.php
@@ -3,8 +3,6 @@
 declare(strict_types=1);
 
 /**
- * Class AddCreditView Creates Credit View in database
- *
  * @copyright  2020 Ad Aures
  * @license    https://www.gnu.org/licenses/agpl-3.0.en.html AGPL3
  * @link       https://castopod.org/
@@ -14,7 +12,7 @@ namespace App\Database\Migrations;
 
 use CodeIgniter\Database\Migration;
 
-class AddCreditView extends Migration
+class AddCreditsView extends Migration
 {
     public function up(): void
     {
@@ -35,7 +33,7 @@ class AddCreditView extends Migration
                     ON (`person_id`=`{$personsTable}`.`id`)
                 INNER JOIN `{$episodesTable}`
                     ON (`episode_id`=`{$episodesTable}`.`id`)
-            WHERE `{$episodesTable}`.published_at <= NOW()
+            WHERE `{$episodesTable}`.published_at <= UTC_TIMESTAMP()
             ORDER BY `person_group`, `full_name`, `person_role`, `podcast_id`, `episode_id`;
         CODE_SAMPLE;
         $this->db->query($createQuery);
diff --git a/app/Database/Seeds/FakePodcastsAnalyticsSeeder.php b/app/Database/Seeds/FakePodcastsAnalyticsSeeder.php
index d05870d897..702387c9a0 100644
--- a/app/Database/Seeds/FakePodcastsAnalyticsSeeder.php
+++ b/app/Database/Seeds/FakePodcastsAnalyticsSeeder.php
@@ -60,7 +60,7 @@ class FakePodcastsAnalyticsSeeder extends Seeder
 
                 $episodes = (new EpisodeModel())
                     ->where('podcast_id', $podcast->id)
-                    ->where('`published_at` <= NOW()', null, false)
+                    ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                     ->findAll();
                 foreach ($episodes as $episode) {
                     $age = floor(($date - strtotime((string) $episode->published_at)) / 86400);
diff --git a/app/Database/Seeds/FakeWebsiteAnalyticsSeeder.php b/app/Database/Seeds/FakeWebsiteAnalyticsSeeder.php
index ea7c230222..8560f25125 100644
--- a/app/Database/Seeds/FakeWebsiteAnalyticsSeeder.php
+++ b/app/Database/Seeds/FakeWebsiteAnalyticsSeeder.php
@@ -199,7 +199,7 @@ class FakeWebsiteAnalyticsSeeder extends Seeder
 
                 $episodes = (new EpisodeModel())
                     ->where('podcast_id', $podcast->id)
-                    ->where('`published_at` <= NOW()', null, false)
+                    ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                     ->findAll();
                 foreach ($episodes as $episode) {
                     $age = floor(($date - strtotime((string) $episode->published_at)) / 86400);
diff --git a/app/Models/EpisodeCommentModel.php b/app/Models/EpisodeCommentModel.php
index 7ac93b0b68..47e4fd8d60 100644
--- a/app/Models/EpisodeCommentModel.php
+++ b/app/Models/EpisodeCommentModel.php
@@ -165,7 +165,7 @@ class EpisodeCommentModel extends UuidModel
                         'in_reply_to_id' => null,
                     ]);
             })
-            ->where('`created_at` <= NOW()', null, false)
+            ->where('`created_at` <= UTC_TIMESTAMP()', null, false)
             ->getCompiledSelect();
 
         $allEpisodeComments = $this->db->query(
diff --git a/app/Models/EpisodeModel.php b/app/Models/EpisodeModel.php
index e9fb463ff4..573b6e7694 100644
--- a/app/Models/EpisodeModel.php
+++ b/app/Models/EpisodeModel.php
@@ -146,7 +146,7 @@ class EpisodeModel extends Model
                 ->join('podcasts', 'podcasts.id = episodes.podcast_id')
                 ->where('slug', $episodeSlug)
                 ->where('podcasts.handle', $podcastHandle)
-                ->where('`published_at` <= NOW()', null, false)
+                ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                 ->first();
 
             cache()
@@ -182,7 +182,7 @@ class EpisodeModel extends Model
                 'id' => $episodeId,
             ])
                 ->where('podcast_id', $podcastId)
-                ->where('`published_at` <= NOW()', null, false)
+                ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                 ->first();
 
             cache()
@@ -224,12 +224,12 @@ class EpisodeModel extends Model
             if ($podcastType === 'serial') {
                 // podcast is serial
                 $found = $this->where($where)
-                    ->where('`published_at` <= NOW()', null, false)
+                    ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                     ->orderBy('season_number DESC, number ASC')
                     ->findAll();
             } else {
                 $found = $this->where($where)
-                    ->where('`published_at` <= NOW()', null, false)
+                    ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                     ->orderBy('published_at', 'DESC')
                     ->findAll();
             }
@@ -257,11 +257,11 @@ class EpisodeModel extends Model
      */
     public function getSecondsToNextUnpublishedEpisode(int $podcastId): int | false
     {
-        $result = $this->select('TIMESTAMPDIFF(SECOND, NOW(), `published_at`) as timestamp_diff')
+        $result = $this->select('TIMESTAMPDIFF(SECOND, UTC_TIMESTAMP(), `published_at`) as timestamp_diff')
             ->where([
                 'podcast_id' => $podcastId,
             ])
-            ->where('`published_at` > NOW()', null, false)
+            ->where('`published_at` > UTC_TIMESTAMP()', null, false)
             ->orderBy('published_at', 'asc')
             ->get()
             ->getResultArray();
diff --git a/app/Models/PodcastModel.php b/app/Models/PodcastModel.php
index d913fd68a4..e458585152 100644
--- a/app/Models/PodcastModel.php
+++ b/app/Models/PodcastModel.php
@@ -189,7 +189,7 @@ class PodcastModel extends Model
                     'left'
                 )
                 ->where(
-                    '`' . $prefix . $fediverseTablePrefix . 'posts`.`published_at` <= NOW()',
+                    '`' . $prefix . $fediverseTablePrefix . 'posts`.`published_at` <= UTC_TIMESTAMP()',
                     null,
                     false
                 )->orWhere($fediverseTablePrefix . 'posts.published_at', null)
@@ -313,7 +313,7 @@ class PodcastModel extends Model
                     'season_number' => null,
                     $episodeModel->deletedField => null,
                 ])
-                ->where('`published_at` <= NOW()', null, false)
+                ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                 ->groupBy('year')
                 ->orderBy('year', 'DESC')
                 ->get()
@@ -349,7 +349,7 @@ class PodcastModel extends Model
                     'season_number is not' => null,
                     $episodeModel->deletedField => null,
                 ])
-                ->where('`published_at` <= NOW()', null, false)
+                ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                 ->groupBy('season_number')
                 ->orderBy('season_number', 'ASC')
                 ->get()
diff --git a/app/Models/PostModel.php b/app/Models/PostModel.php
index 66cdcba216..f100a85368 100644
--- a/app/Models/PostModel.php
+++ b/app/Models/PostModel.php
@@ -50,7 +50,7 @@ class PostModel extends FediversePostModel
             'episode_id' => $episodeId,
         ])
             ->where('in_reply_to_id', null)
-            ->where('`published_at` <= NOW()', null, false)
+            ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
             ->orderBy('published_at', 'DESC')
             ->findAll();
     }
diff --git a/modules/Admin/Controllers/EpisodeController.php b/modules/Admin/Controllers/EpisodeController.php
index 0fac12a17d..6b1373cf17 100644
--- a/modules/Admin/Controllers/EpisodeController.php
+++ b/modules/Admin/Controllers/EpisodeController.php
@@ -448,7 +448,7 @@ class EpisodeController extends BaseController
                     'Y-m-d H:i',
                     $scheduledPublicationDate,
                     $this->request->getPost('client_timezone'),
-                )->setTimezone('UTC');
+                )->setTimezone(app_timezone());
             } else {
                 $db->transRollback();
                 return redirect()
@@ -541,7 +541,7 @@ class EpisodeController extends BaseController
                     'Y-m-d H:i',
                     $scheduledPublicationDate,
                     $this->request->getPost('client_timezone'),
-                )->setTimezone('UTC');
+                )->setTimezone(app_timezone());
             } else {
                 $db->transRollback();
                 return redirect()
diff --git a/modules/Analytics/Database/Migrations/2017-12-01-210000_add_analytics_podcasts_procedure.php b/modules/Analytics/Database/Migrations/2017-12-01-210000_add_analytics_podcasts_procedure.php
index a1d7867f65..06db078734 100644
--- a/modules/Analytics/Database/Migrations/2017-12-01-210000_add_analytics_podcasts_procedure.php
+++ b/modules/Analytics/Database/Migrations/2017-12-01-210000_add_analytics_podcasts_procedure.php
@@ -45,7 +45,7 @@ class AddAnalyticsPodcastsProcedure extends Migration
         COMMENT 'Add one hit in podcast logs tables.'
         BEGIN
 
-        SET @current_datetime = NOW();
+        SET @current_datetime = UTC_TIMESTAMP();
         SET @current_date = DATE(@current_datetime);
         SET @current_hour = HOUR(@current_datetime);
 
diff --git a/modules/Analytics/Database/Migrations/2017-12-01-210000_add_analytics_website_procedure.php b/modules/Analytics/Database/Migrations/2017-12-01-210000_add_analytics_website_procedure.php
index 69c62f467b..c0668ad408 100644
--- a/modules/Analytics/Database/Migrations/2017-12-01-210000_add_analytics_website_procedure.php
+++ b/modules/Analytics/Database/Migrations/2017-12-01-210000_add_analytics_website_procedure.php
@@ -35,7 +35,7 @@ class AddAnalyticsWebsiteProcedure extends Migration
         SQL SECURITY INVOKER
         BEGIN
 
-        SET @current_date = DATE(NOW());
+        SET @current_date = DATE(UTC_TIMESTAMP());
 
         INSERT INTO {$procedureName}_by_browser(`podcast_id`, `browser`, `date`)
             VALUES (p_podcast_id, p_browser, @current_date)
diff --git a/modules/Fediverse/Controllers/ActorController.php b/modules/Fediverse/Controllers/ActorController.php
index 57692c3c92..44b0dc3a12 100644
--- a/modules/Fediverse/Controllers/ActorController.php
+++ b/modules/Fediverse/Controllers/ActorController.php
@@ -272,7 +272,7 @@ class ActorController extends Controller
         // get published activities by publication date
         $actorActivity = model('ActivityModel', false)
             ->where('actor_id', $this->actor->id)
-            ->where('`created_at` <= NOW()', null, false)
+            ->where('`created_at` <= UTC_TIMESTAMP()', null, false)
             ->orderBy('created_at', 'DESC');
 
         $pageNumber = (int) $this->request->getGet('page');
diff --git a/modules/Fediverse/Controllers/PostController.php b/modules/Fediverse/Controllers/PostController.php
index a29d23b5f5..7eb5f47e28 100644
--- a/modules/Fediverse/Controllers/PostController.php
+++ b/modules/Fediverse/Controllers/PostController.php
@@ -76,7 +76,7 @@ class PostController extends Controller
          */
         $postReplies = model('PostModel', false)
             ->where('in_reply_to_id', service('uuid') ->fromString($this->post->id) ->getBytes())
-            ->where('`published_at` <= NOW()', null, false)
+            ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
             ->orderBy('published_at', 'ASC');
 
         $pageNumber = (int) $this->request->getGet('page');
diff --git a/modules/Fediverse/Models/ActivityModel.php b/modules/Fediverse/Models/ActivityModel.php
index 23945ca80e..225e66d5a9 100644
--- a/modules/Fediverse/Models/ActivityModel.php
+++ b/modules/Fediverse/Models/ActivityModel.php
@@ -111,7 +111,7 @@ class ActivityModel extends BaseUuidModel
      */
     public function getScheduledActivities(): array
     {
-        return $this->where('`scheduled_at` <= NOW()', null, false)
+        return $this->where('`scheduled_at` <= UTC_TIMESTAMP()', null, false)
             ->where('status', 'queued')
             ->orderBy('scheduled_at', 'ASC')
             ->findAll();
diff --git a/modules/Fediverse/Models/ActorModel.php b/modules/Fediverse/Models/ActorModel.php
index 05eef1d1fb..3c550ddc2b 100644
--- a/modules/Fediverse/Models/ActorModel.php
+++ b/modules/Fediverse/Models/ActorModel.php
@@ -250,12 +250,12 @@ class ActorModel extends BaseModel
                 ->where($tablePrefix . 'actors.domain', get_current_domain())
                 ->groupStart()
                 ->where(
-                    "`{$tablePrefix}posts`.`created_at` >= NOW() - INTERVAL {$lastNumberOfMonths} month",
+                    "`{$tablePrefix}posts`.`created_at` >= UTC_TIMESTAMP() - INTERVAL {$lastNumberOfMonths} month",
                     null,
                     false
                 )
                 ->orWhere(
-                    "`{$tablePrefix}favourites`.`created_at` >= NOW() - INTERVAL {$lastNumberOfMonths} month",
+                    "`{$tablePrefix}favourites`.`created_at` >= UTC_TIMESTAMP() - INTERVAL {$lastNumberOfMonths} month",
                     null,
                     false
                 )
diff --git a/modules/Fediverse/Models/PostModel.php b/modules/Fediverse/Models/PostModel.php
index 4b6d0a3601..e25e6c6298 100644
--- a/modules/Fediverse/Models/PostModel.php
+++ b/modules/Fediverse/Models/PostModel.php
@@ -135,7 +135,7 @@ class PostModel extends BaseUuidModel
                 'actor_id' => $actorId,
                 'in_reply_to_id' => null,
             ])
-                ->where('`published_at` <= NOW()', null, false)
+                ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                 ->orderBy('published_at', 'DESC')
                 ->findAll();
 
@@ -154,11 +154,11 @@ class PostModel extends BaseUuidModel
      */
     public function getSecondsToNextUnpublishedPosts(int $actorId): int | false
     {
-        $result = $this->select('TIMESTAMPDIFF(SECOND, NOW(), `published_at`) as timestamp_diff')
+        $result = $this->select('TIMESTAMPDIFF(SECOND, UTC_TIMESTAMP(), `published_at`) as timestamp_diff')
             ->where([
                 'actor_id' => $actorId,
             ])
-            ->where('`published_at` > NOW()', null, false)
+            ->where('`published_at` > UTC_TIMESTAMP()', null, false)
             ->orderBy('published_at', 'asc')
             ->get()
             ->getResultArray();
@@ -195,7 +195,7 @@ class PostModel extends BaseUuidModel
             }
 
             $this->where('in_reply_to_id', $this->uuid->fromString($postId) ->getBytes())
-                ->where('`published_at` <= NOW()', null, false)
+                ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                 ->orderBy('published_at', 'ASC');
             $found = $this->findAll();
 
@@ -219,7 +219,7 @@ class PostModel extends BaseUuidModel
 
         if (! ($found = cache($cacheName))) {
             $found = $this->where('reblog_of_id', $this->uuid->fromString($postId) ->getBytes())
-                ->where('`published_at` <= NOW()', null, false)
+                ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                 ->orderBy('published_at', 'ASC')
                 ->findAll();
 
@@ -614,7 +614,7 @@ class PostModel extends BaseUuidModel
             $result = $this->select('COUNT(*) as total_local_posts')
                 ->join($tablePrefix . 'actors', $tablePrefix . 'actors.id = ' . $tablePrefix . 'posts.actor_id')
                 ->where($tablePrefix . 'actors.domain', get_current_domain())
-                ->where('`published_at` <= NOW()', null, false)
+                ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                 ->get()
                 ->getResultArray();
 
diff --git a/modules/WebSub/Controllers/WebSubController.php b/modules/WebSub/Controllers/WebSubController.php
index a75581720a..72e6d31472 100644
--- a/modules/WebSub/Controllers/WebSubController.php
+++ b/modules/WebSub/Controllers/WebSubController.php
@@ -34,7 +34,7 @@ class WebSubController extends Controller
             ->where('podcasts.is_published_on_hubs', false)
             ->orGroupStart()
             ->where('episodes.is_published_on_hubs', false)
-            ->where('`' . $podcastModel->db->getPrefix() . 'episodes`.`published_at` <= NOW()', null, false)
+            ->where('`' . $podcastModel->db->getPrefix() . 'episodes`.`published_at` <= UTC_TIMESTAMP()', null, false)
             ->groupEnd()
             ->findAll();
 
@@ -82,7 +82,7 @@ class WebSubController extends Controller
                     'podcast_id' => $podcast->id,
                     'is_published_on_hubs' => false,
                 ])
-                ->where('`published_at` <= NOW()', null, false)
+                ->where('`published_at` <= UTC_TIMESTAMP()', null, false)
                 ->update();
         }
     }
-- 
GitLab