From c7eddb5465de57ad4b6c6c80d2c48b40538c1fc1 Mon Sep 17 00:00:00 2001 From: James Pattinson Date: Thu, 13 Mar 2025 17:41:08 +0000 Subject: [PATCH] Email send tidy and webook refactor --- functions.php | 145 +++++++++++++++++++++++++++++---------------- newppr.php | 71 +++------------------- webhook.php | 153 ++++++++++++++++++++++++++++-------------------- webhook_old.php | 84 ++++++++++++++++++++++++++ 4 files changed, 274 insertions(+), 179 deletions(-) create mode 100644 webhook_old.php diff --git a/functions.php b/functions.php index 788155e..a3c834e 100644 --- a/functions.php +++ b/functions.php @@ -17,6 +17,9 @@ $mailFromName = 'Swansea Airport'; $baseUrl = "https://ppr.swansea-airport.wales/dev"; +use PHPMailer\PHPMailer\PHPMailer; +use PHPMailer\PHPMailer\Exception; + function getUserIP() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { return $_SERVER['HTTP_CLIENT_IP']; @@ -29,60 +32,60 @@ function getUserIP() { function connectDb() { - // Create connection - $conn = new mysqli( $GLOBALS['host'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['database']); + // Create connection + $conn = new mysqli( $GLOBALS['host'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['database']); - // Check connection - if ($conn->connect_error) { - die("Connection failed: " . $conn->connect_error); - } + // Check connection + if ($conn->connect_error) { + die("Connection failed: " . $conn->connect_error); + } - return $conn; + return $conn; } function logJournal($conn, $id, $message) { - if (isset($_SERVER['PHP_AUTH_USER'])) { - $user = $_SERVER['PHP_AUTH_USER']; - } else { - $user = "None"; - } + if (isset($_SERVER['PHP_AUTH_USER'])) { + $user = $_SERVER['PHP_AUTH_USER']; + } else { + $user = "None"; + } - $stmt = $conn->prepare("INSERT INTO journal (ppr_id, entry, user, ip) VALUES (?, ?, ?, ?)"); - $ip = getUserIP(); - $stmt->bind_param("isss", $id, $message, $user, $ip); - $stmt->execute(); - $stmt->close(); + $stmt = $conn->prepare("INSERT INTO journal (ppr_id, entry, user, ip) VALUES (?, ?, ?, ?)"); + $ip = getUserIP(); + $stmt->bind_param("isss", $id, $message, $user, $ip); + $stmt->execute(); + $stmt->close(); } function require_db_auth() { - if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) { - send_auth_headers(); - } + if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) { + send_auth_headers(); + } - $user = $_SERVER['PHP_AUTH_USER']; - $pass = $_SERVER['PHP_AUTH_PW']; + $user = $_SERVER['PHP_AUTH_USER']; + $pass = $_SERVER['PHP_AUTH_PW']; - $conn = connectDb(); + $conn = connectDb(); - $stmt = $conn->prepare("SELECT password FROM users WHERE username = ?"); - $stmt->bind_param("s", $user); - $stmt->execute(); - $stmt->store_result(); - $stmt->bind_result($stored_hash); - $stmt->fetch(); + $stmt = $conn->prepare("SELECT password FROM users WHERE username = ?"); + $stmt->bind_param("s", $user); + $stmt->execute(); + $stmt->store_result(); + $stmt->bind_result($stored_hash); + $stmt->fetch(); - // Verify the password - if ($stmt->num_rows == 0 || !password_verify($pass, $stored_hash)) { - send_auth_headers(); - } + // Verify the password + if ($stmt->num_rows == 0 || !password_verify($pass, $stored_hash)) { + send_auth_headers(); + } - // Close the connection - $stmt->close(); - $conn->close(); + // Close the connection + $stmt->close(); + $conn->close(); } @@ -93,21 +96,21 @@ function send_auth_headers() { } function require_auth() { - $AUTH_USER = 'admin'; - $AUTH_PASS = 'admin'; - header('Cache-Control: no-cache, must-revalidate, max-age=0'); - $has_supplied_credentials = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW'])); - $is_not_authenticated = ( - !$has_supplied_credentials || - $_SERVER['PHP_AUTH_USER'] != $AUTH_USER || - $_SERVER['PHP_AUTH_PW'] != $AUTH_PASS - ); - if ($is_not_authenticated) { - header('HTTP/1.1 401 Authorization Required'); - header('WWW-Authenticate: Basic realm="PPR"'); + $AUTH_USER = 'admin'; + $AUTH_PASS = 'admin'; + header('Cache-Control: no-cache, must-revalidate, max-age=0'); + $has_supplied_credentials = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW'])); + $is_not_authenticated = ( + !$has_supplied_credentials || + $_SERVER['PHP_AUTH_USER'] != $AUTH_USER || + $_SERVER['PHP_AUTH_PW'] != $AUTH_PASS + ); + if ($is_not_authenticated) { + header('HTTP/1.1 401 Authorization Required'); + header('WWW-Authenticate: Basic realm="PPR"'); echo 'Text to send if user hits Cancel button'; - exit; - } + exit; + } } function generateSecureToken($email, $entryId) { @@ -118,7 +121,6 @@ function generateSecureToken($email, $entryId) { return base64_encode("$data|$hash"); } - function validateSecureToken($token) { $secretKey = "your-very-secret-key"; $decoded = base64_decode($token); @@ -143,3 +145,44 @@ function validateSecureToken($token) { return ['email' => $email, 'entryId' => $entryId]; } +function generatePprEmail($entryId, $email, $ac_reg) { + global $conn, $mailHost, $mailSMTPAuth, $mailUsername, $mailPassword, $mailPort, $baseUrl, $mailFromAddress, $mailFromName; + + if (!class_exists('PHPMailer\PHPMailer\PHPMailer')) { + require '../vendor/autoload.php'; + } + + $token = generateSecureToken($email, $entryId); + $secureLink = $baseUrl . "/pilotppr.php?op=view&token=" . urlencode($token); + + $mail = new PHPMailer(true); + + try { + $mail->isSMTP(); + $mail->Host = $mailHost; + $mail->SMTPAuth = $mailSMTPAuth; + $mail->Username = $mailUsername; + $mail->Password = $mailPassword; + $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; + $mail->Port = $mailPort; + + $mail->setFrom($mailFromAddress, $mailFromName); + $mail->addAddress($email); + + $mail->isHTML(true); + $mail->Subject = "PPR Confirmation for " . $ac_reg; + $mail->Body = " +

This is to confirm we have received your PPR. To view or cancel your PPR please click the button:

+ View PPR + "; + + $mail->send(); + echo "Email sent successfully!"; + logJournal($conn, $entryId, "Confirm email sent"); + + } catch (Exception $e) { + echo "Email sending failed: {$mail->ErrorInfo}"; + logJournal($conn, $entryId, "Confirm email FAILED"); + } +} +?> \ No newline at end of file diff --git a/newppr.php b/newppr.php index 25cb110..fa91f3d 100644 --- a/newppr.php +++ b/newppr.php @@ -1,101 +1,44 @@ Received POST Data:"; - echo ""; } else { echo "

No POST data received.

"; } -function generatePprEmail($entryId) { - - global $conn, $mailHost, $mailSMTPAuth, $mailUsername, $mailPassword, $mailPort, $baseUrl, $mailFromAddress, $mailFromName; - $token = generateSecureToken($_POST['email'], $entryId); - $secureLink = $baseUrl . "/pilotppr.php?op=view&token=" . urlencode($token); - echo $secureLink; - - $mail = new PHPMailer(true); - - try { - $mail->isSMTP(); - $mail->Host = $mailHost; - $mail->SMTPAuth = $mailSMTPAuth; - $mail->Username = $mailUsername; - $mail->Password = $mailPassword; - $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; - $mail->Port = $mailPort; - - $mail->setFrom($mailFromAddress, $mailFromName); - $mail->addAddress($_POST['email']); - - $mail->isHTML(true); - $mail->Subject = "PPR Confirmation for " . $_POST['ac_reg']; - $mail->Body = " -

This is to confirm we have received your PPR. To view or cancel your PPR please click the button:

- View PPR - "; - - $mail->send(); - echo "Email sent successfully!"; - logJournal($conn, $entryId, "Confirm email sent"); - - } catch (Exception $e) { - echo "Email sending failed: {$mail->ErrorInfo}"; - logJournal($conn, $entryId, "Confirm email FAILED"); - - } - -} - ?> diff --git a/webhook.php b/webhook.php index 52d6125..ce84a7d 100644 --- a/webhook.php +++ b/webhook.php @@ -1,84 +1,109 @@ connect_error) { + die("Connection failed: " . $conn->connect_error); } -print_r($data); +// Webhook payload +#$payload = json_decode(file_get_contents('php://input'), true); +$payload = json_decode(file_get_contents('testhook.json'), true); -$fieldMap = array(); -$fieldMap['ac_reg'] = '617dd0cd-2d17-4d7f-826b-5348afdb30b3'; -$fieldMap['ac_type'] = '148a55d8-5357-49a3-b9aa-2a5d4dc64173'; -$fieldMap['ac_call'] = '52d7bc90-9d26-48a1-82db-b91b4ccd2f92'; -$fieldMap['captain'] = '49b2de0d-5bd6-4b0c-86dd-b18b85f8b8ff'; -$fieldMap['fuel'] = 'd153c8a5-8345-4e6a-abfd-cf8adcc06f2d'; -$fieldMap['in_from'] = '4b4f7ecd-f80c-4e86-a7ab-6fadb3220df8'; -$fieldMap['eta'] = 'ca4ac44f-0388-4a70-a072-38276ed2ac13'; -$fieldMap['pob_in'] = '6fc47c54-7383-48fd-93fc-d8080f5ed8f5'; -$fieldMap['out_to'] = 'ba95fd3f-1ec0-4553-95d3-a0b6a850738d'; -$fieldMap['etd'] = '53d60abd-eb75-4b1f-92b6-5d47d26367ec'; -$fieldMap['pob_out'] = 'd1ac0860-31f4-4914-9d0b-cae42dfc7eda'; -$fieldMap['email'] = '0198c86c-edd1-4aaf-93a1-d68f8fc8c365'; -$fieldMap['phone'] = 'e40ebc2d-887b-42b3-931d-c981c76b0c20'; -$fieldMap['notes'] = '73d26c2c-1d3d-44e2-82fc-3a1a2600c393'; +// Mapping of JSON 'name' keys to database column names +$columnMapping = [ + "Aircraft Registration" => "ac_reg", + "Aircraft Type" => "ac_type", + "Callsign" => "ac_call", + "Captain or PIC Name" => "captain", + "Arriving From" => "in_from", + "ETA" => "eta", + "POB Inbound" => "pob_in", + "Fuel Required" => "fuel", + "Departing To" => "out_to", + "ETD" => "etd", + "POB Outbound" => "pob_out", + "Email" => "email", + "Phone Number" => "phone", + "Additional Information" => "notes" +]; -#print_r($json['data'][$fieldMap['eta']]['value']); +// Prepare the SQL statement dynamically +$columns = []; +$values = []; +$placeholders = []; +$types = ''; +$email = ''; +$ac_reg = ''; -$stmt = mysqli_prepare($mysqli, "INSERT INTO submitted (ac_reg, ac_type, captain, fuel, in_from, eta, pob_in, etd, pob_out, email, phone, notes, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); +foreach ($payload['data'] as $key => $field) { + $name = $field['name']; + if (isset($columnMapping[$name])) { + $columns[] = $columnMapping[$name]; + $value = $field['value']; + + // Transform ETA and ETD to MySQL datetime format + if ($name == "ETA" || $name == "ETD") { + $date = DateTime::createFromFormat('d/m/Y H:i', $value); + $value = $date->format('Y-m-d H:i:s'); + } + + // Handle POB Inbound and POB Outbound as integers + if ($name == "POB Inbound" || $name == "POB Outbound") { + $types .= 'i'; + } else { + $types .= 's'; // Assuming all other values are strings + } + + $values[] = $value; + $placeholders[] = '?'; -// Check if the statement was prepared correctly -if ($stmt === false) { - die('MySQL prepare error: ' . mysqli_error($conn)); + // Capture email and aircraft registration for email sending + if ($name == "Email") { + $email = $value; + } + if ($name == "Aircraft Registration") { + $ac_reg = $value; + } + } } -$ac_reg = $json['data'][$fieldMap['ac_reg']]['value']; -$ac_type = $json['data'][$fieldMap['ac_type']]['value']; -$captain = $json['data'][$fieldMap['captain']]['value']; -$in_from = $json['data'][$fieldMap['in_from']]['value']; -$fuel = $json['data'][$fieldMap['fuel']]['value']; -$date = DateTime::createFromFormat('d/m/Y H:i', $json['data'][$fieldMap['eta']]['value']); -$eta = $date->format('Y-m-d H:i:s'); -$pob_in = $json['data'][$fieldMap['pob_in']]['value']; +// Add created_by to the columns, values, and placeholders +$columns[] = 'created_by'; +$values[] = $created_by; +$placeholders[] = '?'; +$types .= 's'; -if (array_key_exists($fieldMap['out_to'], $json['data'])) { - $date = DateTime::createFromFormat('d/m/Y H:i', $json['data'][$fieldMap['etd']]['value']); - $etd = $date->format('Y-m-d H:i:s'); - $pob_out = $json['data'][$fieldMap['pob_out']]['value']; - $out_to = $json['data'][$fieldMap['out_to']]['value']; -} +$sql = "INSERT INTO submitted (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $placeholders) . ")"; +$stmt = $conn->prepare($sql); -$email = $json['data'][$fieldMap['email']]['value']; -$phone = $json['data'][$fieldMap['phone']]['value']; -$notes = $json['data'][$fieldMap['notes']]['value']; - -mysqli_stmt_bind_param($stmt, "ssssssisissss", $ac_reg, $ac_type, $captain, $fuel, $in_from, $eta, $pob_in, $etd, $pob_out, $email, $phone, $notes, $created_by); +// Bind parameters dynamically +$stmt->bind_param($types, ...$values); // Execute the statement -if (mysqli_stmt_execute($stmt)) { - error_log("Record inserted for " . $ac_reg); +if ($stmt->execute()) { + echo "New record created successfully"; + $lastId = $stmt->insert_id; + if (!empty($email)) { + generatePprEmail($lastId, $email, $ac_reg); + } else { + echo "Email is not set."; + } } else { - error_log("Error: " . mysqli_stmt_error($stmt)); + echo "Error: " . $stmt->error; } -// Close the statement and connection -mysqli_stmt_close($stmt); -mysqli_close($mysqli); -?> +// Close the connection +$stmt->close(); +$conn->close(); +?> \ No newline at end of file diff --git a/webhook_old.php b/webhook_old.php new file mode 100644 index 0000000..52d6125 --- /dev/null +++ b/webhook_old.php @@ -0,0 +1,84 @@ +format('Y-m-d H:i:s'); +$pob_in = $json['data'][$fieldMap['pob_in']]['value']; + +if (array_key_exists($fieldMap['out_to'], $json['data'])) { + $date = DateTime::createFromFormat('d/m/Y H:i', $json['data'][$fieldMap['etd']]['value']); + $etd = $date->format('Y-m-d H:i:s'); + $pob_out = $json['data'][$fieldMap['pob_out']]['value']; + $out_to = $json['data'][$fieldMap['out_to']]['value']; +} + +$email = $json['data'][$fieldMap['email']]['value']; +$phone = $json['data'][$fieldMap['phone']]['value']; +$notes = $json['data'][$fieldMap['notes']]['value']; + +mysqli_stmt_bind_param($stmt, "ssssssisissss", $ac_reg, $ac_type, $captain, $fuel, $in_from, $eta, $pob_in, $etd, $pob_out, $email, $phone, $notes, $created_by); + +// Execute the statement +if (mysqli_stmt_execute($stmt)) { + error_log("Record inserted for " . $ac_reg); +} else { + error_log("Error: " . mysqli_stmt_error($stmt)); +} + +// Close the statement and connection +mysqli_stmt_close($stmt); +mysqli_close($mysqli); +?>