Email send tidy and webook refactor

This commit is contained in:
2025-03-13 17:41:08 +00:00
parent 1e63adf9d5
commit c7eddb5465
4 changed files with 274 additions and 179 deletions

View File

@@ -17,6 +17,9 @@ $mailFromName = 'Swansea Airport';
$baseUrl = "https://ppr.swansea-airport.wales/dev"; $baseUrl = "https://ppr.swansea-airport.wales/dev";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
function getUserIP() { function getUserIP() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) { if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP']; return $_SERVER['HTTP_CLIENT_IP'];
@@ -29,60 +32,60 @@ function getUserIP() {
function connectDb() { function connectDb() {
// Create connection // Create connection
$conn = new mysqli( $GLOBALS['host'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['database']); $conn = new mysqli( $GLOBALS['host'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['database']);
// Check connection // Check connection
if ($conn->connect_error) { if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); die("Connection failed: " . $conn->connect_error);
} }
return $conn; return $conn;
} }
function logJournal($conn, $id, $message) { function logJournal($conn, $id, $message) {
if (isset($_SERVER['PHP_AUTH_USER'])) { if (isset($_SERVER['PHP_AUTH_USER'])) {
$user = $_SERVER['PHP_AUTH_USER']; $user = $_SERVER['PHP_AUTH_USER'];
} else { } else {
$user = "None"; $user = "None";
} }
$stmt = $conn->prepare("INSERT INTO journal (ppr_id, entry, user, ip) VALUES (?, ?, ?, ?)"); $stmt = $conn->prepare("INSERT INTO journal (ppr_id, entry, user, ip) VALUES (?, ?, ?, ?)");
$ip = getUserIP(); $ip = getUserIP();
$stmt->bind_param("isss", $id, $message, $user, $ip); $stmt->bind_param("isss", $id, $message, $user, $ip);
$stmt->execute(); $stmt->execute();
$stmt->close(); $stmt->close();
} }
function require_db_auth() { function require_db_auth() {
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) { if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
send_auth_headers(); send_auth_headers();
} }
$user = $_SERVER['PHP_AUTH_USER']; $user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW']; $pass = $_SERVER['PHP_AUTH_PW'];
$conn = connectDb(); $conn = connectDb();
$stmt = $conn->prepare("SELECT password FROM users WHERE username = ?"); $stmt = $conn->prepare("SELECT password FROM users WHERE username = ?");
$stmt->bind_param("s", $user); $stmt->bind_param("s", $user);
$stmt->execute(); $stmt->execute();
$stmt->store_result(); $stmt->store_result();
$stmt->bind_result($stored_hash); $stmt->bind_result($stored_hash);
$stmt->fetch(); $stmt->fetch();
// Verify the password // Verify the password
if ($stmt->num_rows == 0 || !password_verify($pass, $stored_hash)) { if ($stmt->num_rows == 0 || !password_verify($pass, $stored_hash)) {
send_auth_headers(); send_auth_headers();
} }
// Close the connection // Close the connection
$stmt->close(); $stmt->close();
$conn->close(); $conn->close();
} }
@@ -93,21 +96,21 @@ function send_auth_headers() {
} }
function require_auth() { function require_auth() {
$AUTH_USER = 'admin'; $AUTH_USER = 'admin';
$AUTH_PASS = 'admin'; $AUTH_PASS = 'admin';
header('Cache-Control: no-cache, must-revalidate, max-age=0'); header('Cache-Control: no-cache, must-revalidate, max-age=0');
$has_supplied_credentials = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW'])); $has_supplied_credentials = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW']));
$is_not_authenticated = ( $is_not_authenticated = (
!$has_supplied_credentials || !$has_supplied_credentials ||
$_SERVER['PHP_AUTH_USER'] != $AUTH_USER || $_SERVER['PHP_AUTH_USER'] != $AUTH_USER ||
$_SERVER['PHP_AUTH_PW'] != $AUTH_PASS $_SERVER['PHP_AUTH_PW'] != $AUTH_PASS
); );
if ($is_not_authenticated) { if ($is_not_authenticated) {
header('HTTP/1.1 401 Authorization Required'); header('HTTP/1.1 401 Authorization Required');
header('WWW-Authenticate: Basic realm="PPR"'); header('WWW-Authenticate: Basic realm="PPR"');
echo 'Text to send if user hits Cancel button'; echo 'Text to send if user hits Cancel button';
exit; exit;
} }
} }
function generateSecureToken($email, $entryId) { function generateSecureToken($email, $entryId) {
@@ -118,7 +121,6 @@ function generateSecureToken($email, $entryId) {
return base64_encode("$data|$hash"); return base64_encode("$data|$hash");
} }
function validateSecureToken($token) { function validateSecureToken($token) {
$secretKey = "your-very-secret-key"; $secretKey = "your-very-secret-key";
$decoded = base64_decode($token); $decoded = base64_decode($token);
@@ -143,3 +145,44 @@ function validateSecureToken($token) {
return ['email' => $email, 'entryId' => $entryId]; 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 = "
<p>This is to confirm we have received your PPR. To view or cancel your PPR please click the button:</p>
<a href='$secureLink' style='display: inline-block; padding: 10px 20px; color: white; background-color: #007bff; text-decoration: none; border-radius: 5px;'>View PPR</a>
";
$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");
}
}
?>

View File

@@ -1,38 +1,23 @@
<?php <?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../vendor/autoload.php';
include("functions.php"); include("functions.php");
require_db_auth(); require_db_auth();
if ($_SERVER["REQUEST_METHOD"] == "POST") { if ($_SERVER["REQUEST_METHOD"] == "POST") {
$conn = connectDb(); $conn = connectDb();
$columns = []; $columns = [];
$values = []; $values = [];
echo "<h2>Received POST Data:</h2>"; echo "<h2>Received POST Data:</h2><ul>";
echo "<ul>";
foreach ($_POST as $key => $value) { foreach ($_POST as $key => $value) {
$escaped_key = "`" . $conn->real_escape_string($key) . "`"; $escaped_key = "`" . $conn->real_escape_string($key) . "`";
$escaped_value = ($value === '' || $value === null) ? "NULL" : (is_numeric($value) ? $value : "'" . $conn->real_escape_string($value) . "'");
if ($value === '' || $value === null) {
$escaped_value = "NULL"; // Use NULL for empty values
} elseif (is_numeric($value)) {
$escaped_value = $value; // No quotes for numbers
} else {
$escaped_value = "'" . $conn->real_escape_string($value) . "'"; // Escape and quote strings
}
$columns[] = $escaped_key; $columns[] = $escaped_key;
$values[] = $escaped_value; $values[] = $escaped_value;
echo "<li><strong>" . htmlspecialchars($key) . ":</strong> " . htmlspecialchars($value) . "</li>"; echo "<li><strong>" . htmlspecialchars($key) . ":</strong> " . htmlspecialchars($value) . "</li>";
} }
echo "</ul>";
if (!empty($columns)) { if (!empty($columns)) {
$sql = "INSERT INTO submitted (created_by, " . implode(",", $columns) . ") VALUES ('" . $_SERVER['PHP_AUTH_USER'] . "'," . implode(",", $values) . ")"; $sql = "INSERT INTO submitted (created_by, " . implode(",", $columns) . ") VALUES ('" . $_SERVER['PHP_AUTH_USER'] . "'," . implode(",", $values) . ")";
echo $sql; echo $sql;
@@ -42,60 +27,18 @@ if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "<p>Data successfully inserted into database with id = " . $lastId . "</p>"; echo "<p>Data successfully inserted into database with id = " . $lastId . "</p>";
if (!empty($_POST['email'])) { if (!empty($_POST['email'])) {
echo "Email is set to " . $_POST['email']; echo "Email is set to " . $_POST['email'];
generatePprEmail($lastId); generatePprEmail($lastId, $_POST['email'], $_POST['ac_reg']);
} else { } else {
echo "Username is not set."; echo "Email is not set.";
} }
echo '<script>window.close();</script>'; echo '<script>window.close();</script>';
} else { } else {
echo "<p>Error inserting data: " . $conn->error . "</p>"; echo "<p>Error inserting data: " . $conn->error . "</p>";
} }
} }
echo "</ul>";
} else { } else {
echo "<h2>No POST data received.</h2>"; echo "<h2>No POST data received.</h2>";
} }
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 = "
<p>This is to confirm we have received your PPR. To view or cancel your PPR please click the button:</p>
<a href='$secureLink' style='display: inline-block; padding: 10px 20px; color: white; background-color: #007bff; text-decoration: none; border-radius: 5px;'>View PPR</a>
";
$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");
}
}
?> ?>

