contract.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  1. <?php
  2. /* ##########################
  3. [client_email]
  4. [dev_email]
  5. [dev_signature]
  6. [dev_ip]
  7. [dev_timestamp]
  8. [dev_timestamp_offset]
  9. [dev_name]
  10. [client_name]
  11. ################################### */
  12. //error_reporting(E_ERROR | E_PARSE);
  13. error_reporting(E_ALL);
  14. ini_set("display_errors", 1);
  15. date_default_timezone_set("Australia/Hobart");
  16. ini_set("default_charset", "UTF-8");
  17. mb_internal_encoding("UTF-8");
  18. require_once __DIR__ . "/Parsedown.php";
  19. require_once __DIR__ . "/dompdf/autoload.inc.php";
  20. use PHPMailer\PHPMailer\PHPMailer;
  21. use PHPMailer\PHPMailer\SMTP;
  22. use PHPMailer\PHPMailer\Exception;
  23. require_once "../internal/phpmailer/src/Exception.php";
  24. require_once "../internal/phpmailer/src/PHPMailer.php";
  25. require_once "../internal/phpmailer/src/SMTP.php";
  26. // at the top, before any output
  27. session_start();
  28. if ($_SERVER["REQUEST_METHOD"] === "POST") {
  29. $ok = isset($_POST["csrf"], $_SESSION["csrf"]) && hash_equals($_SESSION["csrf"], $_POST["csrf"]);
  30. if (!$ok) {
  31. http_response_code(403);
  32. exit("Invalid CSRF token");
  33. }
  34. }
  35. if (empty($_SESSION["csrf"])) {
  36. $_SESSION["csrf"] = bin2hex(random_bytes(32));
  37. }
  38. /* ------------------------------- CSRF (same) ---------------------------------- */
  39. $cfg = @include __DIR__ . "/config.php";
  40. $cfg = is_array($cfg) ? $cfg : [];
  41. $csrf = htmlspecialchars($_SESSION["csrf"] ?? "", ENT_QUOTES, "UTF-8");
  42. // Behavior flags
  43. $redirectToSigned = true; // keep this true
  44. $allowSelfDelete = (bool)($cfg['self_delete'] ?? false); // default off
  45. $fromAddress = $cfg["from_address"] ?? "drafting@modulosdesign.com.au";
  46. $clientIdRaw = $_GET['clientid'] ?? '';
  47. $clientId = preg_match('/^[A-Za-z0-9_-]{1,64}$/', $clientIdRaw) ? $clientIdRaw : 'unknown';
  48. $devName = $cfg['dev_name'] ?? 'Modulos Design';
  49. $devEmail = $cfg["dev_email"] ?? 'drafting@modulosdesign.com.au';
  50. $devEmail = preg_replace('/[\r\n]+/', "", $devEmail);
  51. $devSig = $cfg["dev_signature"] ?? "";
  52. $devPhone = $cfg['dev_phone'] ?? '';
  53. $devAddress = $cfg['dev_address'] ?? '';
  54. $clientName = $_GET['client_name'] ?? '';
  55. $clientEmail = $_POST['client_email'] ?? $_GET['client_email'] ?? '';
  56. $clientEmail = trim(preg_replace('/[\r\n]+/', '', (string)$clientEmail)); // strip CRLF + trim
  57. $clientPhone = $_GET['client_phone'] ?? '';
  58. $clientAddress = $_GET['client_address'] ?? '';
  59. // 🔧 Fallback to front matter if still empty
  60. if ($clientEmail === '') {
  61. $meta = parseFrontMatterForId($clientId);
  62. $clientEmailFromMd = '';
  63. if (is_array($meta)) {
  64. // prefer nested client.email, but accept client_email if present
  65. $clientEmailFromMd = (string)(
  66. getByPath($meta, 'client.email', '') ?:
  67. ($meta['client']['email'] ?? '') ?:
  68. ($meta['client_email'] ?? '')
  69. );
  70. }
  71. if ($clientEmailFromMd !== '') {
  72. $clientEmail = trim(preg_replace('/[\r\n]+/', '', $clientEmailFromMd));
  73. }
  74. }
  75. if (is_string($devSig) && $devSig !== '') {
  76. // Can be a data: URL or a normal URL; both are fine
  77. $DEV_SIGNATURE = '<img id="dev_signature" src="' . htmlspecialchars($devSig, ENT_QUOTES, 'UTF-8') . '" style="max-height: 117px;padding: 10px;" alt="Client Relations Signature">';
  78. } elseif (!empty($devSigPath) && is_file($devSigPath)) {
  79. // Fallback: original file-path logic
  80. $abs = realpath($devSigPath) ?: $devSigPath;
  81. $prefix = rtrim($_SERVER["DOCUMENT_ROOT"] ?? "", "/");
  82. $devSigUrl = str_replace($prefix, "", $abs);
  83. if ($devSigUrl === $abs) {
  84. // fallback if the file is outside docroot
  85. $devSigUrl = $abs;
  86. }
  87. $DEV_SIGNATURE = '<img id="dev_signature" src="' . htmlspecialchars($devSigUrl, ENT_QUOTES, "UTF-8") . '" style="max-height: 117px;padding: 10px;" alt="Client Relations Signature">';
  88. }
  89. function loadContractHtml(?string $clientId, array $overrides = []): string {
  90. $safeId = preg_match('/^[A-Za-z0-9_-]{1,64}$/', (string)$clientId) ? (string)$clientId : 'default';
  91. $path = __DIR__ . '/contracts/' . $safeId . '.md';
  92. if (!is_file($path)) $path = __DIR__ . '/contracts/default.md';
  93. $md = file_get_contents($path);
  94. // 1) Split front matter and body
  95. $vars = [];
  96. $body = $md;
  97. if (preg_match('/^\s*---\s*\n(.*?)\n---\s*\n(.*)$/s', $md, $m)) {
  98. $front = $m[1];
  99. $body = $m[2];
  100. $vars = parseFrontMatter($front);
  101. }
  102. // 2) Defaults available to every document
  103. $base = [
  104. 'dev' => [
  105. 'name' => $GLOBALS['devName'] ?? 'Modulos Design',
  106. 'email' => $GLOBALS['devEmail'] ?? 'drafting@modulosdesign.com.au',
  107. 'phone' => $GLOBALS['devPhone'] ?? '',
  108. 'address' => $GLOBALS['devAddress'] ?? '',
  109. ],
  110. 'client' => [
  111. 'name' => $GLOBALS['clientName'] ?? '',
  112. 'email' => $GLOBALS['clientEmail'] ?? '',
  113. 'phone' => $GLOBALS['clientPhone'] ?? '',
  114. 'address' => $GLOBALS['clientAddress'] ?? '',
  115. ],
  116. 'today' => date('F j, Y'),
  117. ];
  118. // 3) Merge: URL or POST overrides > front matter > base
  119. $merged = array_replace_recursive($base, $vars, $overrides);
  120. // 4) Also allow flat GET overrides like client_name=...
  121. foreach (['client_name' => 'client.name', 'client_email' => 'client.email', 'client_phone' => 'client.phone'] as $q => $pathKey) {
  122. if (isset($_GET[$q]) && $_GET[$q] !== '') {
  123. setByPath($merged, $pathKey, (string)$_GET[$q]);
  124. }
  125. }
  126. // 5) Replace [path.to.value] placeholders in the Markdown body
  127. $body = preg_replace_callback('/\[([a-zA-Z0-9_.-]+)\]/', function ($m) use ($merged) {
  128. $val = getByPath($merged, $m[1]);
  129. return is_scalar($val) ? (string)$val : '';
  130. }, $body);
  131. // 6) Convert to HTML
  132. $Parsedown = new Parsedown();
  133. $Parsedown->setSafeMode(true);
  134. return $Parsedown->text($body);
  135. }
  136. function parseFrontMatter(string $text): array {
  137. // If the PECL yaml extension is available, use it
  138. if (function_exists('yaml_parse')) {
  139. $arr = @yaml_parse($text);
  140. return is_array($arr) ? $arr : [];
  141. }
  142. // Minimal indentation-aware parser for nested maps and simple lists
  143. $lines = preg_split('/\R/', rtrim($text));
  144. $root = [];
  145. $stack = [ ['indent' => -1, 'ref' => &$root] ];
  146. foreach ($lines as $raw) {
  147. if ($raw === '') continue;
  148. $trimmed = ltrim($raw, ' ');
  149. if ($trimmed === '' || $trimmed[0] === '#') continue;
  150. $indent = strlen($raw) - strlen($trimmed);
  151. // climb up to the correct parent by indent
  152. while (count($stack) > 1 && $indent <= $stack[array_key_last($stack)]['indent']) {
  153. array_pop($stack);
  154. }
  155. $parent =& $stack[array_key_last($stack)]['ref'];
  156. // List item
  157. if (preg_match('/^-\s*(.*)$/', $trimmed, $m)) {
  158. $val = $m[1];
  159. if (!is_array($parent)) $parent = [];
  160. if ($val === '') {
  161. $parent[] = [];
  162. $stack[] = ['indent' => $indent, 'ref' => &$parent[array_key_last($parent)]];
  163. } else {
  164. $parent[] = _fm_trim_quotes($val);
  165. }
  166. continue;
  167. }
  168. // Key: value or Key:
  169. if (preg_match('/^([A-Za-z0-9_.-]+):\s*(.*)$/', $trimmed, $m)) {
  170. $key = $m[1];
  171. $val = $m[2];
  172. if ($val === '') {
  173. if (!isset($parent[$key]) || !is_array($parent[$key])) {
  174. $parent[$key] = [];
  175. }
  176. $stack[] = ['indent' => $indent, 'ref' => &$parent[$key]];
  177. } else {
  178. $parent[$key] = _fm_trim_quotes($val);
  179. }
  180. }
  181. }
  182. return $root;
  183. }
  184. function parseFrontMatterForId(?string $clientId): array {
  185. $safeId = preg_match('/^[A-Za-z0-9_-]{1,64}$/', (string)$clientId) ? (string)$clientId : 'default';
  186. $path = __DIR__ . '/contracts/' . $safeId . '.md';
  187. if (!is_file($path)) $path = __DIR__ . '/contracts/default.md';
  188. $md = @file_get_contents($path);
  189. if ($md && preg_match('/^\s*---\s*\n(.*?)\n---\s*\n/s', $md, $m)) {
  190. return parseFrontMatter($m[1]);
  191. }
  192. return [];
  193. }
  194. function getPreparedDateFromMd(string $clientId): string {
  195. $safe = preg_match('/^[A-Za-z0-9_-]{1,64}$/', $clientId) ? $clientId : 'default';
  196. $path = __DIR__ . '/contracts/' . $safe . '.md';
  197. if (!is_file($path)) $path = __DIR__ . '/contracts/default.md';
  198. $md = file_get_contents($path);
  199. if (preg_match('/^\s*---\s*\n(.*?)\n---/s', $md, $m)) {
  200. $meta = parseFrontMatter($m[1]);
  201. $prepared = getByPath($meta, 'dates.prepared', '');
  202. return is_string($prepared) ? $prepared : '';
  203. }
  204. return '';
  205. }
  206. function _fm_trim_quotes(string $v): string {
  207. $v = trim($v);
  208. if ($v !== '' && $v[0] === "'" && substr($v, -1) === "'") return stripslashes(substr($v, 1, -1));
  209. if ($v !== '' && $v[0] === '"' && substr($v, -1) === '"') return stripslashes(substr($v, 1, -1));
  210. return $v;
  211. }
  212. function getByPath(array $arr, string $path, $default = '') {
  213. $keys = explode('.', $path);
  214. foreach ($keys as $k) {
  215. if ($k === '') continue;
  216. if (is_array($arr) && array_key_exists($k, $arr)) {
  217. $arr = $arr[$k];
  218. } else {
  219. return $default;
  220. }
  221. }
  222. return $arr;
  223. }
  224. function setByPath(array &$arr, string $path, $value): void {
  225. $keys = explode('.', $path);
  226. $ref =& $arr;
  227. foreach ($keys as $k) {
  228. if ($k === '') continue;
  229. if (!isset($ref[$k]) || !is_array($ref[$k])) $ref[$k] = [];
  230. $ref =& $ref[$k];
  231. }
  232. $ref = $value;
  233. }
  234. // Gets the current file URL and replaces the .php extension with .html
  235. function getHtmlUrl(string $htmlName): string {
  236. $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
  237. $scheme = $https ? 'https' : 'https';
  238. $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
  239. $dir = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
  240. return $scheme . '://' . $host . ($dir ? $dir : '') . '/' . $htmlName;
  241. }
  242. function getClientIp(): string {
  243. // 2) X-Forwarded-For: "client, proxy1, proxy2"
  244. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  245. $parts = array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
  246. foreach ($parts as $ip) {
  247. if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
  248. return $ip; // first public address
  249. }
  250. }
  251. // if nothing public, take the first valid one
  252. foreach ($parts as $ip) {
  253. if (filter_var($ip, FILTER_VALIDATE_IP)) {
  254. return $ip;
  255. }
  256. }
  257. }
  258. // 3) X-Real-IP
  259. if (!empty($_SERVER['HTTP_X_REAL_IP']) &&
  260. filter_var($_SERVER['HTTP_X_REAL_IP'], FILTER_VALIDATE_IP)) {
  261. return $_SERVER['HTTP_X_REAL_IP'];
  262. }
  263. // 4) Fallback
  264. if (!empty($_SERVER['REMOTE_ADDR']) &&
  265. filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP)) {
  266. return $_SERVER['REMOTE_ADDR'];
  267. }
  268. return 'UNKNOWN';
  269. }
  270. // Build overrides only when values are non-empty
  271. $ov = ['client' => [], 'dev' => []];
  272. if ($clientName !== '') $ov['client']['name'] = $clientName;
  273. if ($clientEmail !== '') $ov['client']['email'] = $clientEmail;
  274. if ($clientPhone !== '') $ov['client']['phone'] = $clientPhone;
  275. if ($clientAddress!== '') $ov['client']['address'] = $clientAddress;
  276. if ($devName !== '') $ov['dev']['name'] = $devName;
  277. if ($devEmail !== '') $ov['dev']['email'] = $devEmail;
  278. if ($devPhone !== '') $ov['dev']['phone'] = $devPhone;
  279. if ($devAddress !== '') $ov['dev']['address'] = $devAddress;
  280. $CONTRACT_HTML = loadContractHtml($_GET['clientid'] ?? null, $ov);
  281. $CLIENT_SIGNATURE = $_POST["client_signature"] ?? null;
  282. if ( is_string($CLIENT_SIGNATURE) && str_starts_with($CLIENT_SIGNATURE, "data:image/png;base64,") ) {
  283. // Size guard, rejects very large data URIs
  284. if (strlen($CLIENT_SIGNATURE) > 2 * 1024 * 1024) {
  285. http_response_code(413);
  286. exit("Signature too large");
  287. }
  288. $CLIENT_SIGNATURE = '<img id="hk" src="' . htmlspecialchars($CLIENT_SIGNATURE, ENT_QUOTES, "UTF-8") . '">';
  289. } else {
  290. $CLIENT_SIGNATURE = null;
  291. }
  292. /* -------------------------------------------------------------------------- */
  293. /* SECURITY AND ACCESS */
  294. /* -------------------------------------------------------------------------- */
  295. // Optional config
  296. $cfg = @include __DIR__ . '/config.php';
  297. $cfg = is_array($cfg) ? $cfg : [];
  298. // Optional admin creds for Basic Auth or old token scheme
  299. $ADMIN_USER = $cfg['admin_user'] ?? ($ADMIN_USER ?? '');
  300. $ADMIN_PASS = $cfg['admin_pass'] ?? ($ADMIN_PASS ?? '');
  301. $SECRET_KEY = $cfg['admin_secret'] ?? ($SECRET_KEY ?? ''); // old global secret, if you still use it
  302. // Front matter helpers reused from your client file
  303. if (!function_exists('_fm_trim_quotes')) {
  304. function _fm_trim_quotes(string $v) {
  305. $v = trim($v);
  306. if ($v === '') return '';
  307. $q = $v[0];
  308. if (($q === '"' || $q === "'") && substr($v, -1) === $q) return substr($v, 1, -1);
  309. return $v;
  310. }
  311. }
  312. if (!function_exists('parseFrontMatter')) {
  313. function parseFrontMatter(string $text): array {
  314. if (function_exists('yaml_parse')) {
  315. $arr = @yaml_parse($text);
  316. return is_array($arr) ? $arr : [];
  317. }
  318. $lines = preg_split('/\R/', rtrim($text));
  319. $root = [];
  320. $stack = [ ['indent' => -1, 'ref' => &$root] ];
  321. foreach ($lines as $raw) {
  322. if ($raw === '') continue;
  323. $trim = ltrim($raw, ' ');
  324. if ($trim === '' || $trim[0] === '#') continue;
  325. $indent = strlen($raw) - strlen($trim);
  326. while (count($stack) > 1 && $indent <= $stack[array_key_last($stack)]['indent']) array_pop($stack);
  327. $parent =& $stack[array_key_last($stack)]['ref'];
  328. if (preg_match('/^-\s*(.*)$/', $trim, $m)) {
  329. $val = $m[1];
  330. if (!is_array($parent)) $parent = [];
  331. if ($val === '') {
  332. $parent[] = [];
  333. $stack[] = ['indent' => $indent, 'ref' => &$parent[array_key_last($parent)]];
  334. } else {
  335. $parent[] = _fm_trim_quotes($val);
  336. }
  337. continue;
  338. }
  339. if (preg_match('/^([A-Za-z0-9_.-]+):\s*(.*)$/', $trim, $m)) {
  340. $key = $m[1];
  341. $val = $m[2];
  342. if ($val === '') {
  343. if (!isset($parent[$key]) || !is_array($parent[$key])) $parent[$key] = [];
  344. $stack[] = ['indent' => $indent, 'ref' => &$parent[$key]];
  345. } else {
  346. $parent[$key] = _fm_trim_quotes($val);
  347. }
  348. }
  349. }
  350. return $root;
  351. }
  352. }
  353. if (!function_exists('parseFrontMatterForId')) {
  354. function parseFrontMatterForId(?string $clientId): array {
  355. $safeId = preg_match('/^[A-Za-z0-9_-]{1,64}$/', (string)$clientId) ? $clientId : 'default';
  356. $path = __DIR__ . '/contracts/' . $safeId . '.md';
  357. if (!is_file($path)) $path = __DIR__ . '/contracts/default.md';
  358. $md = @file_get_contents($path);
  359. if ($md && preg_match('/^\s*---\s*\n(.*?)\n---\s*\n/s', $md, $m)) {
  360. return parseFrontMatter($m[1]);
  361. }
  362. return [];
  363. }
  364. }
  365. function fm_admin_secret_for(string $clientId): string {
  366. $fm = parseFrontMatterForId($clientId);
  367. // support either nested admin.secret or a flat admin_secret
  368. if (!empty($fm['admin']) && is_array($fm['admin']) && !empty($fm['admin']['secret'])) {
  369. return (string)$fm['admin']['secret'];
  370. }
  371. if (!empty($fm['admin_secret'])) return (string)$fm['admin_secret'];
  372. return '';
  373. }
  374. /**
  375. * Accept both link formats:
  376. * 1) New style: contract.php?clientid=3043&token=HMAC_SHA256(clientid, fm_admin_secret)
  377. * 2) Old style: contract.php?token=HMAC_SHA256(ADMIN_USER|ADMIN_PASS|expires, SECRET_KEY)&expires=UNIX
  378. */
  379. function access_allowed_by_token(): bool {
  380. global $ADMIN_USER, $ADMIN_PASS, $SECRET_KEY;
  381. $clientId = $_GET['clientid'] ?? '';
  382. $token = $_GET['token'] ?? '';
  383. $expires = isset($_GET['expires']) ? (int)$_GET['expires'] : 0;
  384. if ($token === '') return false;
  385. // Old scheme with expiry and global secret
  386. if ($expires > 0 && $ADMIN_USER !== '' && $ADMIN_PASS !== '' && $SECRET_KEY !== '') {
  387. if ($expires < time()) return false;
  388. $expected = hash_hmac('sha256', $ADMIN_USER . '|' . $ADMIN_PASS . '|' . $expires, $SECRET_KEY);
  389. if (hash_equals($expected, $token)) return true;
  390. }
  391. // New scheme with per-client secret in front matter
  392. if ($clientId !== '') {
  393. $secret = fm_admin_secret_for($clientId);
  394. if ($secret !== '') {
  395. $expected2 = hash_hmac('sha256', $clientId, $secret);
  396. if (hash_equals($expected2, $token)) return true;
  397. }
  398. }
  399. return false;
  400. }
  401. function require_admin_auth(): void {
  402. global $ADMIN_USER, $ADMIN_PASS;
  403. // Allow valid token to bypass auth for clients
  404. if (access_allowed_by_token()) return;
  405. // If admin creds are not configured, block
  406. if ($ADMIN_USER === '' || $ADMIN_PASS === '') {
  407. http_response_code(401);
  408. echo 'Auth required';
  409. exit;
  410. }
  411. // Basic Auth for admins
  412. if (!isset($_SERVER['PHP_AUTH_USER'])) {
  413. header('WWW-Authenticate: Basic realm="Contracts Admin"');
  414. header('HTTP/1.0 401 Unauthorized');
  415. echo 'Auth required';
  416. exit;
  417. }
  418. if ($_SERVER['PHP_AUTH_USER'] !== $ADMIN_USER || ($_SERVER['PHP_AUTH_PW'] ?? '') !== $ADMIN_PASS) {
  419. header('WWW-Authenticate: Basic realm="Contracts Admin"');
  420. header('HTTP/1.0 401 Unauthorized');
  421. echo 'Invalid credentials';
  422. exit;
  423. }
  424. }
  425. require_admin_auth();
  426. /** The HTML code (and some PHP) is kept in PHP variables like $CONTRACT_HTML, $FOOTER, $CONTRACT_SIGNED_PHP, and $CLIENT_DATE_IP_COMPILED. **/
  427. function headerWithTitle(
  428. string $title,
  429. ?string $clientId = null,
  430. ?string $preparedDate = null,
  431. string $context = 'web' // 'web' or 'pdf'
  432. ): string {
  433. $safeTitle = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
  434. $safeJob = htmlspecialchars((string)$clientId, ENT_QUOTES, 'UTF-8');
  435. $safePreparedDate = htmlspecialchars((string)$preparedDate, ENT_QUOTES, 'UTF-8');
  436. $baseHref = htmlspecialchars(
  437. ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'https')
  438. . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost')
  439. . rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\') . '/',
  440. ENT_QUOTES,
  441. 'UTF-8'
  442. );
  443. // CSS includes differ by context
  444. $cssLinks = $context === 'web'
  445. ? <<<HTML
  446. <link rel="preconnect" href="https://cdn.jsdelivr.net">
  447. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
  448. <link href="../internal/css/blueprint.css" rel="stylesheet">
  449. <link href="../internal/css/print.css" rel="stylesheet" media="print">
  450. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
  451. <link href="style.css" rel="stylesheet">
  452. HTML
  453. : <<<HTML
  454. <!-- Minimal CSS for PDF -->
  455. <link href="../internal/css/blueprint.css" rel="stylesheet">
  456. <link href="style.css" rel="stylesheet">
  457. <style>
  458. @page { margin: 5mm 10mm 10mm 10mm; }
  459. body { background:#fff;}
  460. .container { max-width: 780px; margin: 0 auto; font-size:0.7rem; }
  461. .shadow-sm { box-shadow: none !important; }
  462. .rounded-3 { border-radius: 0 !important; }
  463. .bg-white { background: #fff !important; }
  464. .d-print-none, .noprint { display: none !important; }
  465. .img-logo { max-height: 40px; }
  466. .page-header { display: table; width: 100%; table-layout: fixed; }
  467. .page-header > .col-4 { display: table-cell; width: 33.333%; vertical-align: middle; padding: 0 8px; }
  468. .page-header .text-start { text-align: left; }
  469. .page-header .text-center { text-align: center; }
  470. .page-header .text-end { text-align: right; }
  471. .compiled-signatures { display: table; width: 100%; table-layout: fixed; margin-top: 1rem; }
  472. .compiled-signatures .compiled-signature { display: table-cell; width: 35%; vertical-align: bottom; padding: 0 8px; }
  473. .compiled-signatures img { max-width: 100%; height: auto; }
  474. </style>
  475. HTML;
  476. // No JS in PDF
  477. $jsLinks = $context === 'web'
  478. ? <<<HTML
  479. <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js"></script>
  480. HTML
  481. : '';
  482. // Navbar only for web
  483. $nav = $context === 'web'
  484. ? <<<HTML
  485. <nav class="navbar bg-brown-dark brown-light border-bottom border-body d-print-none" data-bs-theme="dark">
  486. <div class="container-fluid">
  487. <a class="navbar-brand brown-light" href="#">
  488. <img src="../internal/images/blueprint-logo-light.png" alt="Modulos Design" width="30" height="24" class="d-inline-block align-text-top" >
  489. Modulos Design
  490. </a>
  491. </div>
  492. </nav>
  493. HTML
  494. : '';
  495. return <<<HTML
  496. <!doctype html>
  497. <html lang="en">
  498. <head>
  499. <meta charset="utf-8">
  500. <title>{$safeJob} - {$safeTitle}</title>
  501. <meta name="viewport" content="width=device-width, initial-scale=1">
  502. <meta name="robots" content="noindex">
  503. <link rel="shortcut icon" href="../internal/images/blueprint.ico" type="image/x-icon">
  504. <base href="{$baseHref}">
  505. {$cssLinks}
  506. {$jsLinks}
  507. </head>
  508. <body>
  509. {$nav}
  510. <main class="container my-4">
  511. <div class="bg-white p-4 p-md-5 rounded-0 shadow-sm">
  512. <div class="row align-items-center page-header">
  513. <div class="col-12 col-md-6 text-start">
  514. <img class="img-fluid pt-2 img-logo" src="../internal/images/blueprint-full-logo-medium.png" height="100" alt="Modulos Design">
  515. </div>
  516. <div class="col-12 col-md-6 text-end pt-3">
  517. <h3 class="fw-bold mb-1" style="color:#373a3c;">Job: {$safeJob}</h3>
  518. <h4 class="mb-1"><span class="fw-bold text-secondary">{$safePreparedDate}</span></h4>
  519. </div>
  520. </div>
  521. HTML;
  522. }
  523. function footerFor(string $context = 'web'): string {
  524. $extra = $context === 'web'
  525. ? <<<HTML
  526. <script>
  527. function printContract(){ window.print(); }
  528. </script>
  529. HTML
  530. : ''; // no JS for PDF
  531. return <<<HTML
  532. </div> <!-- /.rounded-3 -->
  533. </main>
  534. {$extra}
  535. </body>
  536. </html>
  537. HTML;
  538. }
  539. if ($CLIENT_SIGNATURE == null) {
  540. /** ⌛ Waiting for Client to sign: include signature elements and javascript **/
  541. // If a signed file already exists for this client, send them there
  542. if ($redirectToSigned) {
  543. $pattern = __DIR__ . "/{$clientId}_signed_contract*.html";
  544. $matches = glob($pattern);
  545. if ($matches) {
  546. usort($matches, fn($a, $b) => filemtime($b) <=> filemtime($a));
  547. $latest = basename($matches[0]);
  548. header("Location: " . $latest . "#hk", true, 302);
  549. exit;
  550. }
  551. }
  552. if (!headers_sent()) {
  553. header('Content-Type: text/html; charset=UTF-8');
  554. }
  555. $preparedDate = $_GET['prepared'] ?? getPreparedDateFromMd($clientId) ?: date('F j, Y');
  556. $HEADER = headerWithTitle(
  557. 'Unsigned Contract',
  558. $clientId, // show this as “Job: …”
  559. $preparedDate, // show this as the date
  560. 'web'
  561. );
  562. //$clientEmailInit = htmlspecialchars($_GET['client_email'] ?? '', ENT_QUOTES, 'UTF-8');
  563. $FOOTER = <<<HTML
  564. <div id="ui-unsigned">
  565. <form method="post" class="noprint" id="signature_form">
  566. <div id="signature-container">
  567. <div id="canvas-container">
  568. <canvas id="signature-pad" class="signature-pad" width="188" height="58.66"></canvas>
  569. </div>
  570. </div>
  571. <div class="animate slide">
  572. <div id="signature-controls" class="d-flex gap-2 justify-content-center mt-3">
  573. <button id="reset" type="button" class="btn btn-warning rounded-0">Clear</button>
  574. <button data-bs-toggle="modal" data-bs-target="#modal-qr" type="button" class="btn btn-secondary rounded-0">Sign on mobile</button>
  575. <button id="confirm" type="submit" class="btn btn-success rounded-0" disabled>Sign</button>
  576. </div>
  577. </div>
  578. <div class="flow" style="max-width: 330px; margin-inline-start: auto;">
  579. <h3 class="margin-top loading-signed hidden | animate slide" style="color: var(--clr-green-500); font-weight: 700;">Saving contract…</h3>
  580. <small class="loading-signed hidden | animate slide delay-16"
  581. style="font-weight: 600; color: var(--clr-blue-700);">
  582. This shouldn't take more than a minute.
  583. </small>
  584. </div>
  585. <input type="hidden" name="client_email" value="{$clientEmail}">
  586. <input type="hidden" name="csrf" value="{$csrf}">
  587. <input type="hidden" id="client_signature" name="client_signature" />
  588. <input type="hidden" name="client_tz" value="">
  589. </form>
  590. <div class="modal fade" tabindex="-1" id="modal-qr" aria-labelledby="modal-qrLabel" aria-hidden="true">
  591. <div class="modal-dialog modal-dialog-centered">
  592. <div class="modal-content">
  593. <div class="modal-body qr-code-container">
  594. <button id="close-modal-qr" type="button" class="btn-close" data-bs-dismiss="modal-qr" aria-label="Close"></button>
  595. <canvas id="qr-code"></canvas>
  596. </div>
  597. </div>
  598. </div>
  599. </div>
  600. </div>
  601. </div>
  602. </main>
  603. <script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>
  604. <script src="https://cdn.jsdelivr.net/npm/qrious@4.0.2/dist/qrious.min.js"></script>
  605. <script id="contract_script_unsigned" type="module">
  606. signature("#signature-pad")
  607. function signature(selector) {
  608. if (!document.querySelector(selector)) return
  609. const canvas = document.querySelector(selector)
  610. // https://github.com/szimek/signature_pad#options
  611. const clientSignaturePad = new SignaturePad(canvas, {
  612. penColor: "hsl(200, 100%, 30%)",
  613. minDistance: 2,
  614. })
  615. resizeCanvas()
  616. if (localStorage.getItem("client_signature")) {
  617. document.querySelector("#confirm").disabled = false
  618. // document.querySelector("#reset").disabled = false
  619. }
  620. // event listeners
  621. // save signature to localStorage on change
  622. clientSignaturePad.addEventListener("afterUpdateStroke", () => {
  623. let data = clientSignaturePad.toDataURL("image/png")
  624. document.querySelector("#client_signature").value = data
  625. localStorage.setItem("client_signature", data)
  626. // ! probably remove these:
  627. document.querySelector("#confirm").disabled = false
  628. // document.querySelector("#reset").disabled = false
  629. })
  630. // button to reset signature
  631. document.querySelector("#reset")?.addEventListener("click", (e) => {
  632. clientSignaturePad.clear()
  633. localStorage.removeItem("client_signature")
  634. document.querySelector("#client_signature").value = null
  635. document.querySelector("#confirm").disabled = true
  636. // document.querySelector("#reset").disabled = true
  637. })
  638. // form submit
  639. document.querySelector("#signature_form").addEventListener("submit", (e) => {
  640. // e.preventDefault();
  641. e.target.querySelectorAll(".loading-signed").forEach((el) => {
  642. el.classList.remove("hidden")
  643. })
  644. e.target.querySelector("#canvas-container").classList.add("just-signed")
  645. let otherElements = document.querySelectorAll("#content > *:not(#ui-unsigned, #dev_signature)")
  646. otherElements.forEach(element => {
  647. // element.style.cssText = `opacity: .5;`
  648. element.style.opacity = "0.5"
  649. })
  650. })
  651. window.onresize = resizeCanvas
  652. // needed for retina displays
  653. function resizeCanvas() {
  654. const ratio = Math.max(window.devicePixelRatio || 1, 1)
  655. canvas.width = canvas.offsetWidth * ratio
  656. canvas.height = canvas.offsetHeight * ratio
  657. canvas.getContext("2d").scale(ratio, ratio)
  658. let data = localStorage.getItem("client_signature");
  659. if (data) {
  660. // console.log(data)
  661. clientSignaturePad.fromDataURL(data)
  662. // disableResetButtonIfSignatureIsEmpty(data)
  663. document.querySelector("#client_signature").value = data
  664. }
  665. }
  666. }
  667. </script>
  668. <script>
  669. (function () {
  670. const modal = document.getElementById('modal-qr')
  671. const btnOpen = document.getElementById('show-modal-qr')
  672. const btnClose = document.getElementById('close-modal-qr')
  673. const canvas = document.getElementById('qr-code')
  674. if (canvas && window.QRious) {
  675. new QRious({
  676. element: canvas,
  677. value: window.location.href,
  678. foreground: 'hsl(200, 30%, 20%)',
  679. padding: 0,
  680. size: 500
  681. })
  682. }
  683. if (btnOpen && modal) {
  684. btnOpen.addEventListener('click', function (e) {
  685. e.preventDefault()
  686. try {
  687. if (typeof modal.showModal === 'function') {
  688. modal.showModal()
  689. } else {
  690. // very old browser fallback
  691. modal.setAttribute('open', '')
  692. }
  693. } catch (err) {
  694. modal.setAttribute('open', '')
  695. }
  696. })
  697. }
  698. btnClose?.addEventListener('click', function () {
  699. try {
  700. if (modal.open) modal.close()
  701. else modal.removeAttribute('open')
  702. } catch (e) {
  703. modal.removeAttribute('open')
  704. }
  705. })
  706. // click outside to close
  707. modal?.addEventListener('click', function (e) {
  708. const r = modal.getBoundingClientRect()
  709. const inside = e.clientY >= r.top && e.clientY <= r.bottom && e.clientX >= r.left && e.clientX <= r.right
  710. if (!inside) {
  711. try { modal.close() } catch (err) { modal.removeAttribute('open') }
  712. }
  713. })
  714. })()
  715. </script>
  716. <script>
  717. document.addEventListener('DOMContentLoaded', function () {
  718. try {
  719. var tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''
  720. var tzField = document.querySelector('input[name="client_tz"]')
  721. if (tzField) tzField.value = tz
  722. } catch (e) {}
  723. })
  724. </script>
  725. </body>
  726. </html>
  727. HTML;
  728. echo $HEADER;
  729. echo $CONTRACT_HTML;
  730. //echo $DEV_SIGNATURE;
  731. echo $FOOTER;
  732. } else {
  733. /** Contract was just signed: put $CLIENT_SIGNATURE and the other parts in the .html file **/
  734. // Build dev signature meta
  735. $devTimestamp = date('F j, Y \a\t g:i:s A T');
  736. $devIP = $_SERVER['SERVER_ADDR'] ?? 'UNKNOWN';
  737. $DEV_SIGNATURE .=
  738. '<div class="date-ip">' .
  739. '<strong>Signed on:</strong> ' . htmlspecialchars($devTimestamp, ENT_QUOTES, 'UTF-8') . '<br>' .
  740. '</div>';
  741. // Client signed date and IP
  742. $clientTz = $_POST['client_tz'] ?? '';
  743. if ($clientTz && in_array($clientTz, timezone_identifiers_list(), true)) {
  744. $tz = new DateTimeZone($clientTz);
  745. $clientDate = (new DateTime('now', $tz))->format('F j, Y \a\t g:i:s A T');
  746. } else {
  747. $clientDate = gmdate('F j, Y \a\t g:i:s A \G\M\T');
  748. }
  749. //$clientIp = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
  750. $clientIp = getClientIp();
  751. $CLIENT_SIGNATURE .=
  752. '<div id="date-ip" class="date-ip">' .
  753. '<strong>Signed on:</strong> ' . htmlspecialchars($clientDate, ENT_QUOTES, 'UTF-8') . '<br>' .
  754. '<strong>Client IP:</strong> ' . htmlspecialchars($clientIp, ENT_QUOTES, 'UTF-8') .
  755. '</div>';
  756. // Optional names above signatures (prefer MD front-matter, then querystring/config)
  757. $meta = parseFrontMatterForId($_GET['clientid'] ?? null);
  758. // try client.name in the MD front-matter
  759. $clientNameFromMd = '';
  760. if (is_array($meta)) {
  761. $clientNameFromMd = (string) (getByPath($meta, 'client.name', '') ?: ($meta['client']['name'] ?? ''));
  762. }
  763. $clientNameResolved = $clientName !== '' ? $clientName : $clientNameFromMd;
  764. // likewise for dev.name (in case you ever move it to the MD)
  765. $devNameFromMd = '';
  766. if (is_array($meta)) {
  767. $devNameFromMd = (string) (getByPath($meta, 'dev.name', '') ?: ($meta['dev']['name'] ?? ''));
  768. }
  769. $devNameResolved = $devName !== '' ? $devName : $devNameFromMd;
  770. if ($devNameResolved !== '') {
  771. $DEV_SIGNATURE = '<strong>' . htmlspecialchars($devNameResolved, ENT_QUOTES, 'UTF-8') . '</strong>' . $DEV_SIGNATURE;
  772. }
  773. if ($clientNameResolved !== '') {
  774. $CLIENT_SIGNATURE = '<strong>' . htmlspecialchars($clientNameResolved, ENT_QUOTES, 'UTF-8') . '</strong>' . $CLIENT_SIGNATURE;
  775. }
  776. $preparedDate = getPreparedDateFromMd($clientId) ?: $clientDate;
  777. // Assemble final HTML
  778. $HEADER = headerWithTitle(
  779. 'Signed Contract',
  780. $clientId,
  781. $preparedDate // you already computed this above
  782. );
  783. $CONTRACT_HTML = loadContractHtml($_GET['clientid'] ?? null);
  784. $compiled = <<<HTML
  785. <div class="row compiled-signatures align-items-end">
  786. <div class="col compiled-signature">{$DEV_SIGNATURE}</div>
  787. <div class="col compiled-signature">{$CLIENT_SIGNATURE}</div>
  788. </div>
  789. <br>
  790. <div class="row download-pdf d-print-none">
  791. <a href="contracts/{$clientId}_signed_contract.pdf" download class="btn btn-light rounded-0" id="downloadpdf">Download PDF</a>
  792. </div>
  793. HTML;
  794. $closing = <<<HTML
  795. </div>
  796. </main>
  797. <script>
  798. function printContract(){ window.print(); }
  799. </script>
  800. </body>
  801. </html>
  802. HTML;
  803. // Build a unique filename like 3043_signed_contract_20250812-184501.html
  804. $timestamp = date('Ymd-His');
  805. //$htmlName = "{$clientId}_signed_contract_{$timestamp}.html";
  806. $htmlName = "{$clientId}_signed_contract.html";
  807. if (file_exists($htmlName)) {
  808. $htmlName = "{$clientId}_signed_contract_" . date('Ymd-His') . ".html";
  809. }
  810. //$output = $HEADER . $CONTRACT_HTML . $compiled . $closing;
  811. // 1) WEB HTML to save
  812. $preparedDate = getByPath(parseFrontMatterForId($_GET['clientid'] ?? null), 'dates.prepared', date('F j, Y'));
  813. $headerWeb = headerWithTitle("{$clientId} - Signed Contract", $clientId, $preparedDate, 'web');
  814. $footerWeb = footerFor('web');
  815. $outputWeb = $headerWeb . $CONTRACT_HTML . $compiled . $footerWeb;
  816. file_put_contents($htmlName, $outputWeb);
  817. // 2) PDF HTML (lean) to render
  818. $headerPdf = headerWithTitle("{$clientId} - Signed Contract", $clientId, $preparedDate, 'pdf');
  819. $footerPdf = footerFor('pdf');
  820. $outputPdf = $headerPdf . $CONTRACT_HTML . $compiled . $footerPdf;
  821. // Save HTML file
  822. file_put_contents($htmlName, $outputWeb);
  823. $options = new \Dompdf\Options();
  824. $options->set('defaultFont', 'Helvetica');
  825. $options->set('isRemoteEnabled', true);
  826. $dompdf = new \Dompdf\Dompdf($options);
  827. $dompdf->loadHtml($outputPdf, 'UTF-8');
  828. $dompdf->setPaper('A4', 'portrait');
  829. // Helpful for resolving relative paths in CSS/images:
  830. $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
  831. $dir = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\') . '/';
  832. $dompdf->setBasePath('https://' . $host . $dir);
  833. $dompdf->render();
  834. $pdfPath = 'contracts/' . $clientId . '_signed_contract.pdf';
  835. file_put_contents($pdfPath, $dompdf->output());
  836. //error_log("$clientId - Finished creating html and pdf, Create email next.\r\n", 3, "error_log");
  837. error_log("$clientId - About to call sendEmails with clientEmail='{$clientEmail}' devEmail='{$devEmail}'\r\n", 3, "error_log");
  838. // Now send emails (and attach PDF)
  839. sendEmails($clientEmail, $devEmail, $fromAddress, $htmlName, $clientId, $pdfPath);
  840. //error_log("$clientId - Finished creating email. Redirect to HTML NOW.\r\n", 3, "error_log");
  841. // Redirect last
  842. header('Location: ' . $htmlName . '#hk', true, 303);
  843. exit;
  844. }
  845. // Function to email notifications; gets called when Client signs
  846. function sendEmails(
  847. string $clientEmail,
  848. string $devEmail,
  849. string $fromAddress,
  850. string $htmlName,
  851. string $clientId,
  852. string $pdfPath = ''
  853. ): void {
  854. global $cfg;
  855. // 1) Clean + validate addresses
  856. $clientEmail = preg_replace('/[\r\n]+/', '', $clientEmail);
  857. $devEmail = preg_replace('/[\r\n]+/', '', $devEmail);
  858. $clientEmail = filter_var($clientEmail, FILTER_VALIDATE_EMAIL) ?: '';
  859. $devEmail = filter_var($devEmail, FILTER_VALIDATE_EMAIL) ?: '';
  860. if (!$clientEmail && !$devEmail) return;
  861. // 2) Inputs for the email template
  862. $viewUrl = htmlspecialchars(getHtmlUrl($htmlName), ENT_QUOTES, 'UTF-8');
  863. $company = $cfg['dev_name'] ?? 'Modulos Design';
  864. $preparedDate = getPreparedDateFromMd($clientId) ?: date('F j, Y');
  865. // Try to greet the client by name (from front-matter)
  866. $meta = parseFrontMatterForId($clientId);
  867. $clientNameFromMd = is_array($meta) ? (string)(getByPath($meta, 'client.name', '')) : '';
  868. $clientCompanyFromMd = is_array($meta) ? (string)(getByPath($meta, 'client.company', '')) : $clientNameFromMd;
  869. $clientNameSafe = $clientNameFromMd;
  870. // Build a simple target list
  871. $targets = [];
  872. if ($clientEmail) $targets[] = ['to' => $clientEmail, 'kind' => 'client'];
  873. if ($devEmail) $targets[] = ['to' => $devEmail, 'kind' => 'dev'];
  874. foreach ($targets as $t) {
  875. // 3) Make the mailer
  876. $mail = new PHPMailer(true);
  877. $mail->SMTPDebug = SMTP::DEBUG_OFF;
  878. $mail->isSMTP();
  879. $mail->Host = $cfg['smtp_host'] ?? '';
  880. $mail->SMTPAuth = true;
  881. $mail->Username = $cfg['smtp_username'] ?? '';
  882. $mail->Password = $cfg['smtp_password'] ?? '';
  883. $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // 465/SSL
  884. $mail->Port = $cfg['smtp_port'] ?? 465;
  885. $mail->CharSet = 'UTF-8';
  886. $mail->Encoding = 'base64';
  887. $mail->setFrom($fromAddress, $company);
  888. // sensible reply-to
  889. if ($t['kind'] === 'client' && $devEmail) $mail->addReplyTo($devEmail);
  890. if ($t['kind'] === 'dev' && $clientEmail) $mail->addReplyTo($clientEmail);
  891. $mail->addAddress($t['to']);
  892. $mail->isHTML(true);
  893. // 4) Embed the logo **on this exact $mail** and get the <img> tag
  894. $logoHtml = email_logo_png_cid($mail, $cfg['dark_logo'] ?? '', $company, 200);
  895. $safeSignature = email_logo_png_cid($mail, $cfg['dev_signature'] ?? '', $company, 100);
  896. // 5) Build the body with correct argument order
  897. [$subject, $html, $alt] = buildSignedContractEmail(
  898. $logoHtml, // <- first param is the HTML for the CID <img>
  899. $viewUrl,
  900. $clientId,
  901. $clientNameSafe,
  902. $preparedDate,
  903. $company,
  904. $safeSignature
  905. );
  906. // Developer copy tweaks
  907. if ($t['kind'] === 'dev') {
  908. $subject = $clientId . ' ' . $clientCompanyFromMd . ' – Contract has been signed';
  909. $signedBy = htmlspecialchars($clientEmail ?: 'unknown', ENT_QUOTES, 'UTF-8');
  910. $inject = '<tr><td style="padding:4px 24px 0;font-size:14px;color:#444;">Signed by: ' . $signedBy . '</td></tr>';
  911. // try to insert after the first <tr> block; fallback to simple boundary replace
  912. $html = preg_replace('/(<tr>\s*<td[^>]*>.*?<\/td>\s*<\/tr>)/s', '$1' . $inject, $html, 1)
  913. ?: str_replace('</tr><tr>', '</tr>' . $inject . '<tr>', $html);
  914. $alt .= "\n\nSigned by: " . ($clientEmail ?: 'unknown');
  915. }
  916. $mail->Subject = $subject;
  917. $mail->Body = $html;
  918. if (!empty($alt)) $mail->AltBody = $alt;
  919. // Optional BCC + attachment
  920. $mail->addBCC('drafting@modulosdesign.com.au');
  921. if ($pdfPath !== '' && is_file($pdfPath)) {
  922. $mail->addAttachment($pdfPath, basename($pdfPath));
  923. }
  924. try {
  925. $mail->send();
  926. } catch (Exception $e) {
  927. error_log("Mailer error to {$t['to']}: {$mail->ErrorInfo}\n", 3, "error_log");
  928. }
  929. }
  930. }
  931. function salutationFromName(string $fullName): string {
  932. // Normalize whitespace (incl. non-breaking space) and collapse runs
  933. $name = str_replace("\xC2\xA0", ' ', $fullName); // NBSP → space
  934. $name = trim(preg_replace('/\s+/u', ' ', $name));
  935. if ($name === '') return 'there';
  936. // Strip common trailing suffixes like ", MD", ", PhD", "Jr.", etc.
  937. $name = preg_replace(
  938. '/,?\s*(Jr\.?|Sr\.?|II|III|IV|MD|Ph\.?D|Esq\.?|J\.?D\.?|M\.?B\.?A\.?|RN|DDS|DMD)\s*$/iu',
  939. '',
  940. $name
  941. );
  942. // Remove one or more leading honorifics (with optional dot), incl. unicode spaces
  943. $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)';
  944. $name = preg_replace('/^(?:' . $honorifics . ')\.?[\s\x{00A0}]+/iu', '', $name);
  945. while (preg_match('/^' . $honorifics . '\.?[\s\x{00A0}]+/iu', $name)) {
  946. $name = preg_replace('/^' . $honorifics . '(\.?)[\s\x{00A0}]+/iu', '', $name, 1);
  947. }
  948. // First non-initial token becomes the salutation
  949. $tokens = preg_split('/[\s\x{00A0}]+/u', $name);
  950. if (!$tokens) return 'there';
  951. foreach ($tokens as $tok) {
  952. $t = rtrim($tok, '.'); // drop trailing dot from initials
  953. if (!preg_match('/^[A-Za-z]\.?$/u', $t)) // skip single-letter initials
  954. return $t;
  955. }
  956. return $tokens[0] ?: 'there';
  957. }
  958. function email_logo_png_cid(PHPMailer $mail, string $dataUrl, string $alt = 'Modulos Design', int $width = 140): string {
  959. if ($dataUrl === '') return '';
  960. // Handle minor whitespace/newlines in config values
  961. $dataUrl = trim($dataUrl);
  962. $prefix = 'data:image/png;base64,';
  963. if (stripos($dataUrl, $prefix) !== 0) return '';
  964. $bin = base64_decode(substr($dataUrl, strlen($prefix)), true);
  965. if ($bin === false || $bin === '') return '';
  966. // Deterministic CID so forwards/replies still render
  967. $cid = 'logo_' . substr(sha1($bin), 0, 12) . '@modulos';
  968. // This is the crucial bit you commented out
  969. $mail->addStringEmbeddedImage($bin, $cid, 'logo.png', 'base64', 'image/png');
  970. return '<img src="cid:' . $cid . '" alt="' . htmlspecialchars($alt, ENT_QUOTES, 'UTF-8') . '" width="' . (int)$width . '" style="display:block;border:0;outline:0;text-decoration:none;height:auto;">';
  971. }
  972. function buildSignedContractEmail(
  973. string $logoHtml,
  974. string $viewUrl,
  975. string $clientId,
  976. string $clientName = '',
  977. string $preparedDate = '',
  978. string $company = 'Modulos Design',
  979. string $safeSignature
  980. ): array {
  981. $firstName = salutationFromName($clientName);
  982. $firstNameSafe = htmlspecialchars($firstName, ENT_QUOTES, 'UTF-8');
  983. $safeUrl = htmlspecialchars($viewUrl, ENT_QUOTES, 'UTF-8');
  984. $safeCompany = htmlspecialchars($company, ENT_QUOTES, 'UTF-8');
  985. $safeJob = htmlspecialchars($clientId, ENT_QUOTES, 'UTF-8');
  986. $safePrepared = htmlspecialchars($preparedDate, ENT_QUOTES, 'UTF-8');
  987. $preparedPart = $preparedDate ? " (prepared {$safePrepared})" : '';
  988. $subject = "{$safeJob} – Copy of Signed Contract";
  989. $html = <<<HTML
  990. <!-- Preheader stays hidden at 0px -->
  991. <div style="display:none;max-height:0;overflow:hidden;opacity:0;mso-hide:all;font-size:0;line-height:0;">
  992. Thank you for signing your contract — here’s your copy and access link.
  993. </div>
  994. <div style="background:#f6f7fb;padding:24px;font-size:14px;line-height:1.6;">
  995. <table role="presentation" cellspacing="0" cellpadding="0" border="0" align="center" width="600"
  996. style="width:600px;max-width:100%;background:#ffffff;border-radius:8px;overflow:hidden;
  997. font-size:14px;line-height:1.6;font-family:Arial,Helvetica,sans-serif;">
  998. <tr>
  999. <td style="font-size:14px;line-height:1.6;padding:20px 24px;background:#D9CCC1;color:#ffffff;">
  1000. <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="font-size:14px;line-height:1.6;">
  1001. <tr>
  1002. <td style="font-size:14px;line-height:1.6;">$logoHtml</td>
  1003. <td align="right" style="font-weight:700;font-size:14px;line-height:1.6;">Job #$safeJob</td>
  1004. </tr>
  1005. </table>
  1006. </td>
  1007. </tr>
  1008. <tr>
  1009. <td style="padding:28px 24px 8px;line-height:1.6;color:#635A4A;font-size:14px;">
  1010. <div style="font-size:14px;margin-bottom:8px;line-height:1.6;">Hello {$firstNameSafe},</div>
  1011. <div style="font-size:14px;line-height:1.6;">
  1012. Thank you for signing the contract{$preparedPart}. A copy is attached for your records,
  1013. and you can view or download it anytime using the link below:
  1014. </div>
  1015. </td>
  1016. </tr>
  1017. <tr>
  1018. <td align="center" style="padding:20px 24px 8px;font-size:14px;line-height:1.6;">
  1019. <!--[if mso]>
  1020. <v:rect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word"
  1021. href="$safeUrl"
  1022. style="height:42px;v-text-anchor:middle;width:240px;"
  1023. stroked="f" fillcolor="#635A4A">
  1024. <w:anchorlock/>
  1025. <center style="color:#ffffff;font-family:Arial,sans-serif;font-size:16px;line-height:1.6;">View Contract</center>
  1026. </v:rect>
  1027. <![endif]-->
  1028. <!--[if !mso]><!-- -->
  1029. <a href="$safeUrl"
  1030. style="background:#635A4A;border-radius:0;display:inline-block;padding:12px 24px;color:#ffffff;
  1031. text-decoration:none;font-weight:700;font-size:14px;line-height:1.6;mso-hide:all"
  1032. target="_blank" rel="noopener">View Contract</a>
  1033. <!--<![endif]-->
  1034. </td>
  1035. </tr>
  1036. <tr>
  1037. <td style="padding:8px 24px 24px;font-size:14px;line-height:1.6;color:#635A4A;">
  1038. <div style="font-size:14px;line-height:1.6;">
  1039. If the button doesn’t work, copy and paste this link into your browser:<br>
  1040. <span style="word-break:break-all;color:#635A4A;font-size:14px;line-height:1.6;">$safeUrl</span>
  1041. </div>
  1042. <div style="font-size:14px;line-height:1.6;margin-top:18px;">
  1043. Thanks again — we’re excited to be working with you and looking forward to getting started.<br><br>
  1044. <b>Kind Regards,</b><br><br>$safeSignature<br>Benjamin Harris<br>Modulos Design<br>0402 984 082 | drafting@modulosdesign.com.au
  1045. </div>
  1046. </td>
  1047. </tr>
  1048. <tr>
  1049. <td style="padding:12px 24px;background:#28261E;color:#D9CCC1;font-size:14px;line-height:1.6;">
  1050. This is an automated message. Please reply to this email if you have any questions.
  1051. </td>
  1052. </tr>
  1053. </table>
  1054. </div>
  1055. HTML;
  1056. $alt = "Hello {$firstName},\n\nThe contract has been signed{$preparedPart}.\n\nView/download: {$viewUrl}\n\nThanks,\n{$company}";
  1057. return [$subject, $html, $alt];
  1058. }
  1059. ?>