From 2284894e587fdd22fb3bfe881bbc5499d54212a8 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 17 Nov 2026 20:56:16 -0500 Subject: [PATCH] Time zones: an agent who works away from the company picks My time zone in Account Preferences, and the calendar, the ticket's booking, the Schedule window, New Event, Edit and the event quick look are on their own clock with a note saying so, while bookings stay in the company's time; their booking emails give their time with the company's beside it; database 3.8.6 adds user_settings.user_config_timezone; 26.11.9 changelog entries --- CHANGELOG.md | 4 +- admin/database_updates/3.8.6.php | 24 ++ agent/ajax.php | 23 +- agent/calendar.php | 7 +- agent/js/calendar.js | 11 + agent/modals/calendar/calendar_event.php | 2 +- agent/modals/calendar/calendar_event_add.php | 4 + agent/modals/calendar/calendar_event_form.php | 7 + agent/modals/ticket/ticket_edit_schedule.php | 6 +- agent/modals/ticket/ticket_helper.php | 6 +- agent/post/event.php | 5 +- agent/post/ticket.php | 8 +- agent/post/ticket_helper.php | 3 +- agent/user/post/profile.php | 1 + agent/user/user_preferences.php | 6 +- db.sql | 1 + functions.php | 1 + functions/ticket.php | 17 +- functions/ticket_helpers.php | 5 +- functions/user_timezone.php | 247 ++++++++++++++++++ 20 files changed, 357 insertions(+), 31 deletions(-) create mode 100644 admin/database_updates/3.8.6.php create mode 100644 functions/user_timezone.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a97c61bf..7c1674f4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's nineteen database changes (3.6.6 to 3.8.5) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, two columns on agents' settings for their calendar color and what their calendar shows, and a table for the agents helping on a ticket, and change nothing that is there. Nothing else is required. This release has eleven security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's twenty database changes (3.6.6 to 3.8.6) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, and a table for the agents helping on a ticket, and change nothing that is there. Nothing else is required. This release has eleven security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. ### Security @@ -107,6 +107,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Calendar: what you have shown - calendars, sources, Whose and the view - is kept to your account, so the calendar opens the same way on every computer and phone. The first time, it opens on your own calendar. With Whose set to Everyone, To schedule lists everyone's open tickets that aren't booked, with who has each. From Mountaineer IT's build of ITFlow. - Tickets: more than one agent can work a ticket. Under Assigned to on the ticket, Additional agents adds others to help, while the ticket stays assigned to its lead. Each helper is booked at the same time as the lead - moving and cancelled with the lead's booking - at a time of their own, or not booked. A helper finds the ticket under Mine and on the dashboard, is emailed the client's replies as the lead is, and is sent their own booking with a calendar file that doesn't replace the lead's. The client's emails stay about the lead's booking. Click a helper to change their booking or take them off. From Mountaineer IT's build of ITFlow. - Tickets: the tickets list and board show +1, +2 after the lead when others are helping - Helping when one of them is you. A helper's booking is on the calendar in their color, can be dragged to a time of their own, shows in their calendar link, and counts when someone books them for something else at the same time. From Mountaineer IT's build of ITFlow. +- Time zones: an agent who works away from the company can pick My time zone under Account > Preferences. The calendar, the ticket's booking, the Schedule window, New Event and Edit, and the event's quick look are then on their own clock, with a note saying so, and their booking emails give their time with the company's beside it. Bookings are still kept in the company's time, so the client's emails and calendar files, and everyone else's view, don't change. From Mountaineer IT's build of ITFlow. ### Bug Fixes @@ -233,6 +234,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Database 3.8.3: `recurring_tickets.recurring_ticket_by_day` and `calendar_events.event_repeat_by_day`, an RFC 5545 BYDAY value (`3WE`, `-1FR`; NULL is the same date) - `byDayReady()` and the helpers in `functions/by_day.php`: `byDayRule()`, `byDayDate($year, $month, $rule)`, `byDayText()`, `byDayOptions($date)` (the rules a date can take), `byDayForDate()` (a posted rule, kept when the date takes it), `byDayFollow()` (a rule carried to a moved date) and `byDayField()`, the Repeats on picker filled by `js/repeat_on.js`, which posts `repeat_on` with `repeat_on_field`. `recurringTicketNextRun()` takes `$by_day` for month-based frequencies, passed by every caller, and `recurringTicketByDaySql()` saves it for `add_recurring_ticket`, `edit_recurring_ticket`, the bulk next run and `recurring_tickets/create` and `update` (`repeat_on`). `calendarEventFormSet()` saves `event_repeat_by_day` from `repeat_on`, or follows `repeat_on_current`; `expandRecurringEvent()`, `calendarRepeatText()` and `icsRepeatToRrule($repeat, $interval, $until, $all_day, $timezone, $by_day, $start)` (BYDAY, with BYMONTH for yearly) use it, through `calendarEventByDay()`. `events/create` and `update` take `event_repeat_by_day`. From Mountaineer IT's build of ITFlow. - Database 3.8.4: `user_settings.user_config_calendar_color` (NULL is `calendarAgentDefaultColor()`, one of `CALENDAR_AGENT_COLORS` by user id) and `user_config_calendar_state` (JSON, `all` and `client`) - `calendarAgentSettingsReady()`. `calendarAgentColor()`, `calendarAgentColors()`, `calendarFirstName()`; `calendarAgentColorField()` (Account > Preferences, Admin > Users' Edit) posts `calendar_color` and `calendar_color_auto`, saved by `calendarAgentColorSave()` in `edit_your_user_preferences` and `edit_user`. The tickets source colors each booking by `ticket_assigned_to` and adds `agent_name` and `agent_full` (the name leaves `detail`); `calendarEventItems()` ends with `calendarEventItemsAgents()`, which colors an event by its attendee agents and leaves out of one agent's calendar an event assigned only to others. `calendarEventAgents()`, `calendarEventAgentChoices()`, `calendarEventDefaultAgents()` (New Event's `agent_id`), `calendarEventSetAgents()` and `calendarEventAgentsText()`; `assign_event` (`agent/post/event.php`) is the quick look's. `calendarLeftBehindSql()` and `calendarLeftBehindTickets()` behind `ajax.php?calendar_left_behind`, and items left behind get `itflow-cal-left-behind`. `ajax.php` `calendar_state` saves through `calendarUserStateSave()` and `calendarCleanState()` (`CALENDAR_VIEWS`); `agent/calendar.php` reads `calendarUserState()` into `data-saved-state`, which `agent/js/calendar.js` prefers to `localStorage`. `calendar_unscheduled` takes `user_id` 0 as everyone's, with `agent`. The `holidays` source reads `business_holidays`. The `timeGridSevenDays` view and `slotEventOverlap: false`. From Mountaineer IT's build of ITFlow. - Database 3.8.5: `ticket_helpers` (`ticket_id`, `user_id`, `follows_lead`, `schedule_start`, `schedule_end`, `added_by`, `added_at`; the lead stays `ticket_assigned_to`) - `functions/ticket_helpers.php`: `ticketHelpersReady()`, `ticketHelpers()`, `ticketHelperNames()`, `ticketHelpersTidy()` (a row for whoever is now the lead is cleared once a request, its booking cancelled and `ticketHelperLeadInvite()` sent), `ticketAssignedSql()` (Mine, the assigned filter and the dashboard's My tickets), `ticketHelperSave()`, `ticketHelperRemove()`, `ticketHelperMail()` (`ticketAgentEmailContent()`'s new `helper` kind; its own UID, `ticketHelperUid()`), `ticketHelpersLeadMoved()` from `ticketSetSchedule()` (their clashes join its conflicts), `ticketHelpersLeadCancelled()` from `ticketCancelSchedule()`, `ticketHelpersMailReplied()` from `ticketMailAssigneeReplied()`, `ticketHelperCalendarItems()` (kind `helper`, in the tickets source), `ticketHelperFeedItems()`, `ticketHelperDashboardItems()` and `ticketHelperConflicts()` (in `ticketScheduleConflicts()`). Helpers are `ticketMentionAgents()`. `agent/modals/ticket/ticket_helper.php`, `agent/post/ticket_helper.php` (`save_ticket_helper`, `remove_ticket_helper`), `ticketHelpersBadge()` in the list and board, and `calendar_move` with `kind` `helper` (their own time). From Mountaineer IT's build of ITFlow. +- Database 3.8.6: `user_settings.user_config_timezone` (NULL is the company's) - `functions/user_timezone.php`: `timezoneUsersReady()`, `timezoneOwn()`, `timezoneOf()`, `timezoneView()`, `timezoneShifted()`, `timezoneConvert()`, `timezoneToView()` and `timezoneFromView()`; `timezoneField()` and `timezoneSave()` (`edit_your_user_preferences`, posting `timezone`). Times go out on the viewer's clock and come back in the company's: `calendar_items` and `calendar_day` turn the days asked for with `timezoneFromView()` and the items with `timezoneItems()`, `calendar_move` takes `timezoneMovePost()`, `add_event` and `edit_event` take `timezoneEventPost()`, `edit_ticket_schedule`, `add_ticket` and `save_ticket_helper` turn `scheduled_date_time` and `schedule` back, and the event form, Schedule window and helper window show `timezoneToView()` with `timezoneFormHint()`. `ticketScheduleShortText()` is on the viewer's clock with `timezoneAbbr()`; `timezoneEventWhenText()` is the quick look's; `agent/calendar.php` has `data-zone` and `timezoneNote()`, and `agent/js/calendar.js` sets `now` from it. `ticketMailSchedule($row, $cal_str, $cancelled, $when_text, $start, $end)` and the helper emails give the agent's time with `timezoneWhenFor()`. From Mountaineer IT's build of ITFlow. ## [26.11.8] diff --git a/admin/database_updates/3.8.6.php b/admin/database_updates/3.8.6.php new file mode 100644 index 000000000..7be3eb060 --- /dev/null +++ b/admin/database_updates/3.8.6.php @@ -0,0 +1,24 @@ + 0; + }; + + if (!$itflow_column('user_settings', 'user_config_timezone')) { + mysqli_query($mysqli, "ALTER TABLE `user_settings` ADD `user_config_timezone` varchar(64) DEFAULT NULL AFTER `user_config_calendar_state`"); + } diff --git a/agent/ajax.php b/agent/ajax.php index 038a7dbd4..ab8a6cc84 100644 --- a/agent/ajax.php +++ b/agent/ajax.php @@ -2566,13 +2566,16 @@ if (isset($_GET['calendar_items'])) { } $opts = ['client_id' => $client_id, 'user_id' => intval($_GET['user_id'] ?? 0)]; + // The days asked for are on the viewer's clock, and so are the times sent back (functions/user_timezone.php) + [$from, $to] = [timezoneFromView($from), timezoneFromView($to)]; + $calendar_ids = array_filter(array_map('intval', explode(',', (string) ($_GET['calendars'] ?? '')))); $items = calendarEventItems($calendar_ids, $from, $to, $opts); foreach (array_filter(explode(',', (string) ($_GET['sources'] ?? ''))) as $key) { $items = array_merge($items, calendarSourceItems($key, $from, $to, $opts)); } - echo json_encode($items); + echo json_encode(timezoneItems($items)); exit; } @@ -2594,6 +2597,9 @@ if (isset($_POST['calendar_move'])) { exit; }; + // Dropped on the viewer's clock - as the company's clock reads it (functions/user_timezone.php) + $_POST = timezoneMovePost($_POST); + $start = ticketScheduleValue($_POST['start'] ?? ''); if ($start === '') { $fail('That is not a date and time.'); @@ -2626,7 +2632,7 @@ if (isset($_POST['calendar_move'])) { $onsite = isset($_POST['onsite']) ? intval($_POST['onsite']) : intval($row['ticket_onsite']); $result = ticketSetSchedule($row, $start, $onsite, $end); - echo json_encode(['ok' => true, 'message' => ticketReference($row) . ' scheduled for ' . $result['when_text'], 'conflicts' => $result['conflicts']]); + echo json_encode(['ok' => true, 'message' => ticketReference($row) . ' scheduled for ' . timezoneWhenFor($start, $end, $session_user_id), 'conflicts' => $result['conflicts']]); exit; } @@ -2661,7 +2667,7 @@ if (isset($_POST['calendar_move'])) { if (!$ok) { $fail($message); } - echo json_encode(['ok' => true, 'message' => $helper['user_name'] . ' booked on ' . ticketReference($row) . ' for ' . ticketScheduleWhenText($start, $end), 'conflicts' => $conflicts]); + echo json_encode(['ok' => true, 'message' => $helper['user_name'] . ' booked on ' . ticketReference($row) . ' for ' . timezoneWhenFor($start, $end, $session_user_id), 'conflicts' => $conflicts]); exit; } @@ -2706,7 +2712,7 @@ if (isset($_POST['calendar_move'])) { logAudit("Calendar Event", "Edit", "$session_name moved the event " . escapeSql($event['event_title']) . " to " . escapeSql(calendarWhenText($event)), intval($event['event_client_id']), $event_id); - echo json_encode(['ok' => true, 'message' => $event['event_title'] . ' moved to ' . calendarWhenText($event) . ($sent ? " - the update was emailed to $sent " . ($sent === 1 ? 'person' : 'people') : '')]); + echo json_encode(['ok' => true, 'message' => $event['event_title'] . ' moved to ' . timezoneEventWhenText($event, $event['event_start'], $event['event_end']) . ($sent ? " - the update was emailed to $sent " . ($sent === 1 ? 'person' : 'people') : '')]); exit; } @@ -2813,13 +2819,14 @@ if (isset($_GET['calendar_day'])) { exit; } - $from = "$date 00:00:00"; - $to = "$date 23:59:59"; + // The viewer's day, and its times on their clock (functions/user_timezone.php) + $from = timezoneFromView("$date 00:00:00"); + $to = timezoneFromView("$date 23:59:59"); $opts = ['user_id' => $user_id]; - $items = array_merge( + $items = timezoneItems(array_merge( calendarSourceItems('tickets', $from, $to, $opts), calendarEventItems(array_keys(calendarList()), $from, $to, $opts) - ); + )); $day = []; foreach ($items as $item) { diff --git a/agent/calendar.php b/agent/calendar.php index 3d066935e..a7b02fdb6 100644 --- a/agent/calendar.php +++ b/agent/calendar.php @@ -65,7 +65,8 @@ foreach ($sources as $key => $source) { data-mobile="" data-initial-date="" data-sources="" - data-saved-state=""> + data-saved-state="" + data-zone="">
@@ -169,6 +170,10 @@ foreach ($sources as $key => $source) {
+ + +
+
diff --git a/agent/js/calendar.js b/agent/js/calendar.js index 215edda44..a6d28bc62 100644 --- a/agent/js/calendar.js +++ b/agent/js/calendar.js @@ -32,6 +32,16 @@ const agentSelect = document.getElementById('calendarAgent'); const unscheduledList = document.getElementById('calendarUnscheduled'); const leftBehindList = document.getElementById('calendarLeftBehind'); + // Away from the company's time zone: "now" on the agent's own clock - the server sends their times moved into it + const zone = root.dataset.zone || ''; + function zoneNow() { + const parts = {}; + new Intl.DateTimeFormat('en-CA', {timeZone: zone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'}) + .formatToParts(new Date()).forEach(function (part) { + parts[part.type] = part.value; + }); + return parts.year + '-' + parts.month + '-' + parts.day + 'T' + parts.hour + ':' + parts.minute + ':' + parts.second; + } // ---------- what this browser remembers ---------- @@ -228,6 +238,7 @@ eventOrder: 'allDay,start,-duration,title', // Bookings at the same time sit side by side, never on top of each other slotEventOverlap: false, + now: zone ? zoneNow : undefined, views: { // Side by side past three, the rest go behind "+N more" timeGrid: {eventMaxStack: 3}, diff --git a/agent/modals/calendar/calendar_event.php b/agent/modals/calendar/calendar_event.php index c08937db7..3aea6bb75 100644 --- a/agent/modals/calendar/calendar_event.php +++ b/agent/modals/calendar/calendar_event.php @@ -73,7 +73,7 @@ ob_start();
When
-
+
, from
diff --git a/agent/modals/calendar/calendar_event_add.php b/agent/modals/calendar/calendar_event_add.php index 26964183a..0fdacfea6 100644 --- a/agent/modals/calendar/calendar_event_add.php +++ b/agent/modals/calendar/calendar_event_add.php @@ -41,6 +41,10 @@ if ($all_day) { } elseif ($end === '' || $end <= $start) { $end = date('Y-m-d H:i:s', strtotime($start) + 3600); } +// Picked on the viewer's own clock - kept in the company's (functions/user_timezone.php) +if (!$all_day && ($_GET['start'] ?? '') !== '') { + [$start, $end] = [timezoneFromView($start), timezoneFromView($end)]; +} $form = [ 'event_title' => (string) ($_GET['title'] ?? ''), diff --git a/agent/modals/calendar/calendar_event_form.php b/agent/modals/calendar/calendar_event_form.php index 12da1cf20..a3df7cdf5 100644 --- a/agent/modals/calendar/calendar_event_form.php +++ b/agent/modals/calendar/calendar_event_form.php @@ -18,6 +18,10 @@ isset($mysqli) || die("Direct file access is not allowed"); $form_all_day = !empty($form['event_all_day']); $form_start_ts = strtotime($form['event_start'] ?? '') ?: strtotime(date('Y-m-d 09:00:00')); $form_end_ts = !empty($form['event_end']) ? (strtotime($form['event_end']) ?: $form_start_ts + 3600) : $form_start_ts + 3600; +// Shown on the viewer's own clock (functions/user_timezone.php) - agent/post/event.php moves it back +if (timezoneShifted() && !$form_all_day) { + [$form_start_ts, $form_end_ts] = [strtotime(timezoneToView(date('Y-m-d H:i:s', $form_start_ts))), strtotime(timezoneToView(date('Y-m-d H:i:s', $form_end_ts)))]; +} $form_repeat = isset(CALENDAR_REPEATS[$form['event_repeat'] ?? '']) ? $form['event_repeat'] : ''; $form_interval = max(1, intval($form['event_repeat_interval'] ?? 1)); $form_calendars = calendarList(); @@ -105,6 +109,9 @@ $form_agents = calendarEventAgentChoices($form_attendees['agents']); >
+ +
+
diff --git a/agent/modals/ticket/ticket_edit_schedule.php b/agent/modals/ticket/ticket_edit_schedule.php index 75f717308..9d6be9eb1 100644 --- a/agent/modals/ticket/ticket_edit_schedule.php +++ b/agent/modals/ticket/ticket_edit_schedule.php @@ -10,7 +10,8 @@ $ticket_id = intval($row['ticket_id']); $ticket_prefix = escapeHtml($row['ticket_prefix']); $ticket_number = intval($row['ticket_number']); -$ticket_scheduled_for = escapeHtml($row['ticket_schedule']); +// On the agent's own clock (functions/user_timezone.php) - edit_ticket_schedule moves it back +$ticket_scheduled_for = escapeHtml(timezoneToView((string) $row['ticket_schedule'])); $ticket_onsite = intval($row['ticket_onsite']); $client_name = escapeHtml($row['client_name']); $client_id = intval($row['ticket_client_id']); @@ -39,8 +40,9 @@ ob_start();
- > + >
+
diff --git a/agent/modals/ticket/ticket_helper.php b/agent/modals/ticket/ticket_helper.php index 5156303eb..e70f83462 100644 --- a/agent/modals/ticket/ticket_helper.php +++ b/agent/modals/ticket/ticket_helper.php @@ -81,7 +81,7 @@ ob_start();
>
@@ -100,7 +100,7 @@ ob_start();
- +
@@ -116,6 +116,8 @@ ob_start();
+ +
diff --git a/db.sql b/db.sql index d10f5b980..047a55e7a 100644 --- a/db.sql +++ b/db.sql @@ -4590,6 +4590,7 @@ CREATE TABLE `user_settings` ( `user_config_calendar_first_day` tinyint(1) NOT NULL DEFAULT 0, `user_config_calendar_color` varchar(7) DEFAULT NULL, `user_config_calendar_state` text DEFAULT NULL, + `user_config_timezone` varchar(64) DEFAULT NULL, `user_config_signature` text DEFAULT NULL, `user_config_theme_dark` tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (`user_id`) diff --git a/functions.php b/functions.php index 8825169e9..fa77fcf6e 100644 --- a/functions.php +++ b/functions.php @@ -71,6 +71,7 @@ require_once __DIR__ . '/functions/ticket_fields.php'; require_once __DIR__ . '/functions/by_day.php'; require_once __DIR__ . '/functions/ticket.php'; require_once __DIR__ . '/functions/ticket_helpers.php'; +require_once __DIR__ . '/functions/user_timezone.php'; require_once __DIR__ . '/functions/ticket_status.php'; require_once __DIR__ . '/functions/ticket_template.php'; require_once __DIR__ . '/functions/ticket_template_transfer.php'; diff --git a/functions/ticket.php b/functions/ticket.php index e30fbb0c6..24178fc7b 100644 --- a/functions/ticket.php +++ b/functions/ticket.php @@ -2247,9 +2247,10 @@ function ticketScheduleValue($input) { * The scheduled-work emails, each with the calendar file - the invite, or its * cancellation: to the agent doing the work, and when client notifications * are on (Admin > Ticket) to the contact and the watchers. $row has the - * ticket's id and, for a booking, location_address. + * ticket's id and, for a booking, location_address. With the booking's $start + * and $end, the agent's email has the time on their own clock. */ -function ticketMailSchedule($row, $cal_str, $cancelled, $when_text) { +function ticketMailSchedule($row, $cal_str, $cancelled, $when_text, $start = null, $end = null) { global $config_ticket_client_general_notifications; $ticket = ticketRow($row['ticket_id']); if (!$ticket || !emailReady()) { @@ -2260,7 +2261,7 @@ function ticketMailSchedule($row, $cal_str, $cancelled, $when_text) { $subject = ($cancelled ? 'Ticket Schedule Cancelled' : 'Ticket Scheduled') . " - [$reference] - " . $ticket['ticket_subject']; if ($agent = ticketMailAgent($ticket['ticket_assigned_to'])) { emailQueue([$agent + ['footnote' => "You get this as the agent $reference is assigned to."]], $subject, - ticketAgentEmailContent($ticket, 'scheduled', $opts), ['from' => ticketEmailFrom(), 'cal_str' => $cal_str]); + ticketAgentEmailContent($ticket, 'scheduled', ['when' => $start ? timezoneWhenFor($start, $end, $ticket['ticket_assigned_to']) : $when_text] + $opts), ['from' => ticketEmailFrom(), 'cal_str' => $cal_str]); } if (intval($config_ticket_client_general_notifications) === 1) { ticketMailSend($ticket['ticket_id'], $subject, ticketEmailContent($ticket, 'scheduled', $opts), ['cal_str' => $cal_str]); @@ -2375,12 +2376,16 @@ function ticketScheduleWhenText($start, $end = null) { return date('l, F j, Y, g:ia', $from) . ' - ' . (date('Y-m-d', $from) === date('Y-m-d', $to) ? date('g:ia', $to) : date('l, F j, Y, g:ia', $to)); } -/** "Oct 20, 2026 · 1:00 PM - 3:00 PM", for the ticket page. */ +/** "Oct 20, 2026 · 1:00 PM - 3:00 PM", for the ticket page - on the viewer's own clock, with its zone, when they work away from the company's. */ function ticketScheduleShortText($start, $end = null) { $end = ticketScheduleEnd($start, $end); + $zone = ''; + if (timezoneShifted()) { + [$start, $end, $zone] = [timezoneToView($start), timezoneToView($end), ' ' . timezoneAbbr(timezoneView())]; + } $from = strtotime($start); $to = strtotime($end); - return date('M j, Y · g:i A', $from) . ' - ' . (date('Y-m-d', $from) === date('Y-m-d', $to) ? date('g:i A', $to) : date('M j, g:i A', $to)); + return date('M j, Y · g:i A', $from) . ' - ' . (date('Y-m-d', $from) === date('Y-m-d', $to) ? date('g:i A', $to) : date('M j, g:i A', $to)) . $zone; } /* @@ -2471,7 +2476,7 @@ function ticketSetSchedule(array $row, $schedule, $onsite, $end = null) { $mail_row = ticketScheduleRow($ticket_id); $cal_str = ticketScheduleIcs($mail_row, $schedule, $end); $when_text = ticketScheduleWhenText($schedule, $end); - ticketMailSchedule($mail_row, $cal_str, false, $when_text); + ticketMailSchedule($mail_row, $cal_str, false, $when_text, $schedule, $end); // The agents helping at the same time move with it, and are sent the new time (functions/ticket_helpers.php) $conflicts = array_merge($conflicts, ticketHelpersLeadMoved($ticket_id)); diff --git a/functions/ticket_helpers.php b/functions/ticket_helpers.php index 6fab191cc..e43ce8940 100644 --- a/functions/ticket_helpers.php +++ b/functions/ticket_helpers.php @@ -295,7 +295,8 @@ function ticketHelperMail($ticket_id, $user_id, $start, $end, $kind) { $opts = ['lead' => (string) ($ticket['user_name'] ?? ''), 'by' => stripslashes((string) $session_name)]; $cal_str = ''; if ($kind === 'booked') { - $opts['when'] = ticketScheduleWhenText($start, $end); + // On their own clock (functions/user_timezone.php) + $opts['when'] = timezoneWhenFor($start, $end, $user_id); $opts['where'] = (string) ($mail_row['location_address'] ?? ''); $subject = "Ticket Scheduled - [$reference] - " . $ticket['ticket_subject']; $cal_str = createiCalStr($start, $title, mb_substr(strip_tags((string) $ticket['ticket_details']), 0, 100) . ' - ' . ticketAgentUrl($ticket), @@ -332,7 +333,7 @@ function ticketHelperLeadInvite($ticket_id) { $mail_row = ticketScheduleRow($ticket['ticket_id']); $end = ticketScheduleEnd($ticket['ticket_schedule'], $ticket['ticket_schedule_end'] ?? null); emailQueue([$agent + ['footnote' => "You get this as the agent $reference is assigned to."]], $subject, - ticketAgentEmailContent($ticket, 'scheduled', ['when' => ticketScheduleWhenText($ticket['ticket_schedule'], $end), 'where' => (string) ($mail_row['location_address'] ?? '')]), + ticketAgentEmailContent($ticket, 'scheduled', ['when' => timezoneWhenFor($ticket['ticket_schedule'], $end, $ticket['ticket_assigned_to']), 'where' => (string) ($mail_row['location_address'] ?? '')]), ['from' => ticketEmailFrom(), 'cal_str' => ticketScheduleIcs($mail_row, $ticket['ticket_schedule'], $end)]); } diff --git a/functions/user_timezone.php b/functions/user_timezone.php new file mode 100644 index 000000000..1539ef3d8 --- /dev/null +++ b/functions/user_timezone.php @@ -0,0 +1,247 @@ + Settings > Localization, + * includes/inc_set_timezone.php) and bookings and events are kept as clock times + * in it. An agent who works somewhere else picks their own zone in Account > + * Preferences, and the calendar, the booking and event windows, the ticket's + * booking and their own booking emails are on their clock. Nothing stored + * changes: times going out to them are moved into their zone (timezoneToView(), + * timezoneItems()), and times coming back - typed, dropped or dragged - are moved + * back into the company's (timezoneFromView()) before anything else sees them. + * The client's emails, calendar files and clash checks keep to company time. + */ + +/** Whether the 3.8.6 update has run. */ +function timezoneUsersReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + if (defined('CURRENT_DATABASE_VERSION')) { + $version = CURRENT_DATABASE_VERSION; + } else { + $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"); + $version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0'; + } + $ready = version_compare($version, '3.8.6', '>='); + } + return $ready; +} + +/** The company's zone - the one stored times are in. */ +function timezoneCompany() { + return date_default_timezone_get(); +} + +/** An agent's own zone, or '' when they keep to the company's - read once a request. */ +function timezoneOwn($user_id) { + global $mysqli; + static $zones = null; + if ($zones === null) { + $zones = []; + $result = timezoneUsersReady() ? mysqli_query($mysqli, "SELECT user_id, user_config_timezone FROM user_settings WHERE user_config_timezone IS NOT NULL AND user_config_timezone <> ''") : false; + while ($result && $row = mysqli_fetch_row($result)) { + $zones[intval($row[0])] = (string) $row[1]; + } + } + $zone = $zones[intval($user_id)] ?? ''; + return $zone !== '' && $zone !== timezoneCompany() && in_array($zone, timezone_identifiers_list(), true) ? $zone : ''; +} + +/** The zone an agent's times are shown in - their own, else the company's. */ +function timezoneOf($user_id) { + return timezoneOwn($user_id) ?: timezoneCompany(); +} + +/** The zone the signed-in agent sees times in. */ +function timezoneView() { + $user_id = intval($GLOBALS['session_user_id'] ?? 0); + return $user_id ? timezoneOf($user_id) : timezoneCompany(); +} + +/** Is a zone (the viewer's by default) away from the company's? */ +function timezoneShifted($zone = null) { + return ($zone ?? timezoneView()) !== timezoneCompany(); +} + +/* + * A clock time moved from one zone to another, in the shape it came in + * ('Y-m-d H:i:s', 'Y-m-d H:i', or with a T). A date alone, or anything else, + * comes back as it was. + */ +function timezoneConvert($value, $from, $to) { + $value = (string) $value; + if ($from === $to || !preg_match('/^(\d{4}-\d{2}-\d{2})([ T])(\d{2}:\d{2})(:\d{2})?$/', $value, $m)) { + return $value; + } + try { + $date = new DateTime($m[1] . ' ' . $m[3] . ($m[4] ?? ''), new DateTimeZone($from)); + $date->setTimezone(new DateTimeZone($to)); + } catch (Throwable $e) { + return $value; + } + return $date->format('Y-m-d') . $m[2] . $date->format(isset($m[4]) && $m[4] !== '' ? 'H:i:s' : 'H:i'); +} + +/** A stored (company) time as the viewer's clock reads it. */ +function timezoneToView($value, $zone = null) { + return timezoneConvert($value, timezoneCompany(), $zone ?? timezoneView()); +} + +/** A time on the viewer's clock as the company's clock reads it - what is stored. */ +function timezoneFromView($value, $zone = null) { + return timezoneConvert($value, $zone ?? timezoneView(), timezoneCompany()); +} + +/** Calendar items' start and end moved onto the viewer's clock - whole-day ones stay on their dates. */ +function timezoneItems(array $items, $zone = null) { + $zone = $zone ?? timezoneView(); + if (!timezoneShifted($zone)) { + return $items; + } + foreach ($items as $i => $item) { + if (!empty($item['allDay'])) { + continue; + } + foreach (['start', 'end'] as $key) { + if (!empty($item[$key])) { + $items[$i][$key] = timezoneToView($item[$key], $zone); + } + } + } + return $items; +} + +/** Now on the viewer's clock - 'Y-m-d\TH:i:s', for the calendar's now and a datetime field's earliest. */ +function timezoneNow($zone = null) { + try { + return (new DateTime('now', new DateTimeZone($zone ?? timezoneView())))->format('Y-m-d\TH:i:s'); + } catch (Throwable $e) { + return date('Y-m-d\TH:i:s'); + } +} + +/** A zone's short name now - "JST", "PST", or "UTC+09" when it has none. */ +function timezoneAbbr($zone) { + try { + $abbr = (new DateTime('now', new DateTimeZone($zone)))->format('T'); + } catch (Throwable $e) { + return ''; + } + return preg_match('/^[+-]\d/', $abbr) ? 'UTC' . $abbr : $abbr; +} + +/** "Tokyo (JST)" - a zone as people say it. */ +function timezoneName($zone) { + $city = str_replace('_', ' ', substr(strrchr('/' . $zone, '/'), 1)); + $abbr = timezoneAbbr($zone); + return $city . ($abbr !== '' ? " ($abbr)" : ''); +} + +/** The calendar's note when the viewer is away from the company's zone - '' when not. */ +function timezoneNote() { + $zone = timezoneView(); + if (!timezoneShifted($zone)) { + return ''; + } + return '' + . 'Times in ' . escapeHtml(timezoneName($zone)) . ' · company: ' . escapeHtml(timezoneName(timezoneCompany())) . ''; +} + +/** The line under a form's times when the viewer is away from the company's zone - '' when not. */ +function timezoneFormHint() { + $zone = timezoneView(); + if (!timezoneShifted($zone)) { + return ''; + } + return '
Times in ' . escapeHtml(timezoneName($zone)) + . ' - kept in the company\'s time, ' . escapeHtml(timezoneName(timezoneCompany())) . '.
'; +} + +/** A drag or a drop on the calendar (start and end on the viewer's clock) with its times in the company's. Whole days keep their dates. */ +function timezoneMovePost(array $post, $zone = null) { + if (!empty($post['all_day']) || !timezoneShifted($zone)) { + return $post; + } + foreach (['start', 'end'] as $key) { + if (!empty($post[$key]) && is_string($post[$key])) { + $post[$key] = timezoneFromView(trim($post[$key]), $zone); + } + } + return $post; +} + +/** New and Edit Event's day and time fields, typed on the viewer's clock, in the company's. Whole-day events keep their dates. */ +function timezoneEventPost(array $post, $zone = null) { + if (!empty($post['all_day']) || !timezoneShifted($zone)) { + return $post; + } + foreach (['start', 'end'] as $key) { + $date = (string) ($post[$key . '_date'] ?? ($key === 'end' ? ($post['start_date'] ?? '') : '')); + $time = (string) ($post[$key . '_time'] ?? ''); + if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) || !preg_match('/^\d{2}:\d{2}$/', $time)) { + continue; + } + $moved = timezoneFromView("$date $time", $zone); + $post[$key . '_date'] = substr($moved, 0, 10); + $post[$key . '_time'] = substr($moved, 11, 5); + } + return $post; +} + +/** An event's when (calendarWhenText()) on the viewer's clock, with the company's after it when they differ. */ +function timezoneEventWhenText(array $event, $start, $end, $zone = null) { + $zone = $zone ?? timezoneView(); + if (!empty($event['event_all_day']) || !timezoneShifted($zone)) { + return calendarWhenText($event, $start, $end); + } + return calendarWhenText($event, timezoneToView($start, $zone), timezoneToView($end, $zone)) . ' ' . timezoneAbbr($zone) + . ' (' . calendarWhenText($event, $start, $end) . ' ' . timezoneAbbr(timezoneCompany()) . ')'; +} + +/* + * Booked work's when (ticketScheduleWhenText()) on an agent's own clock, with + * the company's after it when they differ - for their booking emails. + */ +function timezoneWhenFor($start, $end, $user_id) { + $company = ticketScheduleWhenText($start, $end); + $zone = timezoneOf($user_id); + if (!timezoneShifted($zone)) { + return $company; + } + return ticketScheduleWhenText(timezoneToView($start, $zone), timezoneToView(ticketScheduleEnd($start, $end), $zone)) . ' ' . timezoneAbbr($zone) + . " ($company " . timezoneAbbr(timezoneCompany()) . ')'; +} + +/** The My time zone field - Account > Preferences. Posts timezone ('' for the company's). Nothing before the update. */ +function timezoneField($user_id, $col = 'col-md-6') { + if (!timezoneUsersReady()) { + return ''; + } + $own = timezoneOwn($user_id); + $html = '
' + . '
' + . '
' + . '
When you work away from the company. The calendar, bookings and your booking emails are on your clock.
'; +} + +/** Save the My time zone field - '' or one it doesn't know is the company's. */ +function timezoneSave($user_id, array $post) { + global $mysqli; + $user_id = intval($user_id); + if (!$user_id || !timezoneUsersReady() || !isset($post['timezone'])) { + return; + } + $zone = (string) $post['timezone']; + $value = in_array($zone, timezone_identifiers_list(), true) && $zone !== timezoneCompany() ? "'" . escapeSql($zone) . "'" : 'NULL'; + mysqli_query($mysqli, "INSERT INTO user_settings SET user_id = $user_id, user_config_timezone = $value ON DUPLICATE KEY UPDATE user_config_timezone = $value"); +}