View File

@@ -1,84 +1,109 @@
<?php <?php
include("functions.php");
// Basic connection settings // Database connection details
$databaseHost = 'sasaprod.pattinson.org'; $servername = "sasaprod.pattinson.org";
$databaseUsername = 'root'; $username = "root";
$databasePassword = 'PugPictureMousePen'; $password = "PugPictureMousePen";
$databaseName = 'pprdevdb'; $dbname = "pprdevdb";
$created_by = "webhook-dev"; $created_by = "webhook-dev";
//ini_set("error_log", "ppr.log"); // Create connection
error_log("Webhook handler called"); $conn = new mysqli($servername, $username, $password, $dbname);
// Connect to the database
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
header('Content-Type: application/json');
#if($json = json_decode(file_get_contents("php://input"), true)) {
if($json = json_decode(file_get_contents("testhook.json"), true)) {
$data = $json;
// Check connection
if ($conn->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(); // Mapping of JSON 'name' keys to database column names
$fieldMap['ac_reg'] = '617dd0cd-2d17-4d7f-826b-5348afdb30b3'; $columnMapping = [
$fieldMap['ac_type'] = '148a55d8-5357-49a3-b9aa-2a5d4dc64173'; "Aircraft Registration" => "ac_reg",
$fieldMap['ac_call'] = '52d7bc90-9d26-48a1-82db-b91b4ccd2f92'; "Aircraft Type" => "ac_type",
$fieldMap['captain'] = '49b2de0d-5bd6-4b0c-86dd-b18b85f8b8ff'; "Callsign" => "ac_call",
$fieldMap['fuel'] = 'd153c8a5-8345-4e6a-abfd-cf8adcc06f2d'; "Captain or PIC Name" => "captain",
$fieldMap['in_from'] = '4b4f7ecd-f80c-4e86-a7ab-6fadb3220df8'; "Arriving From" => "in_from",
$fieldMap['eta'] = 'ca4ac44f-0388-4a70-a072-38276ed2ac13'; "ETA" => "eta",
$fieldMap['pob_in'] = '6fc47c54-7383-48fd-93fc-d8080f5ed8f5'; "POB Inbound" => "pob_in",
$fieldMap['out_to'] = 'ba95fd3f-1ec0-4553-95d3-a0b6a850738d'; "Fuel Required" => "fuel",
$fieldMap['etd'] = '53d60abd-eb75-4b1f-92b6-5d47d26367ec'; "Departing To" => "out_to",
$fieldMap['pob_out'] = 'd1ac0860-31f4-4914-9d0b-cae42dfc7eda'; "ETD" => "etd",
$fieldMap['email'] = '0198c86c-edd1-4aaf-93a1-d68f8fc8c365'; "POB Outbound" => "pob_out",
$fieldMap['phone'] = 'e40ebc2d-887b-42b3-931d-c981c76b0c20'; "Email" => "email",
$fieldMap['notes'] = '73d26c2c-1d3d-44e2-82fc-3a1a2600c393'; "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'];
// Check if the statement was prepared correctly // Transform ETA and ETD to MySQL datetime format
if ($stmt === false) { if ($name == "ETA" || $name == "ETD") {
die('MySQL prepare error: ' . mysqli_error($conn)); $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[] = '?';
// 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']; // Add created_by to the columns, values, and placeholders
$ac_type = $json['data'][$fieldMap['ac_type']]['value']; $columns[] = 'created_by';
$captain = $json['data'][$fieldMap['captain']]['value']; $values[] = $created_by;
$in_from = $json['data'][$fieldMap['in_from']]['value']; $placeholders[] = '?';
$fuel = $json['data'][$fieldMap['fuel']]['value']; $types .= 's';
$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'];
if (array_key_exists($fieldMap['out_to'], $json['data'])) { $sql = "INSERT INTO submitted (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $placeholders) . ")";
$date = DateTime::createFromFormat('d/m/Y H:i', $json['data'][$fieldMap['etd']]['value']); $stmt = $conn->prepare($sql);
$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']; // Bind parameters dynamically
$phone = $json['data'][$fieldMap['phone']]['value']; $stmt->bind_param($types, ...$values);
$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 // Execute the statement
if (mysqli_stmt_execute($stmt)) { if ($stmt->execute()) {
error_log("Record inserted for " . $ac_reg); echo "New record created successfully";
$lastId = $stmt->insert_id;
if (!empty($email)) {
generatePprEmail($lastId, $email, $ac_reg);
} else {
echo "Email is not set.";
}
} else { } else {
error_log("Error: " . mysqli_stmt_error($stmt)); echo "Error: " . $stmt->error;
} }
// Close the statement and connection // Close the connection
mysqli_stmt_close($stmt); $stmt->close();
mysqli_close($mysqli); $conn->close();
?> ?>

84
webhook_old.php Normal file
View File

@@ -0,0 +1,84 @@
<?php
// Basic connection settings
$databaseHost = 'sasaprod.pattinson.org';
$databaseUsername = 'root';
$databasePassword = 'PugPictureMousePen';
$databaseName = 'pprdevdb';
$created_by = "webhook-dev";
//ini_set("error_log", "ppr.log");
error_log("Webhook handler called");
// Connect to the database
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
header('Content-Type: application/json');
#if($json = json_decode(file_get_contents("php://input"), true)) {
if($json = json_decode(file_get_contents("testhook.json"), true)) {
$data = $json;
}
print_r($data);
$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';
#print_r($json['data'][$fieldMap['eta']]['value']);
$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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
// Check if the statement was prepared correctly
if ($stmt === false) {
die('MySQL prepare error: ' . mysqli_error($conn));
}
$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'];
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);
?>