true,
CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR),
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 15,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
]);
$raw = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (!is_string($raw) || $code !== 200) throw new RuntimeException('Mailchimp is temporarily unavailable.');
$result = json_decode($raw, true);
if (!is_array($result) || ($result['status'] ?? null) === 'error') {
throw new RuntimeException('Mailchimp did not return a template list.');
}
return $result;
}
function PAEmailReviewCode(array $template): string {
$published = (string)($template['publish_code'] ?? '');
return trim($published) !== '' ? $published : (string)($template['code'] ?? '');
}
function PAEmailReviewVersion(array $template): string {
$published = trim((string)($template['publish_code'] ?? '')) !== '';
$content = [PAEmailReviewCode($template)];
foreach (['subject', 'from_email', 'from_name', 'text'] as $field) {
$publishedValue = (string)($template['publish_' . $field] ?? '');
$content[] = $published && $publishedValue !== '' ? $publishedValue : (string)($template[$field] ?? '');
}
return hash('sha256', json_encode($content, JSON_THROW_ON_ERROR));
}
function PAEmailReviewPriority(string $name): array {
$name = strtoupper($name);
if (preg_match('/^TEST(?:\d|IMPORT|TEMPLATE)/', $name)) return [6, 'Test template'];
if (str_contains($name, 'DASHALERT') || str_contains($name, 'DASH_ALERT_ESCALATION')
|| str_contains($name, 'DASH_CONTACT_FOLLOWUP')
|| preg_match('/_(?:1_ALERT|2_CONTACT_REQUEST|3_CONTACT_REQUEST|14_EC_ACKNOWLEDGE)(?:_|$)/', $name)) {
return [1, 'Emergency and contacts'];
}
if (str_contains($name, '_PI_6_CASE_AVAILABLE') || str_contains($name, 'DASH_DETECTIVE_FOLLOWUP')) {
return [2, 'Detective requests'];
}
if (preg_match('/^PA_(?:EC|PA|PI|PC|SC|TU)_/', $name)) return [3, 'Case updates'];
if (str_starts_with($name, 'PA_SHOP_')) return [4, 'Shop and billing'];
return [5, 'Registration and accounts'];
}
function PAEmailReviewSort(array &$names, array $openCounts, array $needsReapproval): void {
usort($names, static function (string $a, string $b) use ($openCounts, $needsReapproval): int {
$aState = ($openCounts[$a] ?? 0) > 0 ? 0 : (!empty($needsReapproval[$a]) ? 1 : 2);
$bState = ($openCounts[$b] ?? 0) > 0 ? 0 : (!empty($needsReapproval[$b]) ? 1 : 2);
if ($aState !== $bState) return $aState <=> $bState;
$priority = PAEmailReviewPriority($a)[0] <=> PAEmailReviewPriority($b)[0];
if ($priority !== 0) return $priority;
if ($aState === 0) {
$openDifference = ($openCounts[$b] ?? 0) <=> ($openCounts[$a] ?? 0);
if ($openDifference !== 0) return $openDifference;
}
return strnatcasecmp($a, $b);
});
}
function PAEmailReviewSync(PDO $db, array $templates): void {
$values = [];
$parameters = [];
foreach ($templates as $template) {
$name = (string)($template['name'] ?? '');
if ($name === '' || strlen($name) > 190) continue;
$values[] = '(?, ?)';
$parameters[] = $name;
$parameters[] = PAEmailReviewVersion($template);
}
if (!$values) return;
$sql = 'INSERT INTO PART_MailchimpTemplateReview (TemplateName, CurrentHash) VALUES '
. implode(', ', $values) . ' ON DUPLICATE KEY UPDATE CurrentHash=VALUES(CurrentHash)';
$db->prepare($sql)->execute($parameters);
}
function PAEmailReviewFakeValue(string $tag): string {
$tag = strtoupper($tag);
$known = [
'CURRENT_YEAR'=>'2026', 'CASEID'=>'999', 'CASENAME'=>'PA-20261007-0000999', 'CASENAME_HTML'=>'PA-20261007-0000999',
'EVENTTIME'=>'2026-10-09 15:00:00',
'EMAILCODE'=>'123456', 'PART_PI_REGISTRATION_CODE'=>'123456',
'PART_PI_REGISTRATION_INVITATION_CODE'=>'DEMO-2026',
'URLRESETLINK'=>'https://example.invalid/reset',
'URLCREATEADMIN'=>'https://example.invalid/admin',
'PARTADMINURL'=>'https://example.invalid/admin',
'PART_PI_REGISTRATION_IOS_LINK'=>'https://example.invalid/ios-app-not-live',
'PART_PI_REGISTRATION_ANDROID_LINK'=>'https://example.invalid/android-app-not-live',
'PART_PI_REGISTRATION_HOURLY_FEE'=>'$75',
'PART_PI_REGISTRATION_FLAT_FEE_TEXT'=>'$200 flat fee',
'TIMERMINUTES'=>'30', 'EVENT_DATE'=>'October 7, 2026',
'SERVICE_END'=>'November 7, 2026',
'TRACKERUSERLASTALERTTIME'=>'October 7, 2026, 10:30 AM',
'TRACKERUSERLASTGPS'=>'29.75, -98.07 (sample coordinates)',
'TRACKERUSER'=>'Alex Example',
'TRACKERUSERHTML'=>'Alex Example',
'TRACKERUSERVEHICLEDESC'=>'Silver sample SUV, Texas plate DEMO-123 (fictional registration)',
'TRACKERUSERVEHICLEDESC_HTML'=>'Silver sample SUV, Texas plate DEMO-123 (fictional registration)',
'ALERTCOORDINATES'=>'29.4241000,-98.4936000 (sample location)',
'ALERTACCURACY'=>'25 meters (sample)',
'NEARBYADDRESS'=>'Downtown San Antonio, TX (sample location)',
'NEARBYADDRESSHTML'=>'Downtown San Antonio, TX (sample location)',
'ALERTMAPURL'=>'https://www.google.com/maps/search/?api=1&query=29.4241%2C-98.4936',
'TRACKERLOCATIONTIME'=>'2026-10-09 15:00:00 UTC (sample time)',
'TRACKERLOCATIONCOORDINATES'=>'29.4241000,-98.4936000 (sample location)',
'TRACKERLOCATIONACCURACY'=>'25 meters (sample)',
'TRACKERLOCATIONADDRESS'=>'Downtown San Antonio, TX (sample location)',
'TRACKERLOCATIONADDRESSHTML'=>'Downtown San Antonio, TX (sample location)',
'TRACKERLOCATIONMAPURL'=>'https://www.google.com/maps/search/?api=1&query=29.4241%2C-98.4936',
'TRACKERUSERADDRESS'=>'123 Example Street, Example City, TX 78258',
'TRACKERUSERADDRESSSTATE'=>'TX',
'PARTBUSINESSADDRESS'=>'123 Example Street, Example City, TX 78258',
'PAPHONECUSTOMERSERVICE'=>'202-555-0148',
'PAPHONEPISERVICE'=>'202-555-0148',
'PAINTERNALSMS'=>'202-555-0148',
'PART_PI_REGISTRATION_ADMIN_PHONE'=>'202-555-0148',
'RESOLUTION'=>'The sample case was resolved safely.',
'CORRECTION_INSTRUCTIONS'=>'Please upload a clearer sample license image.',
'TIMERDETAIL'=>'Please review the pending sample case and respond.',
'STATUS_MESSAGE'=>'Your sample case has been updated.',
'SOURCESTEPTITLE'=>'Notify Primary Contact',
'TIMERTITLE'=>'Action required on sample case',
'CASEINFORMATIONHTML'=>'Case: PA-DEMO-0000001
From Pink Angels Admin: Morgan Example
Recorded (UTC): 2026-10-11 20:00:00
Source: Primary Contact Taylor Example
Information status: REPORTED
The family reports Alex was last seen near the north entrance at 19:30 UTC. This has not been independently verified.
Acknowledge this information separately from your investigation report.',
'STEP_TITLE'=>'New case information from Admin: PA-DEMO-0000001',
'CASEINFORMATIONTEXT'=>'Family contact Taylor Example reports Alex was seen near the north entrance. Reported information, not independently verified.',
'PIUPDATE_TITLE'=>'Investigation update from Detective Jordan Example: PA-20261007-0000999',
'PIUPDATE_TITLE_HTML'=>'Investigation update from Detective Jordan Example: PA-20261007-0000999',
'PIINFORMATIONHTML'=>"Case: PA-20261007-0000999\nDetective: Jordan Example\nRecorded (UTC): 2026-10-12 13:00:00\nSource: Witness Taylor Example\nInformation status: REPORTED\nObserved/reported time (UTC): 2026-10-12 12:50:00\nLocation: 29.75, -98.07\nLocation source: WITNESS_REPORTED\n\nA witness reported a possible sighting. This has not been independently verified.\n\nThe main investigation report and case remain open.",
'PIINFORMATIONTEXT'=>'Detective Jordan Example recorded a witness report of a possible sighting. Unverified information; main report remains open.',
'ALERTSOURCE'=>'Tracker Button', 'SOURCE'=>'Tracker Button',
'DASHALERTTYPE'=>'Kidnapping Alert',
'ACTION'=>'Review the sample case',
'SUBSCRIPTION'=>'Monthly Tracker Service',
'TRACKER'=>'DEMO-TRACKER-001',
'PART_PI_REGISTRATION_COMPANY_AND_LICENSE'=>'Example Detective Agency, License DEMO-1234',
'PILICENSE'=>'DEMO-1234',
];
if (isset($known[$tag])) return $known[$tag];
if (str_contains($tag, 'EMAIL') || $tag === 'USERNAME') return 'alex@example.invalid';
if (str_contains($tag, 'PHONE')) return '202-555-0148';
if (str_contains($tag, 'FIRST') || $tag === 'FNAME') return 'Alex';
if (str_contains($tag, 'LAST') || $tag === 'LNAME') return 'Example';
if (str_contains($tag, 'NAME')) return 'Alex Example';
if (str_contains($tag, 'URL') || str_contains($tag, 'LINK')) return 'https://example.invalid/sample';
return 'Sample ' . ucwords(strtolower(str_replace('_', ' ', $tag)));
}
function PAEmailReviewPreviewText(string $text): string {
$text = preg_replace('/\*\|(IF:[^|]+|END:IF)\|\*/i', '', $text);
$text = preg_replace_callback('/\*\|([^|]+)\|\*/', static fn($m) => PAEmailReviewFakeValue($m[1]), $text);
return preg_replace_callback('/\{\{\s*([A-Za-z0-9_]+)\s*\}\}/', static fn($m) => PAEmailReviewFakeValue($m[1]), $text);
}
function PAEmailReviewPreviewHtml(string $html): string {
if (str_contains($html, 'cid:tracker_alert_map')) {
// The review iframe has no MIME attachments; use a fixed fictional sample map.
$html = preg_replace('/\*\|IF:HASMAP\|\*(.*?)\*\|END:IF\|\*/is', '$1', $html, 1) ?? $html;
$html = preg_replace('/\*\|IF:HASLOCATION\|\*(.*?)\*\|ELSE:\|\*.*?\*\|END:IF\|\*/is', '$1', $html, 1) ?? $html;
$map = @file_get_contents(__DIR__ . '/../assets/img/email-review-sample-map.png');
if (is_string($map) && strlen($map) <= 300000 && str_starts_with($map, "\x89PNG\r\n\x1a\n")) {
$html = str_replace('cid:tracker_alert_map', 'data:image/png;base64,' . base64_encode($map), $html);
$html = str_replace('alt="Map showing the reported tracker alert location"',
'alt="Sample map showing a fictional alert location"', $html);
$html = str_replace('alt="Map of the last reported tracker location"',
'alt="Sample map showing a fictional tracker location"', $html);
} else {
$html = preg_replace('/
]*src="cid:tracker_alert_map"[^>]*>/i',
'Sample map unavailable; the sent email includes a map when alert coordinates are available.', $html) ?? $html;
}
}
$html = preg_replace('/\*\|(IF:[^|]+|END:IF)\|\*/i', '', $html);
$html = preg_replace_callback('/\*\|([^|]+)\|\*/', static function($m) {
$value=htmlspecialchars(PAEmailReviewFakeValue($m[1]), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
return strtoupper($m[1])==='PIINFORMATIONHTML' ? nl2br($value) : $value;
}, $html);
$html = preg_replace_callback('/\{\{\s*([A-Za-z0-9_]+)\s*\}\}/', static fn($m) =>
htmlspecialchars(PAEmailReviewFakeValue($m[1]), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), $html);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('' . $html, LIBXML_NONET);
libxml_clear_errors();
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//script|//form|//iframe|//object|//embed') as $node) {
$node->parentNode->removeChild($node);
}
foreach ($xpath->query('//*') as $node) {
if (!$node->hasAttributes()) continue;
$remove = [];
foreach ($node->attributes as $attribute) {
if (str_starts_with(strtolower($attribute->name), 'on')) $remove[] = $attribute->name;
}
foreach ($remove as $name) $node->removeAttribute($name);
if ($node->hasAttribute('href')) $node->setAttribute('href', '#');
}
return $dom->saveHTML();
}