Diff -- /var/www/vhosts/3dshawn.com/abforge.3dshawn.com/admin_chat.cgi

O Operator
Diff

/var/www/vhosts/3dshawn.com/abforge.3dshawn.com/admin_chat.cgi

added on local at 2026-07-11 18:36:51

Added
+549
lines
Removed
-0
lines
Context
0
unchanged
Blobs
from
to b12413da2345
Restore this content →
Unified diff
Naive LCS-based line diff. Additions in emerald, deletions in rose. Both sides decompressed live from BLOB_STORE.
1#!/usr/bin/perl
2#======================================================================
3# ABForge - Admin Chat
4#
5# Dedicated chat console: list of conversations on the left, thread on
6# the right, reply box at the bottom. Online/offline toggle controls
7# whether the chat widget appears on visitor-facing storefronts.
8#======================================================================
9use strict;
10use warnings;
11
12use lib '/var/www/vhosts/abforge.com/httpdocs';
13use CGI;
14use MODS::Template;
15use MODS::DBConnect;
16use MODS::Login;
17use MODS::ABForge::Config;
18use MODS::ABForge::Wrapper;
19use MODS::ABForge::Admin;
20use MODS::ABForge::Tracking;
21
22my $q = CGI->new;
23my $form = $q->Vars;
24my $auth = MODS::Login->new;
25my $wrap = MODS::ABForge::Wrapper->new;
26my $tfile = MODS::Template->new;
27my $db = MODS::DBConnect->new;
28my $cfg = MODS::ABForge::Config->new;
29my $admin = MODS::ABForge::Admin->new;
30my $tr = MODS::ABForge::Tracking->new;
31my $DB = $cfg->settings('database_name');
32
33$|=1;
34my $userinfo = $auth->login_verify();
35if (!$userinfo) {
36 print "Status: 302 Found\nLocation: /login.cgi\n\n";
37 exit;
38}
39
40my $entry = ($ENV{SCRIPT_NAME} || '') =~ m{/([^/]+)\.cgi$} ? $1 : 'admin_chat';
41
42if ($entry eq 'admin_tracking_action') {
43 # Shared action endpoint used by admin_chat + admin_visitors pages.
44 # Uses its own feature gate (admin_view_traffic) rather than the
45 # primary page's admin_chat gate.
46 $admin->require_admin($userinfo);
47 require MODS::ABForge::Permissions;
48 MODS::ABForge::Permissions->new->require_feature($userinfo, 'admin_view_traffic');
49 _handle_action($q, $form);
50 exit;
51}
52
53$admin->require_admin($userinfo);
54require MODS::ABForge::Permissions;
55MODS::ABForge::Permissions->new->require_feature($userinfo, 'admin_chat');
56
57my $tutorial_mode = ($form->{tutorial} && $form->{tutorial} eq '1') ? 1 : 0;
58
59my $dbh = $db->db_connect();
60my $schema_ready = $tr->schema_ready($db, $dbh, $DB);
61
62my $admin_online = $schema_ready ? $tr->admin_online($db, $dbh, $DB) : 0;
63
64# View filter + search
65my %ok_view = (active=>1, closed=>1, archived=>1, all=>1);
66my $view = $form->{view} || 'active';
67$view = 'active' unless $ok_view{$view};
68my $search = defined $form->{q} ? $form->{q} : '';
69$search =~ s/^\s+|\s+$//g;
70my $search_trim = substr($search, 0, 100);
71
72# Conversation list
73my @chats_raw = $schema_ready ? $tr->admin_chat_list($db, $dbh, $DB,
74 filter => $view, search => $search_trim, limit => 100) : ();
75my $counts = $schema_ready ? $tr->chat_counts_by_status($db, $dbh, $DB)
76 : { active=>0, closed=>0, archived=>0, all=>0 };
77
78sub _h { my $s = shift; $s //= ''; $s =~ s/&/&amp;/g; $s =~ s/</&lt;/g; $s =~ s/>/&gt;/g; $s =~ s/"/&quot;/g; return $s; }
79sub _qs { my $s = shift; $s //= ''; $s =~ s/([^A-Za-z0-9\-_.~])/sprintf('%%%02X', ord($1))/eg; return $s; }
80# Viewer-local timestamp wrapper. Parses YYYY-MM-DD HH:MM:SS (from
81# MODS::Tracking, which doesn't yet surface epoch columns) and emits
82# the portfolio ts-span so window.tzLocalize() rewrites it. If the
83# value is already short-formatted (e.g. "14:18") the wrapper returns
84# it untouched -- no reliable way to backfill an epoch for a bare time.
85sub _acx_ts_wrap {
86 my ($human, $fmt) = @_;
87 $fmt = 'datetime' unless defined $fmt && length $fmt;
88 return '' unless defined($human) && length($human);
89 return _h($human) unless $human =~ /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})/;
90 my ($y, $mo, $d, $h, $mi, $s) = ($1, $2, $3, $4, $5, $6);
91 require Time::Local;
92 my $ep = eval { Time::Local::timelocal($s+0, $mi+0, $h+0, $d+0, $mo-1, $y-1900) } || 0;
93 my $esc = _h($human);
94 return $esc unless $ep;
95 return qq~<span class="ts" data-ts="$ep" data-fmt="$fmt">$esc</span>~;
96}
97
98# Build the ?view=X&q=... fragment so list links keep filter state.
99my $view_qs = '&view=' . $view;
100$view_qs .= '&q=' . _qs($search_trim) if length $search_trim;
101
102my @chats;
103my $selected_chat_id = $form->{chat} || 0;
104$selected_chat_id =~ s/[^0-9]//g;
105
106foreach my $c (@chats_raw) {
107 my $is_selected = ($selected_chat_id && $c->{chat_id} eq $selected_chat_id) ? 1 : 0;
108 $selected_chat_id ||= $c->{chat_id} if !$selected_chat_id;
109
110 # Pull session fingerprint for classification.
111 my $full = $db->db_readwrite($dbh, qq~
112 SELECT id, buyer_account_id FROM `${DB}`.tracking_sessions WHERE id='$c->{session_id}' LIMIT 1
113 ~, $ENV{SCRIPT_NAME}, __LINE__);
114 my $cls = $tr->classify_session($db, $dbh, $DB, $full);
115
116 my $chat_status = $c->{status} || 'open';
117 my $idle = $c->{idle_seconds} || 0;
118 push @chats, {
119 chat_id => $c->{chat_id},
120 session_id => $c->{session_id},
121 label => _h($c->{visitor_label} || ('Visitor #' . $c->{session_id})),
122 platform_meta => _h(($c->{os_name} || '') . ' / ' . ($c->{browser_name} || '')),
123 device => _h($c->{device_type} || ''),
124 current_page => _h($c->{current_page_path} || ''),
125 last_message_at => _acx_ts_wrap($c->{last_message_at}, 'relative'),
126 last_body => _h(substr($c->{last_body} || '', 0, 60)),
127 last_from => $c->{last_from} || '',
128 unread => $c->{unread_for_admin} || 0,
129 href => '/admin_chat.cgi?chat=' . $c->{chat_id} . $view_qs,
130 is_selected => $is_selected,
131 # Buyer classification (guest/lead/customer)
132 status => $cls->{status},
133 status_label => $cls->{status_label},
134 is_customer => $cls->{status} eq 'customer' ? 1 : 0,
135 is_lead => $cls->{status} eq 'lead' ? 1 : 0,
136 is_guest => $cls->{status} eq 'guest' ? 1 : 0,
137 email => _h($cls->{email} || ''),
138 has_email => $cls->{email} ? 1 : 0,
139 total_orders => $cls->{total_orders},
140 ltv_display => '$' . sprintf('%.2f', ($cls->{ltv_cents} || 0) / 100),
141 # Conversation status (open/closed/archived) for visual treatment
142 chat_status => $chat_status,
143 is_open => $chat_status eq 'open' ? 1 : 0,
144 is_closed => $chat_status eq 'closed' ? 1 : 0,
145 is_archived => $chat_status eq 'archived' ? 1 : 0,
146 visitor_online => ($c->{is_online} && $idle < 60) ? 1 : 0,
147 awaiting_reply => (($c->{last_from} || '') eq 'visitor' && $c->{unread_for_admin}) ? 1 : 0,
148 };
149}
150
151# Selected thread + visitor details
152my @thread_rows;
153my $thread = {};
154if ($schema_ready && $selected_chat_id) {
155 # Mark read on view
156 $tr->mark_chat_read($db, $dbh, $DB, $selected_chat_id, 'admin');
157
158 my @msgs = $tr->chat_messages($db, $dbh, $DB, $selected_chat_id, 200);
159 foreach my $m (@msgs) {
160 # HTML-escape first, then linkify URLs. Order matters: escaping
161 # an already-built <a> tag would mangle it; URLs themselves
162 # don't contain HTML-special chars normally, and any that do
163 # (& in querystrings) are correctly &amp;-escaped inside the
164 # href attribute, which is what HTML attribute parsing expects.
165 my $safe = _h($m->{body});
166 $safe =~ s{(https?://[^\s<]+)}{<a href="$1" target="_blank" rel="noopener" style="color:#ffb347;text-decoration:underline">$1</a>}g;
167 push @thread_rows, {
168 id => $m->{id},
169 from_role => $m->{from_role},
170 body => $safe,
171 sent_at => _acx_ts_wrap($m->{sent_at}, 'datetime'),
172 is_admin => ($m->{from_role} eq 'admin') ? 1 : 0,
173 is_visitor => ($m->{from_role} eq 'visitor') ? 1 : 0,
174 is_system => ($m->{from_role} eq 'system') ? 1 : 0,
175 };
176 }
177
178 # Visitor info for the right rail + chat row for status-driven actions
179 my $sess = $db->db_readwrite($dbh, qq~
180 SELECT s.*, c.status AS chat_status FROM `${DB}`.support_chats c
181 JOIN `${DB}`.tracking_sessions s ON s.id = c.session_id
182 WHERE c.id='$selected_chat_id' LIMIT 1
183 ~, $ENV{SCRIPT_NAME}, __LINE__);
184 if ($sess && $sess->{id}) {
185 my $cls = $tr->classify_session($db, $dbh, $DB, $sess);
186 my $chat_status = $sess->{chat_status} || 'open';
187 $thread = {
188 session_id => $sess->{id},
189 label => _h($sess->{visitor_label} || ''),
190 os => _h(($sess->{os_name} || '') . ' ' . ($sess->{os_version} || '')),
191 browser => _h(($sess->{browser_name} || '') . ' ' . ($sess->{browser_version} || '')),
192 device => _h($sess->{device_type} || ''),
193 screen => ($sess->{screen_width} && $sess->{screen_height}) ? ($sess->{screen_width} . 'x' . $sess->{screen_height}) : '',
194 language => _h($sess->{language} || ''),
195 timezone => _h($sess->{timezone} || ''),
196 current_page => _h($sess->{current_page_path} || ''),
197 status => $cls->{status},
198 status_label => $cls->{status_label},
199 is_customer => $cls->{status} eq 'customer' ? 1 : 0,
200 is_lead => $cls->{status} eq 'lead' ? 1 : 0,
201 is_guest => $cls->{status} eq 'guest' ? 1 : 0,
202 email => _h($cls->{email} || ''),
203 has_email => $cls->{email} ? 1 : 0,
204 total_orders => $cls->{total_orders},
205 ltv_display => '$' . sprintf('%.2f', ($cls->{ltv_cents} || 0) / 100),
206 # Conversation status drives which header buttons render.
207 chat_status => $chat_status,
208 is_open => $chat_status eq 'open' ? 1 : 0,
209 is_closed => $chat_status eq 'closed' ? 1 : 0,
210 is_archived => $chat_status eq 'archived' ? 1 : 0,
211 };
212 }
213}
214
215# ---- Concluded-chats summary (last 30 days + today) -----------------
216# Counts every chat that hit status='closed' OR 'archived' (both count
217# as "resolved" -- archive is just an old close). Today's bar always
218# renders even when zero closures so the trend reads honestly. Also
219# pulls the individual chats so the bar drilldown overlay can list
220# them without a follow-up request.
221my @resolved_raw = $schema_ready ? $tr->chats_closed_by_day($db, $dbh, $DB, 30) : ();
222my @resolved_list = $schema_ready ? $tr->chats_closed_list($db, $dbh, $DB, 30) : ();
223my %resolved_by_d = map { $_->{d} => $_ } @resolved_raw;
224my %chats_by_d;
225foreach my $cc (@resolved_list) {
226 my $d = $cc->{d} || '';
227 push @{ $chats_by_d{$d} }, {
228 id => $cc->{id} + 0,
229 hm => $cc->{hm} || '',
230 label => $cc->{label} || ('Visitor #' . $cc->{id}),
231 };
232}
233
234# Build the trailing 30 days from oldest -> newest so the chart reads
235# left-to-right as time-moves-forward.
236my @resolved_days;
237my $resolved_max = 0;
238my $today_count = 0;
239my @short_months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
240# Today's date as a reference point. We walk back 29 days and stop at today.
241my ($t_sec,$t_min,$t_hour,$t_mday,$t_mon,$t_year) = localtime(time);
242require POSIX;
243my $today_epoch = POSIX::mktime(0,0,12,$t_mday,$t_mon,$t_year);
244for (my $i = 29; $i >= 0; $i--) {
245 my $epoch = $today_epoch - ($i * 86400);
246 my @t = localtime($epoch);
247 my $d_iso = sprintf('%04d-%02d-%02d', $t[5]+1900, $t[4]+1, $t[3]);
248 my $d_short = sprintf('%s %d', $short_months[$t[4]], $t[3]); # "May 17"
249 my $n = ($resolved_by_d{$d_iso} && $resolved_by_d{$d_iso}->{n}) || 0;
250 $resolved_max = $n if $n > $resolved_max;
251 $today_count = $n if $i == 0;
252 # Serialise the per-day chat list so the drilldown can read it
253 # from a data-* attribute. Embeds visitor label + close time +
254 # link to the conversation. Strict JSON (double-quoted keys/values
255 # with JSON-escaping) so the JS can JSON.parse it cleanly.
256 my $chats_for_day = $chats_by_d{$d_iso} || [];
257 my @items_json;
258 for my $cc (@$chats_for_day) {
259 my $lbl = $cc->{label};
260 # JSON-escape: backslash, double-quote, control chars
261 $lbl =~ s/\\/\\\\/g;
262 $lbl =~ s/"/\\"/g;
263 $lbl =~ s/\r/\\r/g;
264 $lbl =~ s/\n/\\n/g;
265 $lbl =~ s/\t/\\t/g;
266 my $hm = $cc->{hm} || '';
267 $hm =~ s/[^0-9:]//g;
268 my $cid = $cc->{id} + 0;
269 # Build with sprintf instead of qq~ so a literal '~' in the
270 # visitor label cannot accidentally terminate the heredoc.
271 push @items_json, sprintf('{"id":%d,"hm":"%s","label":"%s"}', $cid, $hm, $lbl);
272 }
273 my $chats_json = '[' . join(',', @items_json) . ']';
274 # HTML-attribute escape the JSON so it's safe inside data-chats='...'.
275 # Single-quote attribute means we only need to escape the apostrophe.
276 $chats_json =~ s/&/&amp;/g;
277 $chats_json =~ s/'/&#39;/g;
278 push @resolved_days, {
279 d_iso => $d_iso,
280 d_short => $d_short,
281 d_label => $d_short,
282 n => $n,
283 is_current => $i == 0 ? 1 : 0,
284 chats_json => $chats_json,
285 };
286}
287# Add a relative-height percent for the bar visual.
288foreach my $r (@resolved_days) {
289 $r->{bar_pct} = $resolved_max ? sprintf('%.1f', ($r->{n} / $resolved_max) * 100) : '0.0';
290}
291my $resolved_total_30d = 0;
292$resolved_total_30d += $_->{n} for @resolved_days;
293# Preserve the old var names so unrelated template branches keep working.
294my $mtd_resolved = $today_count;
295my @resolved_months = @resolved_days;
296my $resolved_total_6mo = $resolved_total_30d;
297
298$db->db_disconnect($dbh);
299
300my $tvars = {
301 user_id => $userinfo->{user_id},
302 schema_ready => $schema_ready ? 1 : 0,
303 schema_missing => $schema_ready ? 0 : 1,
304 admin_online => $admin_online,
305
306 # Monthly resolved-chats summary
307 resolved_months => \@resolved_months,
308 has_resolved_months => scalar(@resolved_months) ? 1 : 0,
309 resolved_total_6mo => $resolved_total_6mo,
310 resolved_mtd => $mtd_resolved,
311 chats => \@chats,
312 has_chats => scalar(@chats) ? 1 : 0,
313 chat_count => scalar(@chats),
314 selected_chat_id => $selected_chat_id || 0,
315 has_selected => $selected_chat_id ? 1 : 0,
316 thread => $thread,
317 has_thread => %$thread ? 1 : 0,
318 thread_rows => \@thread_rows,
319 has_thread_rows => scalar(@thread_rows) ? 1 : 0,
320 tutorial_mode => $tutorial_mode,
321 not_tutorial_mode=> $tutorial_mode ? 0 : 1,
322 # Filter + search state
323 view => $view,
324 is_view_active => $view eq 'active' ? 1 : 0,
325 is_view_closed => $view eq 'closed' ? 1 : 0,
326 is_view_archived => $view eq 'archived' ? 1 : 0,
327 is_view_all => $view eq 'all' ? 1 : 0,
328 search_q => _h($search_trim),
329 has_search => length $search_trim ? 1 : 0,
330 count_active => $counts->{active},
331 count_closed => $counts->{closed},
332 count_archived => $counts->{archived},
333 count_all => $counts->{all},
334};
335
336# Tutorial sample
337if ($tutorial_mode) {
338 $tvars->{admin_online} = 1;
339 $tvars->{count_active} = 3;
340 $tvars->{count_closed} = 12;
341 $tvars->{count_archived} = 48;
342 $tvars->{count_all} = 63;
343 # Sample daily resolved-chats trend (30 trailing days). Numbers
344 # picked to look organic (busier weekdays, quieter weekends) without
345 # spiking off-chart so the bar visual reads naturally in tutorial.
346 my @sample_pattern = (4,6,5,7,3,2,1, 5,8,9,7,6,2,3, 6,7,10,8,9,4,2, 5,9,11,8,7,3,1, 6,12);
347 my @sample_days;
348 my @short_months_tut = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
349 my ($s_sec,$s_min,$s_hour,$s_mday,$s_mon,$s_year) = localtime(time);
350 require POSIX;
351 my $s_today_epoch = POSIX::mktime(0,0,12,$s_mday,$s_mon,$s_year);
352 my $sample_total = 0;
353 my $sample_today = 0;
354 my $sample_max = 0;
355 for (my $i = 29; $i >= 0; $i--) {
356 my $n = $sample_pattern[29 - $i] || 0;
357 my @t = localtime($s_today_epoch - ($i * 86400));
358 my $d_iso = sprintf('%04d-%02d-%02d', $t[5]+1900, $t[4]+1, $t[3]);
359 my $d_short = sprintf('%s %d', $short_months_tut[$t[4]], $t[3]);
360 $sample_total += $n;
361 $sample_today = $n if $i == 0;
362 $sample_max = $n if $n > $sample_max;
363 push @sample_days, {
364 d_iso => $d_iso,
365 d_short => $d_short,
366 d_label => $d_short,
367 n => $n,
368 is_current => $i == 0 ? 1 : 0,
369 chats_json => '[]',
370 };
371 }
372 foreach my $m (@sample_days) {
373 $m->{bar_pct} = $sample_max ? sprintf('%.1f', ($m->{n} / $sample_max) * 100) : '0.0';
374 }
375 $tvars->{resolved_months} = \@sample_days;
376 $tvars->{has_resolved_months} = 1;
377 $tvars->{resolved_total_6mo} = $sample_total;
378 $tvars->{resolved_mtd} = $sample_today;
379 $tvars->{chats} = [
380 { chat_id=>1, session_id=>842, label=>'Visitor #842', platform_meta=>'macOS / Safari', device=>'desktop',
381 current_page=>'/store.cgi?id=1', last_message_at=>'2 min ago',
382 last_body=>'Do these prints come with supports?', last_from=>'visitor',
383 unread=>2, href=>'/admin_chat.cgi?tutorial=1&chat=1', is_selected=>1,
384 status=>'customer', status_label=>'Customer', is_customer=>1, is_lead=>0, is_guest=>0,
385 email=>'rune.caster@example.com', has_email=>1, total_orders=>4, ltv_display=>'$96.00',
386 chat_status=>'open', is_open=>1, is_closed=>0, is_archived=>0, visitor_online=>1, awaiting_reply=>1 },
387 { chat_id=>2, session_id=>841, label=>'Visitor #841', platform_meta=>'Windows / Chrome', device=>'desktop',
388 current_page=>'/store.cgi?id=1&page=catalog', last_message_at=>'18 min ago',
389 last_body=>'Thanks, that worked!', last_from=>'visitor',
390 unread=>0, href=>'/admin_chat.cgi?tutorial=1&chat=2', is_selected=>0,
391 status=>'guest', status_label=>'Guest', is_customer=>0, is_lead=>0, is_guest=>1,
392 email=>'', has_email=>0, total_orders=>0, ltv_display=>'$0.00',
393 chat_status=>'open', is_open=>1, is_closed=>0, is_archived=>0, visitor_online=>0, awaiting_reply=>0 },
394 { chat_id=>3, session_id=>840, label=>'Visitor #840', platform_meta=>'iOS / Safari', device=>'mobile',
395 current_page=>'/store.cgi?id=1&page=about', last_message_at=>'1 h ago',
396 last_body=>'Glad you could help!', last_from=>'admin',
397 unread=>0, href=>'/admin_chat.cgi?tutorial=1&chat=3', is_selected=>0,
398 status=>'lead', status_label=>'Lead', is_customer=>0, is_lead=>1, is_guest=>0,
399 email=>'bench.hammer@example.com', has_email=>1, total_orders=>0, ltv_display=>'$0.00',
400 chat_status=>'open', is_open=>1, is_closed=>0, is_archived=>0, visitor_online=>0, awaiting_reply=>0 },
401 ];
402 $tvars->{has_chats} = 1;
403 $tvars->{chat_count} = 3;
404 $tvars->{selected_chat_id} = 1;
405 $tvars->{has_selected} = 1;
406 $tvars->{thread} = {
407 session_id=>842, label=>'Visitor #842',
408 os=>'macOS 14.4', browser=>'Safari 17.4', device=>'desktop',
409 screen=>'2560x1440', language=>'en-US', timezone=>'America/Denver',
410 current_page=>'/store.cgi?id=1',
411 status=>'customer', status_label=>'Customer', is_customer=>1, is_lead=>0, is_guest=>0,
412 email=>'rune.caster@example.com', has_email=>1, total_orders=>4, ltv_display=>'$96.00',
413 chat_status=>'open', is_open=>1, is_closed=>0, is_archived=>0,
414 };
415 $tvars->{has_thread} = 1;
416 $tvars->{thread_rows} = [
417 { id=>1, from_role=>'visitor', body=>'Hi! Quick question about the Dragon Lord MK-II.', sent_at=>'14:18', is_admin=>0, is_visitor=>1, is_system=>0 },
418 { id=>2, from_role=>'admin', body=>'Hey! Happy to help -- what is the question?', sent_at=>'14:19', is_admin=>1, is_visitor=>0, is_system=>0 },
419 { id=>3, from_role=>'visitor', body=>'Do these prints come with supports?', sent_at=>'14:20', is_admin=>0, is_visitor=>1, is_system=>0 },
420 { id=>4, from_role=>'visitor', body=>'And what layer height did you test at?', sent_at=>'14:20', is_admin=>0, is_visitor=>1, is_system=>0 },
421 ];
422 $tvars->{has_thread_rows} = 1;
423 $tvars->{schema_ready} = 1;
424 $tvars->{schema_missing} = 0;
425}
426
427print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
428
429my $body = join('', $tfile->template('abforge_admin_chat.html', $tvars, $userinfo));
430
431$wrap->render({
432 userinfo => $userinfo,
433 page_key => 'admin_chat',
434 title => 'Admin &middot; Chat',
435 body => $body,
436});
437
438#======================================================================
439# admin_tracking_action entry: shared POST handler for admin_chat and
440# admin_visitors (chat send, push link, online toggle, close/archive/reopen).
441#======================================================================
442sub _handle_action {
443 my ($q, $form) = @_;
444
445 my $admin_id = $userinfo->{user_id};
446 $admin_id =~ s/[^0-9]//g;
447
448 my $act = $form->{act} || '';
449 my $back_to = $form->{back_to} || '';
450
451 my $dbh = $db->db_connect();
452 unless ($tr->schema_ready($db, $dbh, $DB)) {
453 $db->db_disconnect($dbh);
454 _act_back($back_to, '?err=schema');
455 return;
456 }
457
458 if ($act eq 'send_message') {
459 my $chat_id = $form->{chat_id}; $chat_id =~ s/[^0-9]//g;
460 my $body = $form->{body} || '';
461 if ($chat_id && length $body) {
462 $tr->post_chat_message($db, $dbh, $DB,
463 chat_id => $chat_id,
464 from_role => 'admin',
465 admin_user_id => $admin_id,
466 body => $body,
467 );
468 }
469 $db->db_disconnect($dbh);
470 _act_back($back_to, '?chat=' . ($chat_id || ''));
471 return;
472 }
473
474 if ($act eq 'push_link') {
475 my $sid = $form->{session_id}; $sid =~ s/[^0-9]//g;
476 my $url = $form->{url} || '';
477 my $label = $form->{label} || '';
478 if ($sid && length $url) {
479 $tr->push_link($db, $dbh, $DB,
480 session_id => $sid,
481 admin_user_id => $admin_id,
482 url => $url,
483 label => $label,
484 open_mode => $form->{open_mode} || 'new_tab',
485 );
486 }
487 $db->db_disconnect($dbh);
488 if ($back_to eq 'chat') {
489 my $chat_id = $form->{chat_id} || '';
490 $chat_id =~ s/[^0-9]//g;
491 _act_back('chat', '?chat=' . $chat_id . '&ok=pushed');
492 } else {
493 _act_back('visitors', '?id=' . $sid . '&ok=pushed');
494 }
495 return;
496 }
497
498 if ($act eq 'toggle_online') {
499 my $value = $form->{value};
500 $value = ($value && $value eq '1') ? 1 : 0;
501 $tr->set_admin_online($db, $dbh, $DB, $value, $admin_id);
502 $db->db_disconnect($dbh);
503 _act_back('chat', '');
504 return;
505 }
506
507 if ($act eq 'close_chat') {
508 my $chat_id = $form->{chat_id}; $chat_id =~ s/[^0-9]//g;
509 if ($chat_id) {
510 $tr->close_chat_by_admin($db, $dbh, $DB, $chat_id, $admin_id);
511 }
512 $db->db_disconnect($dbh);
513 # Land on the Closed view with this chat selected -- otherwise it
514 # vanishes from the default Active list and looks broken.
515 _act_back('chat', '?view=closed&chat=' . ($chat_id || ''));
516 return;
517 }
518
519 if ($act eq 'archive_chat') {
520 my $chat_id = $form->{chat_id}; $chat_id =~ s/[^0-9]//g;
521 if ($chat_id) {
522 $tr->archive_chat_by_admin($db, $dbh, $DB, $chat_id, $admin_id);
523 }
524 $db->db_disconnect($dbh);
525 _act_back('chat', '?view=archived&chat=' . ($chat_id || ''));
526 return;
527 }
528
529 if ($act eq 'reopen_chat') {
530 my $chat_id = $form->{chat_id}; $chat_id =~ s/[^0-9]//g;
531 if ($chat_id) {
532 $tr->reopen_chat_by_admin($db, $dbh, $DB, $chat_id, $admin_id);
533 }
534 $db->db_disconnect($dbh);
535 _act_back('chat', '?view=active&chat=' . ($chat_id || ''));
536 return;
537 }
538
539 $db->db_disconnect($dbh);
540 _act_back($back_to, '?err=unknown_act');
541}
542
543sub _act_back {
544 my ($where, $qs) = @_;
545 my $loc = ($where eq 'visitors') ? '/admin_visitors.cgi'
546 : ($where eq 'chat') ? '/admin_chat.cgi'
547 : '/admin_chat.cgi';
548 print "Status: 302 Found\nLocation: $loc$qs\n\n";
549}