loa.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * LOA signing page
  5. * Mirrors contracts.php features but reads/writes under /loa and uses "Authorisation" wording.
  6. */
  7. error_reporting(E_ALL);
  8. ini_set("display_errors", 0);
  9. ini_set("log_errors", 1);
  10. date_default_timezone_set("Australia/Hobart");
  11. ini_set("default_charset", "UTF-8");
  12. mb_internal_encoding("UTF-8");
  13. require_once __DIR__ . "/Parsedown.php";
  14. require_once __DIR__ . '/ParsedownExtra.php';
  15. require_once __DIR__ . "/dompdf/autoload.inc.php";
  16. require_once __DIR__ . '/../vendor/autoload.php'; // for setasign/fpdf & setasign/fpdi
  17. use PHPMailer\PHPMailer\PHPMailer;
  18. use PHPMailer\PHPMailer\SMTP;
  19. use PHPMailer\PHPMailer\Exception as MailerException;
  20. require_once __DIR__ . "/../internal/phpmailer/src/Exception.php";
  21. require_once __DIR__ . "/../internal/phpmailer/src/PHPMailer.php";
  22. require_once __DIR__ . "/../internal/phpmailer/src/SMTP.php";
  23. // at the top, before any output
  24. if (session_status() !== PHP_SESSION_ACTIVE) session_start();
  25. if ($_SERVER["REQUEST_METHOD"] === "POST") {
  26. $ok = isset($_POST["csrf"], $_SESSION["csrf"]) && hash_equals($_SESSION["csrf"], $_POST["csrf"]);
  27. if (!$ok) {
  28. http_response_code(403);
  29. exit("Invalid CSRF token");
  30. }
  31. }
  32. if (empty($_SESSION["csrf"])) {
  33. $_SESSION["csrf"] = bin2hex(random_bytes(32));
  34. }
  35. $csrf = $_SESSION["csrf"];
  36. // Load optional config
  37. $cfg = @include __DIR__ . "/config.php";
  38. $cfg = is_array($cfg) ? $cfg : [];
  39. // Core settings (can be overridden by config.php)
  40. $CFG = [
  41. "brand_name" => $cfg["dev_name"] ?? "Modulos Design",
  42. "from_email" => $cfg["from_address"] ?? "drafting@modulosdesign.com.au",
  43. "bcc_email" => $cfg["bcc_email"] ?? "drafting@modulosdesign.com.au",
  44. "secret" => $cfg["loa_secret"] ?? ($cfg["admin_secret"] ?? ""),
  45. ];
  46. // Compute base URL
  47. $https = !empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] !== "off";
  48. $scheme = $https ? "https" : "http";
  49. $host = $_SERVER["HTTP_HOST"] ?? "localhost";
  50. $base = rtrim(dirname($_SERVER["SCRIPT_NAME"] ?? ""), "/\\");
  51. $CFG["base_url"] = $scheme . "://" . $host . ($base ? $base . "/" : "/");
  52. /* ----------------------------- helpers ----------------------------- */
  53. function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES, "UTF-8"); }
  54. function getClientIp(): string {
  55. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  56. $parts = array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
  57. foreach ($parts as $ip) {
  58. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) return $ip;
  59. }
  60. foreach ($parts as $ip) if (filter_var($ip, FILTER_VALIDATE_IP)) return $ip;
  61. }
  62. if (!empty($_SERVER['HTTP_X_REAL_IP']) && filter_var($_SERVER['HTTP_X_REAL_IP'], FILTER_VALIDATE_IP)) return $_SERVER['HTTP_X_REAL_IP'];
  63. if (!empty($_SERVER['REMOTE_ADDR']) && filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP)) return $_SERVER['REMOTE_ADDR'];
  64. return "UNKNOWN";
  65. }
  66. function tokenForJob(string $job, string $secret): string { return hash_hmac("sha256", "loa|" . $job, $secret); }
  67. function verifyToken(string $job, string $token, string $secret): bool {
  68. return $secret !== "" && $token !== "" && hash_equals(tokenForJob($job, $secret), $token);
  69. }
  70. /* --------------------------- Front matter --------------------------- */
  71. function _fm_trim_quotes(string $v): string {
  72. $v = trim($v);
  73. if ($v !== "" && $v[0] === "'" && substr($v, -1) === "'") return stripslashes(substr($v, 1, -1));
  74. if ($v !== "" && $v[0] === '"' && substr($v, -1) === '"') return stripslashes(substr($v, 1, -1));
  75. return $v;
  76. }
  77. function parseFrontMatter(string $text): array {
  78. if (function_exists("yaml_parse")) {
  79. $arr = @yaml_parse($text);
  80. return is_array($arr) ? $arr : [];
  81. }
  82. $lines = preg_split('/\R/', rtrim($text));
  83. $root = [];
  84. $stack = [ ["indent" => -1, "ref" => &$root] ];
  85. foreach ($lines as $raw) {
  86. if ($raw === "") continue;
  87. $trimmed = ltrim($raw, " ");
  88. if ($trimmed === "" || $trimmed[0] === "#") continue;
  89. $indent = strlen($raw) - strlen($trimmed);
  90. while (count($stack) > 1 && $indent <= $stack[array_key_last($stack)]["indent"]) {
  91. array_pop($stack);
  92. }
  93. $parent =& $stack[array_key_last($stack)]["ref"];
  94. // List item
  95. if (preg_match('/^-\s*(.*)$/', $trimmed, $m)) {
  96. $val = $m[1];
  97. if (!is_array($parent)) $parent = [];
  98. if ($val === "") {
  99. $parent[] = [];
  100. $stack[] = ["indent" => $indent, "ref" => &$parent[array_key_last($parent)]];
  101. } else {
  102. $parent[] = _fm_trim_quotes($val);
  103. }
  104. continue;
  105. }
  106. // Key: value or Key:
  107. if (preg_match('/^([A-Za-z0-9_.-]+):\s*(.*)$/', $trimmed, $m)) {
  108. $key = $m[1];
  109. $val = $m[2];
  110. if ($val === "") {
  111. if (!isset($parent[$key]) || !is_array($parent[$key])) $parent[$key] = [];
  112. $stack[] = ["indent" => $indent, "ref" => &$parent[$key]];
  113. } else {
  114. $parent[$key] = _fm_trim_quotes($val);
  115. }
  116. }
  117. }
  118. return $root;
  119. }
  120. function getByPath($arr, string $path, $default = "") {
  121. $keys = explode(".", $path);
  122. foreach ($keys as $k) {
  123. if ($k === "") continue;
  124. if (is_array($arr) && array_key_exists($k, $arr)) {
  125. $arr = $arr[$k];
  126. } else {
  127. return $default;
  128. }
  129. }
  130. return $arr;
  131. }
  132. function setByPath(array &$arr, string $path, $value): void {
  133. $keys = explode(".", $path);
  134. $ref =& $arr;
  135. foreach ($keys as $k) {
  136. if ($k === "") continue;
  137. if (!isset($ref[$k]) || !is_array($ref[$k])) $ref[$k] = [];
  138. $ref =& $ref[$k];
  139. }
  140. $ref = $value;
  141. }
  142. function parseFrontMatterForJob(string $job): array {
  143. $safe = preg_match('/^\d{1,10}$/', $job) ? $job : "default";
  144. $path = __DIR__ . "/loa/$safe/" . $safe . ".md";
  145. if (!is_file($path)) $path = __DIR__ . "/loa/default-authorisation.md";
  146. $md = @file_get_contents($path);
  147. if ($md && preg_match('/^\s*---\s*\n(.*?)\n---\s*\n/s', $md, $m)) {
  148. return parseFrontMatter($m[1]);
  149. }
  150. return [];
  151. }
  152. function abs_url(string $rel): string {
  153. $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
  154. $scheme = $https ? 'https' : 'http';
  155. $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
  156. $dir = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
  157. $root = $scheme . '://' . $host . ($dir ? $dir . '/' : '/');
  158. return $root . ltrim($rel, '/');
  159. }
  160. function council_recipients(array $vars, array $cfg): array {
  161. $to = [];
  162. if (!empty($cfg['council_email'])) $to[] = $cfg['council_email'];
  163. $councilName = (string)getByPath($vars, 'property.council', '');
  164. if ($councilName && !empty($cfg['council_map'][$councilName])) {
  165. $to[] = $cfg['council_map'][$councilName];
  166. }
  167. // TODO: if you later store locality/postcode, you can look up by locality too.
  168. return array_values(array_unique(array_filter($to)));
  169. }
  170. /* --------------------- Render LOA Markdown to HTML --------------------- */
  171. function md_to_html(string $md): string {
  172. $pd = class_exists('ParsedownExtra') ? new ParsedownExtra() : new Parsedown();
  173. $pd->setSafeMode(true);
  174. // Optional: $pd->setBreaksEnabled(true); // if you want single newlines as <br>
  175. return $pd->text($md);
  176. }
  177. function loadLoaHtml(string $job, array $overrides = []): string {
  178. $safe = preg_match('/^\d{1,10}$/', $job) ? $job : "default";
  179. $path = __DIR__ . "/loa/$safe/" . $safe . ".md";
  180. if (!is_file($path)) $path = __DIR__ . "/loa/default-authorisation.md";
  181. $md = file_get_contents($path);
  182. // Split front matter and body
  183. $vars = [];
  184. $body = $md;
  185. if (preg_match('/^\s*---\s*\n(.*?)\n---\s*\n(.*)$/s', $md, $m)) {
  186. $front = $m[1];
  187. $body = $m[2];
  188. $vars = parseFrontMatter($front);
  189. }
  190. // Defaults available
  191. $base = [
  192. "dev" => [
  193. "name" => $GLOBALS["cfg"]["dev_name"] ?? "Modulos Design",
  194. "email" => $GLOBALS["cfg"]["dev_email"] ?? "drafting@modulosdesign.com.au",
  195. "phone" => $GLOBALS["cfg"]["dev_phone"] ?? "0402 984 082",
  196. "address" => $GLOBALS["cfg"]["dev_address"] ?? "34 Coplestone St, Scottsdale, Tas 7260",
  197. ],
  198. "client" => [
  199. "name" => "",
  200. "email" => "",
  201. "phone" => "",
  202. "address" => "",
  203. ],
  204. "job" => $safe,
  205. "today" => date("F j, Y"),
  206. ];
  207. // Merge: overrides > front matter > base
  208. $merged = array_replace_recursive($base, $vars, $overrides);
  209. // Flat GET overrides like client_name=...
  210. foreach (["client_name" => "client.name", "client_email" => "client.email", "client_phone" => "client.phone"] as $q => $pathKey) {
  211. if (isset($_GET[$q]) && $_GET[$q] !== "") {
  212. setByPath($merged, $pathKey, (string)$_GET[$q]);
  213. }
  214. }
  215. // Replace [path.to.value] placeholders
  216. $body = preg_replace_callback('/\[([a-zA-Z0-9_.-]+)\]/', function ($m) use ($merged) {
  217. $val = getByPath($merged, $m[1]);
  218. return is_scalar($val) ? (string)$val : "";
  219. }, $body);
  220. // Convert Markdown to HTML (ParsedownExtra supports tables)
  221. return md_to_html($body);
  222. }
  223. /* --------------------------- HTML wrappers --------------------------- */
  224. function headerWithTitle(string $title, ?string $job = null, ?string $preparedDate = null, string $context = "web"): string {
  225. $safeTitle = h($title);
  226. $safeJob = h((string)$job);
  227. $safePreparedDate = h((string)$preparedDate);
  228. $https = !empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] !== "off";
  229. $scheme = $https ? "https" : "http";
  230. $host = $_SERVER["HTTP_HOST"] ?? "localhost";
  231. $dir = rtrim(dirname($_SERVER["SCRIPT_NAME"] ?? ""), "/\\") . "/";
  232. $cssLinks = $context === "web"
  233. ? <<<HTML
  234. <link rel="preconnect" href="https://cdn.jsdelivr.net">
  235. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
  236. <link href="../internal/css/blueprint.css" rel="stylesheet">
  237. <link href="../internal/css/print.css" rel="stylesheet" media="print">
  238. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
  239. <link href="style.css" rel="stylesheet">
  240. HTML
  241. : <<<HTML
  242. <link href="../internal/css/blueprint.css" rel="stylesheet">
  243. <link href="style.css" rel="stylesheet">
  244. <style>
  245. @page { margin: 5mm 10mm 10mm 10mm; }
  246. body { background:#fff;}
  247. .container { max-width: 780px; margin: 0 auto; font-size:0.7rem; }
  248. .shadow-sm { box-shadow: none !important; }
  249. .rounded-3 { border-radius: 0 !important; }
  250. .bg-white { background: #fff !important; }
  251. .d-print-none, .noprint { display: none !important; }
  252. .img-logo { max-height: 40px; }
  253. .page-header { display: table; width: 100%; table-layout: fixed; }
  254. .page-header > .col-4 { display: table-cell; width: 33.333%; vertical-align: middle; padding: 0 8px; }
  255. .page-header .text-start { text-align: left; }
  256. .page-header .text-center { text-align: center; }
  257. .page-header .text-end { text-align: right; }
  258. .compiled-signatures { display: table; width: 100%; table-layout: fixed; margin-top: 1rem; }
  259. .compiled-signatures .compiled-signature { display: table-cell; width: 35%; vertical-align: bottom; padding: 0 8px; }
  260. .compiled-signatures img { max-width: 100%; height: auto; }
  261. table { border-collapse: collapse; width: 100%; margin: 12px 0; }
  262. th, td { border: 1px solid #ddd; padding: 2px 4px; vertical-align: top; }
  263. th { background: #f6f6f6; text-align: left; }
  264. </style>
  265. HTML;
  266. $jsLinks = $context === "web"
  267. ? <<<HTML
  268. <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js"></script>
  269. HTML
  270. : "";
  271. $nav = $context === "web"
  272. ? <<<HTML
  273. <nav class="navbar bg-brown-dark brown-light border-bottom border-body d-print-none" data-bs-theme="dark">
  274. <div class="container-fluid">
  275. <a class="navbar-brand brown-light" href="#">
  276. <img src="../internal/images/blueprint-logo-light.png" alt="Modulos Design" width="30" height="24" class="d-inline-block align-text-top" >
  277. Modulos Design
  278. </a>
  279. </div>
  280. </nav>
  281. HTML
  282. : "";
  283. return <<<HTML
  284. <!doctype html>
  285. <html lang="en">
  286. <head>
  287. <meta charset="utf-8">
  288. <title>{$safeJob} - {$safeTitle}</title>
  289. <meta name="viewport" content="width=device-width, initial-scale=1">
  290. <meta name="robots" content="noindex">
  291. <link rel="shortcut icon" href="../internal/images/blueprint.ico" type="image/x-icon">
  292. <base href="{$scheme}://{$host}{$dir}">
  293. {$cssLinks}
  294. {$jsLinks}
  295. </head>
  296. <body>
  297. {$nav}
  298. <main class="container my-4">
  299. <div class="bg-white p-4 p-md-5 rounded-0 shadow-sm">
  300. <div class="row align-items-center page-header">
  301. <div class="col-12 col-md-4 text-start">
  302. <img class="img-fluid pt-2 img-logo" src="../internal/images/blueprint-full-logo-medium.png" height="100" alt="Modulos Design">
  303. </div>
  304. <div class="col-12 col-md-8 text-end pt-3">
  305. <h3 class="fw-bold mb-1" style="color:#373a3c;">Job: {$safeJob}</h3>
  306. <h4 class="mb-1"><span class="fw-bold text-secondary">{$safePreparedDate}</span></h4>
  307. </div>
  308. </div>
  309. HTML;
  310. }
  311. function footerFor(string $context = "web"): string {
  312. $extra = $context === "web"
  313. ? <<<HTML
  314. <script>
  315. function printDoc(){ window.print(); }
  316. </script>
  317. HTML
  318. : "";
  319. return <<<HTML
  320. </div>
  321. </main>
  322. {$extra}
  323. </body>
  324. </html>
  325. HTML;
  326. }
  327. /* --------------------------- Email helpers --------------------------- */
  328. function salutationFromName(string $fullName): string {
  329. $name = str_replace("\xC2\xA0", " ", $fullName);
  330. $name = trim(preg_replace('/\s+/u', ' ', $name));
  331. if ($name === "") return "there";
  332. $name = preg_replace('/,?\s*(Jr\.?|Sr\.?|II|III|IV|MD|Ph\.?D|Esq\.?|J\.?D\.?|M\.?B\.?A\.?|RN|DDS|DMD)\s*$/iu', '', $name);
  333. $honorifics = '(mr|mrs|ms|miss|mx|dr|prof|sir|dame|lord|lady|hon|rev|fr|father|pastor|rabbi|imam|capt|cpt|gen|col|maj|sgt|officer|chief|coach|pres|sen|rep)';
  334. $name = preg_replace('/^(?:' . $honorifics . ')\.?[\s\x{00A0}]+/iu', '', $name);
  335. while (preg_match('/^' . $honorifics . '\.?[\s\x{00A0}]+/iu', $name)) {
  336. $name = preg_replace('/^' . $honorifics . '(\.?)[\s\x{00A0}]+/iu', '', $name, 1);
  337. }
  338. $tokens = preg_split('/[\s\x{00A0}]+/u', $name);
  339. if (!$tokens) return "there";
  340. foreach ($tokens as $tok) {
  341. $t = rtrim($tok, ".");
  342. if (!preg_match('/^[A-Za-z]\.?$/u', $t)) return $t;
  343. }
  344. return $tokens[0] ?: "there";
  345. }
  346. function email_logo_png_cid(PHPMailer $mail, string $dataUrl, string $alt = "Modulos Design", int $width = 140): string {
  347. if ($dataUrl === "") return "";
  348. $dataUrl = trim($dataUrl);
  349. $prefix = "data:image/png;base64,";
  350. if (stripos($dataUrl, $prefix) !== 0) return "";
  351. $bin = base64_decode(substr($dataUrl, strlen($prefix)), true);
  352. if ($bin === false || $bin === "") return "";
  353. $cid = "logo_" . substr(sha1($bin), 0, 12) . "@modulos";
  354. $mail->addStringEmbeddedImage($bin, $cid, "logo.png", "base64", "image/png");
  355. return '<img src="cid:' . $cid . '" alt="' . h($alt) . '" width="' . (int)$width . '" style="display:block;border:0;outline:0;text-decoration:none;height:auto;">';
  356. }
  357. function email_cta(string $href, string $label): string {
  358. $safeUrl = h($href);
  359. $safeLbl = h($label);
  360. return <<<HTML
  361. <!--[if mso]>
  362. <v:rect xmlns:v="urn:schemas-microsoft-com:vml" href="{$safeUrl}"
  363. style="height:42px;v-text-anchor:middle;width:240px;" stroked="f" fillcolor="#635A4A">
  364. <w:anchorlock/>
  365. <center style="color:#ffffff;font-family:Arial,sans-serif;font-size:16px;line-height:1.6;">{$safeLbl}</center>
  366. </v:rect>
  367. <![endif]-->
  368. <!--[if !mso]><!-- -->
  369. <a href="{$safeUrl}"
  370. style="background:#635A4A;border-radius:0;display:inline-block;padding:12px 24px;color:#ffffff;
  371. text-decoration:none;font-weight:700;font-size:14px;line-height:1.6;mso-hide:all"
  372. target="_blank" rel="noopener">{$safeLbl}</a>
  373. <!--<![endif]-->
  374. HTML;
  375. }
  376. function email_signature_block(string $safeSignatureHtml, string $company = "Modulos Design"): string {
  377. $safeCo = h($company);
  378. return <<<HTML
  379. <div style="font-size:14px;line-height:1.6;margin-top:18px;">
  380. <b>Kind Regards,</b><br><br>{$safeSignatureHtml}<br>
  381. Benjamin Harris<br>{$safeCo}<br>
  382. 0402 984 082 | drafting@modulosdesign.com.au
  383. </div>
  384. HTML;
  385. }
  386. /**
  387. * Reusable frame: preheader + header band + {contentHtml} + footer band
  388. */
  389. function email_frame(string $preheader, string $logoHtml, string $job, string $contentHtml, string $footerNote = "This is an automated message. Please reply to this email if you have any questions."): string {
  390. $safePre = h($preheader);
  391. $safeJob = h($job);
  392. $safeFoot = h($footerNote);
  393. return <<<HTML
  394. <!-- Preheader -->
  395. <div style="display:none;max-height:0;overflow:hidden;opacity:0;mso-hide:all;font-size:0;line-height:0;">{$safePre}</div>
  396. <div style="background:#f6f7fb;padding:24px;font-size:14px;line-height:1.6;">
  397. <table role="presentation" cellspacing="0" cellpadding="0" border="0" align="center" width="600"
  398. style="width:600px;max-width:100%;background:#ffffff;border-radius:8px;overflow:hidden;
  399. font-size:14px;line-height:1.6;font-family:Arial,Helvetica,sans-serif;">
  400. <tr>
  401. <td style="font-size:14px;line-height:1.6;padding:20px 24px;background:#D9CCC1;color:#ffffff;">
  402. <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="font-size:14px;line-height:1.6;">
  403. <tr>
  404. <td style="font-size:14px;line-height:1.6;">{$logoHtml}</td>
  405. <td align="right" style="font-weight:700;font-size:14px;line-height:1.6;">Job #{$safeJob}</td>
  406. </tr>
  407. </table>
  408. </td>
  409. </tr>
  410. {$contentHtml}
  411. <tr>
  412. <td style="padding:12px 24px;background:#28261E;color:#D9CCC1;font-size:14px;line-height:1.6;">
  413. {$safeFoot}
  414. </td>
  415. </tr>
  416. </table>
  417. </div>
  418. HTML;
  419. }
  420. function buildSignedLoaEmail(
  421. string $logoHtml,
  422. string $viewUrl,
  423. string $job,
  424. string $clientName = "",
  425. string $preparedDate = "",
  426. string $company = "Modulos Design",
  427. string $safeSignature = ""
  428. ): array {
  429. $firstName = salutationFromName($clientName);
  430. $firstNameSafe = h($firstName);
  431. $safeUrl = h($viewUrl);
  432. $safeJob = h($job);
  433. $safePrepared = h($preparedDate);
  434. $preparedPart = $preparedDate ? " (prepared {$safePrepared})" : "";
  435. $subject = "{$safeJob} – Copy of Signed Authorisation";
  436. $cta = email_cta($safeUrl, "View Authorisation");
  437. $sig = email_signature_block($safeSignature, $company);
  438. $content = <<<HTML
  439. <tr>
  440. <td style="padding:28px 24px 8px;line-height:1.6;color:#635A4A;font-size:14px;">
  441. <div style="font-size:14px;margin-bottom:8px;line-height:1.6;">Hello {$firstNameSafe},</div>
  442. <div>Thank you for signing the authorisation{$preparedPart}. A copy is attached for your records,
  443. and you can view or download it anytime using the link below:</div>
  444. </td>
  445. </tr>
  446. <tr>
  447. <td align="center" style="padding:20px 24px 8px;font-size:14px;line-height:1.6;">{$cta}</td>
  448. </tr>
  449. <tr>
  450. <td style="padding:8px 24px 24px;font-size:14px;line-height:1.6;color:#635A4A;">
  451. <div>If the button doesn’t work, copy and paste this link into your browser:<br>
  452. <span style="word-break:break-all;color:#635A4A;">{$safeUrl}</span>
  453. </div>
  454. {$sig}
  455. </td>
  456. </tr>
  457. HTML;
  458. $html = email_frame(
  459. "Thank you for signing your authorisation — here’s your copy and access link.",
  460. $logoHtml,
  461. $job,
  462. $content
  463. );
  464. $alt = "Hello {$firstName},\n\nThe authorisation has been signed{$preparedPart}.\n\nView/download: {$viewUrl}\n\nThanks,\n{$company}";
  465. return [$subject, $html, $alt];
  466. }
  467. function buildCouncilRequestEmail(
  468. string $logoHtml,
  469. string $job,
  470. array $vars,
  471. string $loaPublicUrl,
  472. string $company = "Modulos Design",
  473. string $safeSignature = ""
  474. ): array {
  475. $addr = (string)getByPath($vars, 'property.address', '');
  476. $pid = (string)getByPath($vars, 'property.pid', '');
  477. $title = (string)getByPath($vars, 'property.title', '');
  478. $vol = (string)getByPath($vars, 'property.vol', '');
  479. $folio = (string)getByPath($vars, 'property.folio', '');
  480. $owners = (string)getByPath($vars, 'client.name', '');
  481. $prepared = (string)getByPath($vars, 'dates.prepared', date('F j, Y'));
  482. $titleRef = $title ?: trim($vol . '/' . $folio, '/');
  483. $safeAddr = h($addr);
  484. $safePid = h($pid);
  485. $safeTitle = h($titleRef);
  486. $safeOwners= h($owners);
  487. $safeJob = h($job);
  488. $safeDate = h($prepared);
  489. $safeUrl = h($loaPublicUrl);
  490. $safeCo = h($company);
  491. $subject = "Request for Planning & Plumbing Information – {$safeAddr} (PID {$safePid}, Title {$safeTitle}) – Job #{$safeJob}";
  492. $sig = email_signature_block($safeSignature, $company);
  493. $cta = email_cta($safeUrl, "View Signed LOA");
  494. $content = <<<HTML
  495. <tr><td style="padding:22px 24px;color:#222;">
  496. <p>Good day,</p>
  497. <p>We’re requesting planning and plumbing information for:</p>
  498. <table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="border-collapse:collapse;">
  499. <tr><td style="border:1px solid #ddd;padding:8px;font-weight:600;width:160px;">Property Address</td><td style="border:1px solid #ddd;padding:8px;">{$safeAddr}</td></tr>
  500. <tr><td style="border:1px solid #ddd;padding:8px;font-weight:600;">Registered Owner(s)</td><td style="border:1px solid #ddd;padding:8px;">{$safeOwners}</td></tr>
  501. <tr><td style="border:1px solid #ddd;padding:8px;font-weight:600;">PID</td><td style="border:1px solid #ddd;padding:8px;">{$safePid}</td></tr>
  502. <tr><td style="border:1px solid #ddd;padding:8px;font-weight:600;">Title / Volume–Folio</td><td style="border:1px solid #ddd;padding:8px;">{$safeTitle}</td></tr>
  503. <tr><td style="border:1px solid #ddd;padding:8px;font-weight:600;">LOA prepared</td><td style="border:1px solid #ddd;padding:8px;">{$safeDate}</td></tr>
  504. </table>
  505. <p style="margin-top:14px;">Specifically, could you please supply or confirm:</p>
  506. <ul style="margin:0 0 0 18px;padding:0;">
  507. <li>Record of any recent or active Development/Building/Plumbing Applications and associated permit numbers and decisions;</li>
  508. <li>Any additional planning advice or pre-application notes Council considers relevant.</li>
  509. </ul>
  510. <p style="margin-top:14px;">A signed Letter of Authority is attached. You can also view it here:</p>
  511. <div style="margin:10px 0 18px;">{$cta}</div>
  512. <div style="font-size:12px;color:#555;">If the button doesn’t work, copy and paste this link:<br>
  513. <span style="word-break:break-all;color:#635A4A;">{$safeUrl}</span>
  514. </div>
  515. {$sig}
  516. </td></tr>
  517. HTML;
  518. $html = email_frame(
  519. "Request for planning & plumbing information for {$addr}.",
  520. $logoHtml,
  521. $job,
  522. $content,
  523. "Please reply to this email with the requested information or next steps."
  524. );
  525. $alt = "Request for planning & plumbing info\n\n"
  526. . "Address: {$addr}\n"
  527. . "Owners: {$owners}\n"
  528. . "PID: {$pid}\n"
  529. . "Title: {$titleRef}\n"
  530. . "LOA prepared: {$prepared}\n\n"
  531. . "Please provide scheme & zoning, overlays, constraints/easements, stormwater/sewer/water service info, "
  532. . "any recent DA/BA/Plumbing records, and any other relevant advice.\n\n"
  533. . "LOA (view): {$loaPublicUrl}\n\n"
  534. . "Thanks,\n{$company}";
  535. return [$subject, $html, $alt];
  536. }
  537. function getHtmlUrl(string $htmlName): string {
  538. $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
  539. $scheme = $https ? 'https' : 'http';
  540. $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
  541. $dir = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
  542. return $scheme . '://' . $host . ($dir ? $dir : '') . '/' . $htmlName;
  543. }
  544. /* ------------------------------- Routing ------------------------------- */
  545. $job = isset($_REQUEST["job"]) ? preg_replace('/\D+/', '', (string)$_REQUEST["job"]) : "";
  546. $token = $_REQUEST["token"] ?? "";
  547. // Resolve some prepared/derived values
  548. $preparedDate = getByPath(parseFrontMatterForJob($job), "dates.prepared", date("F j, Y"));
  549. if ($_SERVER["REQUEST_METHOD"] === "GET") {
  550. if (!$job || !verifyToken($job, $token, $CFG["secret"])) {
  551. http_response_code(403);
  552. echo "Auth required";
  553. exit;
  554. }
  555. // If a signed file already exists for this job, redirect there
  556. $pattern = __DIR__ . "/loa/{$job}/{$job}_signed_loa*.pdf";
  557. $matches = glob($pattern);
  558. if ($matches) {
  559. usort($matches, fn($a, $b) => filemtime($b) <=> filemtime($a));
  560. $latest = basename($matches[0]);
  561. header("Location: loa/{$job}/" . $latest, true, 302);
  562. exit;
  563. }
  564. // Render unsigned page
  565. $HEADER = headerWithTitle("Unsigned Authorisation", $job, $preparedDate, "web");
  566. $LOA_HTML = loadLoaHtml($job);
  567. echo $HEADER;
  568. echo $LOA_HTML;
  569. // Signature UI (mirrors contracts.php)
  570. ?>
  571. <div id="ui-unsigned">
  572. <form method="post" class="noprint" id="signature_form">
  573. <div id="signature-container">
  574. <div id="canvas-container">
  575. <canvas id="signature-pad" class="signature-pad" width="188" height="58.66"></canvas>
  576. </div>
  577. </div>
  578. <div class="animate slide">
  579. <div id="signature-controls" class="d-flex gap-2 justify-content-center mt-3">
  580. <button id="reset" type="button" class="btn btn-warning rounded-0">Clear</button>
  581. <button data-bs-toggle="modal" data-bs-target="#modal-qr" type="button" class="btn btn-secondary rounded-0">Sign on mobile</button>
  582. <button id="confirm" type="submit" class="btn btn-success rounded-0" disabled>Sign</button>
  583. </div>
  584. </div>
  585. <div class="flow" style="max-width: 330px; margin-inline-start: auto;">
  586. <h3 class="margin-top loading-signed hidden | animate slide" style="color: var(--clr-green-500); font-weight: 700;">Saving authorisation…</h3>
  587. <small class="loading-signed hidden | animate slide delay-16"
  588. style="font-weight: 600; color: var(--clr-blue-700);">
  589. This shouldnt take more than a minute.
  590. </small>
  591. </div>
  592. <input type="hidden" name="csrf" value="<?php echo $csrf; ?>">
  593. <input type="hidden" name="job" value="<?php echo h($job); ?>">
  594. <input type="hidden" name="token" value="<?php echo h($token); ?>">
  595. <input type="hidden" id="client_signature" name="client_signature" />
  596. <input type="hidden" name="client_tz" value="">
  597. </form>
  598. <div class="modal fade" tabindex="-1" id="modal-qr" aria-labelledby="modal-qrLabel" aria-hidden="true">
  599. <div class="modal-dialog modal-dialog-centered">
  600. <div class="modal-content">
  601. <div class="modal-body qr-code-container">
  602. <button id="close-modal-qr" type="button" class="btn-close" data-bs-dismiss="modal-qr" aria-label="Close"></button>
  603. <canvas id="qr-code"></canvas>
  604. </div>
  605. </div>
  606. </div>
  607. </div>
  608. </div>
  609. </div>
  610. </main>
  611. <script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>
  612. <script src="https://cdn.jsdelivr.net/npm/qrious@4.0.2/dist/qrious.min.js"></script>
  613. <script id="loa_script_unsigned" type="module">
  614. signature("#signature-pad");
  615. function signature(selector) {
  616. if (!document.querySelector(selector)) return;
  617. const canvas = document.querySelector(selector);
  618. const sigPad = new SignaturePad(canvas, {
  619. penColor: "hsl(200, 100%, 30%)",
  620. minDistance: 2,
  621. });
  622. resizeCanvas();
  623. if (localStorage.getItem("client_signature_loa_<?php echo h($job); ?>")) {
  624. document.querySelector("#confirm").disabled = false;
  625. }
  626. sigPad.addEventListener("afterUpdateStroke", () => {
  627. let data = sigPad.toDataURL("image/png");
  628. document.querySelector("#client_signature").value = data;
  629. localStorage.setItem("client_signature_loa_<?php echo h($job); ?>", data);
  630. document.querySelector("#confirm").disabled = false;
  631. });
  632. document.querySelector("#reset")?.addEventListener("click", (e) => {
  633. sigPad.clear();
  634. localStorage.removeItem("client_signature_loa_<?php echo h($job); ?>");
  635. document.querySelector("#client_signature").value = null;
  636. document.querySelector("#confirm").disabled = true;
  637. });
  638. document.querySelector("#signature_form").addEventListener("submit", (e) => {
  639. e.target.querySelectorAll(".loading-signed").forEach((el) => el.classList.remove("hidden"));
  640. e.target.querySelector("#canvas-container").classList.add("just-signed");
  641. // allow submit to continue
  642. });
  643. window.onresize = resizeCanvas;
  644. function resizeCanvas() {
  645. const ratio = Math.max(window.devicePixelRatio || 1, 1);
  646. canvas.width = canvas.offsetWidth * ratio;
  647. canvas.height = canvas.offsetHeight * ratio;
  648. canvas.getContext("2d").scale(ratio, ratio);
  649. let data = localStorage.getItem("client_signature_loa_<?php echo h($job); ?>");
  650. if (data) {
  651. sigPad.fromDataURL(data);
  652. document.querySelector("#client_signature").value = data;
  653. }
  654. }
  655. }
  656. </script>
  657. <script>
  658. (function () {
  659. const modal = document.getElementById('modal-qr');
  660. const btnClose = document.getElementById('close-modal-qr');
  661. const canvas = document.getElementById('qr-code');
  662. if (canvas && window.QRious) {
  663. new QRious({
  664. element: canvas,
  665. value: window.location.href,
  666. foreground: 'hsl(200, 30%, 20%)',
  667. padding: 0,
  668. size: 500
  669. });
  670. }
  671. btnClose?.addEventListener('click', function () {
  672. try { if (modal.open) modal.close(); else modal.removeAttribute('open'); } catch (e) { modal.removeAttribute('open'); }
  673. });
  674. modal?.addEventListener('click', function (e) {
  675. const r = modal.getBoundingClientRect();
  676. const inside = e.clientY >= r.top && e.clientY <= r.bottom && e.clientX >= r.left && e.clientX <= r.right;
  677. if (!inside) {
  678. try { modal.close(); } catch (err) { modal.removeAttribute('open'); }
  679. }
  680. });
  681. try {
  682. var tz = Intl.DateTimeFormat().resolvedOptions().timeZone || '';
  683. var tzField = document.querySelector('input[name="client_tz"]');
  684. if (tzField) tzField.value = tz;
  685. } catch (e) {}
  686. })();
  687. </script>
  688. </body>
  689. </html>
  690. <?php
  691. exit;
  692. }
  693. /* ---------------------------------- POST ------------------------------------- */
  694. if ($_SERVER["REQUEST_METHOD"] === "POST") {
  695. if (!hash_equals($_SESSION["csrf"] ?? "", $_POST["csrf"] ?? "")) {
  696. http_response_code(403);
  697. exit("Invalid CSRF");
  698. }
  699. $job = preg_replace('/\D+/', '', (string)($_POST["job"] ?? ""));
  700. $token = (string)($_POST["token"] ?? "");
  701. if (!$job || !verifyToken($job, $token, $CFG["secret"])) { http_response_code(403); exit("Auth required"); }
  702. $jobDir = __DIR__ . "/loa/{$job}";
  703. if (!is_dir($jobDir)) {
  704. mkdir($jobDir, 0775, true);
  705. }
  706. $clientSignature = $_POST["client_signature"] ?? null;
  707. if (!is_string($clientSignature) || strpos($clientSignature, "data:image/png;base64,") !== 0) {
  708. http_response_code(400);
  709. exit("No signature");
  710. }
  711. // Load variables/body again
  712. $LOA_HTML = loadLoaHtml($job);
  713. $vars = parseFrontMatterForJob($job);
  714. // Save signature PNG
  715. $sigData = base64_decode(substr($clientSignature, strlen("data:image/png;base64,")));
  716. if ($sigData === false) { http_response_code(400); exit("Bad signature data"); }
  717. $sigPathRel = "loa/{$job}/{$job}_signature.png";
  718. $sigPathAbs = $jobDir . "/{$job}_signature.png";
  719. file_put_contents($sigPathAbs, $sigData);
  720. // Build compiled signatures block
  721. $clientTz = $_POST["client_tz"] ?? "";
  722. if ($clientTz && in_array($clientTz, timezone_identifiers_list(), true)) {
  723. $tz = new DateTimeZone($clientTz);
  724. $clientDate = (new DateTime("now", $tz))->format("F j, Y \a\t g:i:s A T");
  725. } else {
  726. $clientDate = gmdate("F j, Y \a\t g:i:s A \G\M\T");
  727. }
  728. $clientIp = getClientIp();
  729. $CLIENT_SIGNATURE = '<strong>' . h(getByPath($vars, "client.name", "")) . '</strong>';
  730. $CLIENT_SIGNATURE .= '<div id="date-ip" class="date-ip">'
  731. . '<strong>Signed on:</strong> ' . h($clientDate) . '<br>'
  732. . '<strong>Client IP:</strong> ' . h($clientIp) . '</div>'
  733. . '<img id="sig" src="' . h($sigPathRel) . '" style="max-height: 117px;padding:10px;" alt="Client Signature">';
  734. $compiled = <<<HTML
  735. <div class="row compiled-signatures align-items-start">
  736. <div class="col compiled-signature">{$CLIENT_SIGNATURE}</div>
  737. </div>
  738. <br>
  739. <div class="row download-pdf d-print-none">
  740. <a href="loa/{$job}/{$job}_signed_loa.pdf" download class="btn btn-light rounded-0" id="downloadpdf">Download PDF</a>
  741. </div>
  742. HTML;
  743. // Build final HTML (web and pdf versions)
  744. $headerWeb = headerWithTitle("{$job} - Signed Authorisation", $job, getByPath($vars, "dates.prepared", date("F j, Y")), "web");
  745. $footerWeb = footerFor("web");
  746. $outputWeb = $headerWeb . $LOA_HTML . $compiled . $footerWeb;
  747. $headerPdf = headerWithTitle("{$job} - Signed Authorisation", $job, getByPath($vars, "dates.prepared", date("F j, Y")), "pdf");
  748. $footerPdf = footerFor("pdf");
  749. $outputPdf = $headerPdf . $LOA_HTML . $compiled . $footerPdf;
  750. // Render and save PDF
  751. $options = new \Dompdf\Options();
  752. $options->set('defaultFont', 'Helvetica');
  753. $options->set('isRemoteEnabled', true);
  754. $dompdf = new \Dompdf\Dompdf($options);
  755. $dompdf->loadHtml($outputPdf, "UTF-8");
  756. $dompdf->setPaper("A4", "portrait");
  757. $https = !empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] !== "off";
  758. $scheme = $https ? "https" : "http";
  759. $host = $_SERVER["HTTP_HOST"] ?? "localhost";
  760. $dir = rtrim(dirname($_SERVER["SCRIPT_NAME"] ?? ""), "/\\") . "/";
  761. $dompdf->setBasePath($scheme . "://" . $host . $dir);
  762. $dompdf->render();
  763. $pdfPathRel = "{$job}_signed_loa.pdf";
  764. $pdfPathAbs = __DIR__ . "/loa/{$job}/" . $pdfPathRel;
  765. $pdfPublicRel = "loa/{$job}/{$pdfPathRel}";
  766. file_put_contents($pdfPathAbs, $dompdf->output());
  767. // Email client + dev
  768. $clientEmail = (string)(getByPath($vars, "client.email", "") ?: "");
  769. $devEmail = (string)($cfg["dev_email"] ?? "drafting@modulosdesign.com.au");
  770. $fromAddress = (string)($cfg["from_address"] ?? "drafting@modulosdesign.com.au");
  771. // --- Dorset council PDF + email (only if Dorset is the council) ---
  772. try {
  773. // Guard so we only do this for Dorset; set in your LOA front matter:
  774. // council:
  775. // name: "Dorset Council"
  776. // email: "development@dorset.tas.gov.au"
  777. $councilName = (string) getByPath($vars, 'council.name', '');
  778. $councilEmail = (string) getByPath($vars, 'council.email', '');
  779. if ($councilEmail && stripos($councilEmail, 'tazz.com.au') !== false) { //dorset.tas.gov.au
  780. require_once __DIR__ . '/dorset_fill.php';
  781. $templatePath = __DIR__ . '/loa/dorset_consent_form.pdf';
  782. $dorsetOutAbs = __DIR__ . "/loa/{$job}/{$job}_dorset_consent_form.pdf";
  783. $dorsetPdf = generate_dorset_application($job, $vars, $cfg, $templatePath, $dorsetOutAbs);
  784. if ($dorsetPdf) {
  785. // Email Dorset + BCC dev
  786. $mailCouncil = new PHPMailer(true);
  787. // SMTP (optional but recommended if set in config)
  788. if (!empty($cfg['smtp_host'])) {
  789. $mailCouncil->isSMTP();
  790. $mailCouncil->Host = $cfg['smtp_host'] ?? '';
  791. $mailCouncil->SMTPAuth = true;
  792. $mailCouncil->Username = $cfg['smtp_username'] ?? '';
  793. $mailCouncil->Password = $cfg['smtp_password'] ?? '';
  794. $mailCouncil->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
  795. $mailCouncil->Port = (int)($cfg['smtp_port'] ?? 465);
  796. }
  797. // From/Reply-To
  798. $fromAddress = (string)($cfg['from_address'] ?? 'drafting@modulosdesign.com.au');
  799. $mailCouncil->CharSet = 'UTF-8';
  800. $mailCouncil->Encoding = 'base64';
  801. $mailCouncil->setFrom($fromAddress, $CFG['brand_name'] ?? 'Modulos Design');
  802. if (!empty($cfg['dev_email'])) $mailCouncil->addReplyTo($cfg['dev_email']);
  803. // ✅ REQUIRED: recipient(s)
  804. $mailCouncil->addAddress($councilEmail);
  805. if (!empty($CFG['bcc_email'])) $mailCouncil->addBCC($CFG['bcc_email']);
  806. // Build body using shared template
  807. $logoCouncil = email_logo_png_cid($mailCouncil, $cfg['dark_logo'] ?? "", $CFG['brand_name'] ?? 'Modulos Design', 200);
  808. $sigCouncil = email_logo_png_cid($mailCouncil, $cfg['dev_signature'] ?? "", "Signature", 100);
  809. $loaUrl = abs_url($pdfPublicRel);
  810. [$subject, $html, $alt] = buildCouncilRequestEmail(
  811. $logoCouncil,
  812. $job,
  813. $vars,
  814. $loaUrl,
  815. (string)($CFG['brand_name'] ?? 'Modulos Design'),
  816. $sigCouncil
  817. );
  818. $mailCouncil->isHTML(true);
  819. $mailCouncil->Subject = $subject;
  820. $mailCouncil->Body = $html;
  821. $mailCouncil->AltBody = $alt;
  822. // Attach Dorset form + (optionally) the signed LOA
  823. if (is_file($dorsetPdf)) $mailCouncil->addAttachment($dorsetPdf, basename($dorsetPdf));
  824. if (is_file($pdfPathAbs)) $mailCouncil->addAttachment($pdfPathAbs, basename($pdfPathAbs));
  825. try {
  826. $mailCouncil->send();
  827. } catch (Throwable $e) {
  828. error_log("Council email failed for job {$job} to {$councilEmail}: ".$e->getMessage());
  829. }
  830. }
  831. }
  832. } catch (Throwable $e) {
  833. error_log("Dorset generation error for job {$job}: ".$e->getMessage());
  834. }
  835. // Build the mailer once per recipient (same as contracts.php)
  836. $targets = [];
  837. if ($clientEmail) $targets[] = ["to" => $clientEmail, "kind" => "client"];
  838. if ($devEmail) $targets[] = ["to" => $devEmail, "kind" => "dev"];
  839. foreach ($targets as $t) {
  840. $mail = new PHPMailer(true);
  841. $mail->SMTPDebug = SMTP::DEBUG_OFF;
  842. if (!empty($cfg["smtp_host"])) {
  843. $mail->isSMTP();
  844. $mail->Host = $cfg["smtp_host"] ?? "";
  845. $mail->SMTPAuth = true;
  846. $mail->Username = $cfg["smtp_username"] ?? "";
  847. $mail->Password = $cfg["smtp_password"] ?? "";
  848. $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // 465/SSL
  849. $mail->Port = $cfg["smtp_port"] ?? 465;
  850. }
  851. $mail->CharSet = "UTF-8";
  852. $mail->Encoding = "base64";
  853. $mail->setFrom($fromAddress, $CFG["brand_name"] ?? "Modulos Design");
  854. if ($t["kind"] === "client" && $devEmail) $mail->addReplyTo($devEmail);
  855. if ($t["kind"] === "dev" && $clientEmail)$mail->addReplyTo($clientEmail);
  856. $mail->addAddress($t["to"]);
  857. $mail->isHTML(true);
  858. // Embed assets per message
  859. $logoHtml = email_logo_png_cid($mail, $cfg["dark_logo"] ?? "", $CFG["brand_name"] ?? "Modulos Design", 200);
  860. $safeSignature = email_logo_png_cid($mail, $cfg["dev_signature"] ?? "", "Signature", 100);
  861. [$subject, $html, $alt] = buildSignedLoaEmail(
  862. $logoHtml,
  863. abs_url($pdfPublicRel), // <= FIX: public URL, not the filesystem path
  864. $job,
  865. (string)getByPath($vars, "client.name", ""),
  866. (string)getByPath($vars, "dates.prepared", date("F j, Y")),
  867. (string)($CFG["brand_name"] ?? "Modulos Design"),
  868. $safeSignature
  869. );
  870. // Developer copy extra info
  871. if ($t["kind"] === "dev") {
  872. $subject = $job . " – Authorisation has been signed";
  873. $signedBy = h($clientEmail ?: "unknown");
  874. $inject = '<tr><td style="padding:4px 24px 0;font-size:14px;color:#444;">Signed by: ' . $signedBy . '</td></tr>';
  875. $html = preg_replace('/(<tr>\s*<td[^>]*>.*?<\/td>\s*<\/tr>)/s', '$1' . $inject, $html, 1)
  876. ?: str_replace('</tr><tr>', '</tr>' . $inject . '<tr>', $html);
  877. $alt .= "\n\nSigned by: " . ($clientEmail ?: "unknown");
  878. }
  879. $mail->Subject = $subject;
  880. $mail->Body = $html;
  881. if (!empty($alt)) $mail->AltBody = $alt;
  882. if (!empty($CFG["bcc_email"])) $mail->addBCC($CFG["bcc_email"]);
  883. if (is_file($pdfPathAbs)) $mail->addAttachment($pdfPathAbs, basename($pdfPathAbs));
  884. try {
  885. $mail->send();
  886. } catch (MailerException $e) {
  887. error_log("LOA mailer error to {$t['to']}: {$mail->ErrorInfo}\n");
  888. }
  889. }
  890. // Public URL to the signed LOA (for the link in the email body)
  891. $loaUrl = abs_url($pdfPublicRel);
  892. // Council recipients
  893. $councilTo = council_recipients($vars, $cfg);
  894. foreach ($councilTo as $addr) {
  895. try {
  896. $mail = new PHPMailer(true);
  897. $mail->SMTPDebug = SMTP::DEBUG_OFF;
  898. if (!empty($cfg["smtp_host"])) {
  899. $mail->isSMTP();
  900. $mail->Host = $cfg["smtp_host"] ?? "";
  901. $mail->SMTPAuth = true;
  902. $mail->Username = $cfg["smtp_username"] ?? "";
  903. $mail->Password = $cfg["smtp_password"] ?? "";
  904. $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
  905. $mail->Port = $cfg["smtp_port"] ?? 465;
  906. }
  907. $mail->CharSet = "UTF-8";
  908. $mail->Encoding = "base64";
  909. $mail->setFrom($CFG["from_email"] ?? "drafting@modulosdesign.com.au", $CFG["brand_name"] ?? "Modulos Design");
  910. // Replies come back to you
  911. if (!empty($cfg["dev_email"])) $mail->addReplyTo($cfg["dev_email"]);
  912. $mail->addAddress($addr);
  913. $mail->isHTML(true);
  914. // Embed assets
  915. $logoHtml = email_logo_png_cid($mail, $cfg["dark_logo"] ?? "", $CFG["brand_name"] ?? "Modulos Design", 200);
  916. $safeSignature = email_logo_png_cid($mail, $cfg["dev_signature"] ?? "", "Signature", 100);
  917. // Build council email
  918. [$subject, $html, $alt] = buildCouncilRequestEmail(
  919. $logoHtml,
  920. $job,
  921. $vars,
  922. $loaUrl,
  923. (string)($CFG["brand_name"] ?? "Modulos Design"),
  924. $safeSignature
  925. );
  926. $mail->Subject = $subject;
  927. $mail->Body = $html;
  928. $mail->AltBody = $alt;
  929. if (!empty($CFG["bcc_email"])) $mail->addBCC($CFG["bcc_email"]);
  930. if (is_file($pdfPathAbs)) $mail->addAttachment($pdfPathAbs, basename($pdfPathAbs)); // attach signed LOA
  931. $mail->send();
  932. } catch (MailerException $e) {
  933. error_log("Council mailer error to {$addr}: {$mail->ErrorInfo}\n");
  934. }
  935. }
  936. // Redirect to signed HTML
  937. header("Location: " . $pdfPublicRel, true, 303);
  938. exit;
  939. }