code cleaned up and refactored

This commit is contained in:
eclipse 2025-03-01 11:30:51 +01:00
parent 093e0f16b5
commit 34902f8076
4 changed files with 150 additions and 136 deletions

View File

@ -1,38 +1,41 @@
<?php
// inspired by https://www.mailgun.com/blog/email/double-opt-in-with-php-mailgun/
$statusCode = "HTTP/1.1 303 See Other";
$statusCode = 'HTTP/1.1 303 See Other';
$successURL = '/newsletter/confirmed.html';
$errorURL = '/newsletter/confirm-error.html';
// return TRUE when successful, message string on failure
// e.g. Adresse schon vorhanden, Datenbank-Fehler, was noch?
function AddMemberToDB($recipientAddress) {
function AddSubscriberToDB($recipientAddress) {
global $db;
echo "ah jup";
echo 'ah jup';
return TRUE;
}
function CheckConfirmationHash($confEmail, $confCode) {
global $general;
return (md5($confEmail . $general['uniqueKey']) === $confCode);
}
require(dirname(__FILE__) . "/settings.php");
require(dirname(__FILE__) . '/settings.php');
$c = isset($_GET['c']) ? SanitizeInputs($_GET['c']) : NULL;
$e = isset($_GET['e']) ? SanitizeInputs($_GET['e']) : NULL;
if (isset($_GET['c']) && isset($_GET['e'])) {
$c = filter_var($_GET['c'], FILTER_SANITIZE_STRING);
$e = filter_var($_GET['e'], FILTER_SANITIZE_STRING);
if (! (isset($c) && isset($e) && CheckConfirmationHash($e, $c)) ) {
header($statusCode);
header("Location: " . $errorURL . "?" . http_build_query(["msg" => SanitizeInputs("Ungültiger Link")]));
} else {
$result = AddMemberToDB($e);
if ($result == TRUE) {
header($statusCode);
header("Location: " . $successURL);
} elseif (gettype($result == "string")) {
header($statusCode);
header("Location: " . $errorURL . "?" . http_build_query(["msg" => SanitizeInputs($result)]));
if (CheckConfirmationHash($e, $c)) {
$result = AddSubscriberToDB($e);
if ($result == TRUE) {
GracefulExit($successURL, 'Bestätigung erfolgt: Newsletter-Anmeldung bestätigt');
} elseif (gettype($result == 'string')) {
GracefulExit($errorURL, "Bestätigung fehlgeschlagen: {$result}");
} else {
GracefulExit($errorURL, 'Bestätigung fehlgeschlagen: Unbekannter Fehler');
}
} else {
header($statusCode);
header("Location: " . $errorURL . "?" . http_build_query(["msg" => SanitizeInputs("Unbekannter Fehler")]));
GracefulExit($errorURL, 'Bestätigung fehlgeschlagen: Fehlerhafter Hash');
}
} else {
GracefulExit($errorURL, 'Bestätigung fehlgeschlagen: Fehlende Emailadresse oder Hash');
}
?>

View File

@ -1,62 +1,104 @@
<?php
// inspired by https://www.mailgun.com/blog/email/double-opt-in-with-php-mailgun/
// import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$dname = dirname(__FILE__);
require $dname . '/Exception.php';
require $dname . '/PHPMailer.php';
require $dname . '/SMTP.php';
// general constants
$general = array(
// "domain" => 'tobias-radloff.de',
"domain" => 'localhost',
"uniqueKey" => '***REMOVED***', // works like password salt
"confirmScript" => "/confirm.php"
);
$general["siteURL"] = "https://" . $general["domain"];
$general = [
// 'domain' => 'tobias-radloff.de',
'domain' => 'localhost',
'uniqueKey' => '***REMOVED***', // works like password salt
'confirmScript' => '/confirm.php',
'statusCode' => 'HTTP/1.1 303 See Other'
];
$general['siteURL'] = 'https://' . $general['domain'];
// smtp info
$smtp = array(
"host" => '***REMOVED***
"port" => 587,
"username" => 'tobias',
"password" => '***REMOVED***',
"auth" => TRUE,
"fromAddress" => "***REMOVED***", // 'newsletter@tobias-radloff.de'
"fromName" => "Tobias Radloffs Newsletter",
);
$smtp = [
'host' => '***REMOVED***
'port' => 587,
'username' => 'tobias',
'password' => '***REMOVED***',
'auth' => TRUE,
'fromAddress' => '***REMOVED***', // 'newsletter@tobias-radloff.de'
'fromName' => 'Tobias Radloffs Newsletter',
];
$body = array(
"Hallo!",
"Bitte bestätige die Anmeldung für meinen Newsletter, indem du auf den folgenden Link klickst:",
"%confirmURL%", // placeholder
"Bis bald und viele Grüße, Tobias"
);
$bodyConfirmation = [
'Hallo!',
'Bitte bestätige die Anmeldung für meinen Newsletter, indem du auf den folgenden Link klickst:',
'%Placeholder%', // placeholder
'Bis bald und viele Grüße, Tobias'
];
// mail contents
$mail = array(
"subject" => 'Newsletter-Anmeldung bestaetigen',
"bodyHTML" => "<p>" . implode("</p><p>", $body) . "</p>",
"bodyText" => implode("\n\n", $body)
);
$mailConfirmation = [
'subject' => 'Newsletter-Anmeldung bestaetigen',
'bodyHTML' => '<p>' . implode('</p><p>', $bodyConfirmation) . '</p>',
'bodyText' => implode("\n\n", $bodyConfirmation)
];
// DB constants
$db = array(
"host" => "",
"port" => "",
"username" => "",
"password" => ""
);
$db = [
'host' => '',
'port' => '',
'username' => '',
'password' => ''
];
function SanitizeInputs($var) {
return htmlspecialchars($var, ENT_QUOTES);
function SendEmail($recipientAddress, $mailContents, $link = NULL) {
global $general, $smtp;
$mail = new PHPMailer(true);
try {
//Server settings
// $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mail->isSMTP();
$mail->Host = $smtp["host"];
$mail->SMTPAuth = $smtp["auth"];
$mail->Username = $smtp["username"];
$mail->Password = $smtp["password"];
//$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
$mail->Port = $smtp["port"]; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
//Recipients
$mail->setFrom($smtp["fromAddress"], $smtp["fromName"]);
$mail->addAddress($recipientAddress); //Add a recipient
//Content
if (isset($link)) {
$mailContents["bodyHTML"] = str_replace("%Placeholder%", $link, $mailContents["bodyHTML"]);
$mailContents["bodyText"] = str_replace("%Placeholder%", $link, $mailContents["bodyText"]);
}
$mail->CharSet = "UTF-8";
$mail->isHTML(true);
$mail->Subject = $mailContents["subject"];
$mail->Body = $mailContents["bodyHTML"];
$mail->AltBody = $mailContents["bodyText"];
$mail->send();
return TRUE;
} catch (Exception $e) {
error_log("Message error: {$e}");
return FALSE;
}
}
function SanitizeEmail ($var) {
$sane = htmlspecialchars($var, ENT_QUOTES);
$pattern = "/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/";
preg_match($pattern, $sane, $res);
$r = $res[0] ? $res[0] : false;
return $r;
}
function CheckConfirmationHash($confEmail, $confCode) {
function GracefulExit($location, $message = NULL) {
global $general;
return (md5($confEmail . $general["uniqueKey"]) === $confCode);
header($general['statusCode']);
if (isset($message)) {
$location .= "?" . http_build_query(['msg' => $message]);
error_log($location);
}
header("Location: {$location}");
}
?>

View File

@ -1,73 +1,33 @@
<?php
// inspired by https://www.mailgun.com/blog/email/double-opt-in-with-php-mailgun/
// import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$successURL = '/newsletter/subscribed.html';
$errorURL = '/newsletter/subscribe-error.html';
$dname = dirname(__FILE__);
require $dname . '/Exception.php';
require $dname . '/PHPMailer.php';
require $dname . '/SMTP.php';
require(dirname(__FILE__) . '/settings.php');
function MakeConfirmationHash($confEmail, $confCode) {
return md5($confEmail . $confCode);
}
function SendConfirmationEmail($recipientAddress) {
global $general, $smtp, $mail;
$hashedUnique = MakeConfirmationHash($recipientAddress, $general["uniqueKey"]);
$confirmQuery = http_build_query(["c" => $hashedUnique, "e" => $recipientAddress]);
$confirmURL = $general["siteURL"] . $general["confirmScript"] . "?" . $confirmQuery;
// create PHPMailer instance
$mailer = new PHPMailer(true);
try {
//Server settings
// $mailer->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mailer->isSMTP();
$mailer->Host = $smtp["host"];
$mailer->SMTPAuth = $smtp["auth"];
$mailer->Username = $smtp["username"];
$mailer->Password = $smtp["password"];
//$mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
$mailer->Port = $smtp["port"]; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
//Recipients
$mailer->setFrom($smtp["fromAddress"], $smtp["fromName"]);
$mailer->addAddress($recipientAddress); //Add a recipient
//Content
$mailer->CharSet = "UTF-8";
$mailer->isHTML(true);
$mailer->Subject = $mail["subject"];
$mailer->Body = str_replace("%confirmURL%", $confirmURL, $mail["bodyHTML"]);
$mailer->AltBody = str_replace("%confirmURL%", $confirmURL, $mail["bodyText"]);
$mailer->send();
return TRUE;
} catch (Exception $e) {
error_log("Message error: " . $e);
return FALSE;
}
}
require($dname . "/settings.php");
if (isset($_POST['email'])) {
$email = SanitizeEmail(trim($_POST['email']));
// error_log("Received subscription request for address " . $email . " ..."); //DEBUG
$result = SendConfirmationEmail($email);
if ( $result == TRUE ) {
header('Location: /newsletter/subscribed.html');
error_log("Message to " . $email . " has been sent.");
if (isset($_POST['email'])) {
$email = filter_var(trim($_POST['email'], FILTER_SANITIZE_STRING));
error_log("Email ist: {$email}");
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$hashedUnique = MakeConfirmationHash($email, $general['uniqueKey']);
$confirmQuery = http_build_query(['c' => $hashedUnique, 'e' => $email]);
$confirmLink = $general['siteURL'] . $general['confirmScript'] . "?" . $confirmQuery;
$result = SendEmail($email, $mailConfirmation, $confirmLink);
if ( $result == TRUE ) {
GracefulExit($successURL, 'Anmeldung wird fortgesetzt: Email mit Bestätigungslink wurde versandt.');
} else {
GracefulExit($errorURL, 'Anmeldung fehlgeschlagen: Fehler beim Versenden der Bestätigungs-Email.');
}
} else {
header('Location: /newsletter/subscribe-error.html');
error_log("Message to " . $email . " could not be sent.");
GracefulExit($errorURL, 'Anmeldung fehlgeschlagen: Ungültige Emailadresse.');
}
} else {
GracefulExit($errorURL, 'Anmeldung fehlgeschlagen: Keine Emailadresse angegeben.');
}
?>

View File

@ -1,18 +1,27 @@
<?php
function RemoveSubscriberfromDB($subscriberAddress) {
error_log("removing subscriber " . $subscriberAddress . " from DB ...");
require(dirname(__FILE__) . '/settings.php');
$successURL = '/newsletter/unsubscribed.html';
$errorURL = '/newsletter/unsubscribe-error.html';
function RemoveSubscriberFromDB($subscriberAddress) {
error_log("removing subscriber {$subscriberAddress} from DB ...");
return TRUE;
}
require(dirname(__FILE__) . "/settings.php");
$email = isset($_GET['e']) ? SanitizeInputs($_GET['e']) : NULL;
if (isset($email)) {
$r = RemoveSubscriberfromDB($email);
if ($r) {
header('Location: /newsletter/unsubscribed.html');
if (isset($_GET['e'])) {
$e = filter_var($_GET["e"], FILTER_SANITIZE_STRING);
$result = RemoveSubscriberFromDB($e);
if ($result == TRUE) {
GracefulExit($successURL, "Abmeldung für {$e} erfolgreich.");
} elseif (gettype($result == 'string')) {
GracefulExit($errorURL, "Abmeldung fehlgeschlagen: {$result}");
} else {
header('Location: /newsletter/unsubscribe-error.html');
GracefulExit($errorURL, 'Abmeldung fehlgeschlagen: Unbekannter Fehler');
}
} else {
GracefulExit($errorURL, 'Abmeldung fehlgeschlagen: Fehlerhafte Emailadresse');
}
?>