rewrote and tested contact script, moved some files around

This commit is contained in:
eclipse 2025-03-04 23:10:35 +01:00
parent 1a8948704c
commit 5e735d6a9a
4 changed files with 70 additions and 70 deletions

View File

@ -4,11 +4,9 @@ date: 2025-03-03 17:19
author: Tobias Radloff author: Tobias Radloff
summary: Ein Fehler ist aufgetreten summary: Ein Fehler ist aufgetreten
lang: de lang: de
slug: error save_as: error.html
save_as: newsletter/error.html
url: newsletter/error.html
featured_image: featured_image:
- pic: ../images/newsletter/error-unsplash.jpg - pic: ../images/error-unsplash.jpg
alt: eine Frau vor einem Laptop stützt geknickt den Kopf in die Hände alt: eine Frau vor einem Laptop stützt geknickt den Kopf in die Hände
credit: Elisa Ventur on Unsplash.com credit: Elisa Ventur on Unsplash.com
--- ---

View File

@ -1,18 +1,37 @@
<?php <?php
//source: https://www.unixdude.net/posts/2017/Nov/29/pelican-contact-form/ // inspired by: https://www.unixdude.net/posts/2017/Nov/29/pelican-contact-form/
if(isset($_POST['address']) && $_POST['address'] == ''){
//The form was submitted // The 'address' form field is in the code but doesn't get rendered on the page. The message will only get sent if the field is empty, thus weeding out bots that will just fill out any form field
$ouremail = 'kontakt@tobias-radloff.de'; if ( $_POST['address'] != '' ) {
// Important: if we add any form fields to the HTML, header('Location: /');
// and want them included in the email, we will need to add them here also exit;
$body = "Diese Nachricht wurde soeben durch das Kontaktformular auf t-r.de übermittelt: }
Name: $_POST[name]
Emailadresse: $_POST[email] require(dirname(__FILE__) . '/../settings.php');
Nachricht: $_POST[nachricht]";
// From: $successURL = '/success.html';
$headers = "From: $_POST[email]"; $errorURL = '/error.html';
// send the message $err = 'Nachrichtversand fehlgeschlagen';
mail($ouremail, 'Nachricht ueber das Kontaktformular von t-r.de!', $body, $headers );
header('Location: /kontakt/danke/'); $body = [
} 'Diese Nachricht wurde soeben durch das Kontaktformular auf t-r.de übermittelt:',
"Name: {$_POST['name']}",
"Emailadresse: {$_POST['email']}",
"Nachricht: {$_POST['nachricht']}"
];
$mailContents = [
'subject' => 'Diese Nachricht kam ueber das Kontaktformular von t-r.de',
'bodyText' => implode("\n\n", $body),
'fromAddress' => '***REMOVED***', //'kontakt@tobias-radloff.de',
'fromName' => 'Tobias Radloffs Kontaktformular'
];
try {
sendEmail($_POST['email'], $mailContents);
} catch (Exception $e) {
GracefulExit($errorURL, "{$err}: {$e->getMessage()}");
}
header("Location: {$successURL}");
?> ?>

View File

@ -5,9 +5,9 @@ use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception; use PHPMailer\PHPMailer\Exception;
$dname = dirname(__FILE__); $dname = dirname(__FILE__);
require $dname . '/../Exception.php'; require $dname . '/Exception.php';
require $dname . '/../PHPMailer.php'; require $dname . '/PHPMailer.php';
require $dname . '/../SMTP.php'; require $dname . '/SMTP.php';
// general constants // general constants
$general = [ $general = [
@ -39,23 +39,6 @@ $smtp = [
'username' => 'tobias', 'username' => 'tobias',
'password' => '***REMOVED***', 'password' => '***REMOVED***',
'auth' => TRUE, 'auth' => TRUE,
'fromAddress' => '***REMOVED***', // 'newsletter@tobias-radloff.de'
'fromName' => 'Tobias Radloffs Newsletter',
];
// body of confirmation email
$bodyConfirmation = [
'Hallo!',
'Bitte bestätige die Anmeldung für meinen Newsletter, indem du auf den folgenden Link klickst:',
'%Placeholder%',
'Bis bald und viele Grüße, Tobias'
];
// contents of confirmation email
$mailConfirmation = [
'subject' => 'Newsletter-Anmeldung bestaetigen',
'bodyHTML' => '<p>' . implode('</p><p>', $bodyConfirmation) . '</p>',
'bodyText' => implode("\n\n", $bodyConfirmation)
]; ];
// database information // database information
@ -83,36 +66,38 @@ function getPDO($dbType = 'sqlite') {
return new \PDO($db[$dbType]['dsn']); return new \PDO($db[$dbType]['dsn']);
} }
// Sends an email to single recipient with subject and body specified in an array // Sends an email to single recipient with subject, body and sender info specified in an array
function SendEmail($recipientAddress, $mailContents, $link = NULL) { function SendEmail($recipientAddress, $mailContents) {
global $general, $smtp; global $general, $smtp;
$mail = new PHPMailer(true); $mail = new PHPMailer(true);
//Server settings //Server settings
// $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output // $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mail->isSMTP(); $mail->isSMTP();
$mail->Host = $smtp["host"]; $mail->Host = $smtp['host'];
$mail->SMTPAuth = $smtp["auth"]; $mail->SMTPAuth = $smtp['auth'];
$mail->Username = $smtp["username"]; $mail->Username = $smtp['username'];
$mail->Password = $smtp["password"]; $mail->Password = $smtp['password'];
//$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption //$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` $mail->Port = $smtp['port']; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
//Recipients // recipient
$mail->setFrom($smtp["fromAddress"], $smtp["fromName"]);
$mail->addAddress($recipientAddress); //Add a recipient $mail->addAddress($recipientAddress); //Add a recipient
//Content // content
if (isset($link)) { $mail->CharSet = 'UTF-8';
$mailContents["bodyHTML"] = str_replace("%Placeholder%", $link, $mailContents["bodyHTML"]); if ( isset($mailContents['bodyHTML']) and $mailContents['bodyHTML'] != '' ) {
$mailContents["bodyText"] = str_replace("%Placeholder%", $link, $mailContents["bodyText"]); $mail->isHTML(true);
$mail->Body = $mailContents['bodyHTML'];
$mail->AltBody = $mailContents['bodyText'];
} else {
$mail->isHTML(false);
$mail->Body = $mailContents['bodyText'];
} }
$mail->CharSet = "UTF-8"; $mail->Subject = $mailContents['subject'];
$mail->isHTML(true); $mail->setFrom($mailContents['fromAddress'], $mailContents['fromName']);
$mail->Subject = $mailContents["subject"];
$mail->Body = $mailContents["bodyHTML"];
$mail->AltBody = $mailContents["bodyText"];
// send
$mail->send(); $mail->send();
} }
@ -121,33 +106,29 @@ function MakeSureTableExists($pdo) {
global $general; global $general;
$query = $pdo->prepare($general['sql']['create_table']); $query = $pdo->prepare($general['sql']['create_table']);
if ( ! $query->execute() ) { if ( ! $query->execute() ) {
// error_log('Unbekannter Datenbankfehler beim Prüfen/Erzeugen der Tabelle.'); return 'Unbekannter Datenbankfehler';
return "Unbekannter Datenbankfehler";
} }
return TRUE; return TRUE;
} }
// returns true if record does not yet exist in database; error string otherwise // returns true if record does not yet exist in database; error string otherwise
function NotAlreadySubscribed($email, $pdo = NULL) { function NotYetSubscribed($email, $pdo = NULL) {
if (!isset($pdo)) { if (!isset($pdo)) {
$pdo = getPDO(); $pdo = getPDO();
} }
$result = MakeSureTableExists($pdo); $result = MakeSureTableExists($pdo);
if ( gettype($result) == "string" ) { if ( gettype($result) == 'string' ) {
// error_log("Datenbankfehler beim Adresscheck: {$result}");
return $result; return $result;
} }
global $general; global $general;
$query = $pdo->prepare($general['sql']['read_record']); $query = $pdo->prepare($general['sql']['read_record']);
if ( ! $query->execute([':e' => $email]) ) { if ( ! $query->execute([':e' => $email]) ) {
// error_log("Datenbankfehler: Adresscheck für Emailadresse {$email} ergab einen Fehler."); return 'Fehler beim Zugriff auf Datenbank';
return "Fehler beim Zugriff auf Datenbank";
} }
if ( $query->fetch() ) { if ( $query->fetch() ) {
// error_log("Adresscheck: Emailadresse {$email} ist bereits eingetragen.");
return "Emailadresse {$email} ist bereits eingetragen"; return "Emailadresse {$email} ist bereits eingetragen";
} }
@ -155,13 +136,14 @@ function NotAlreadySubscribed($email, $pdo = NULL) {
return TRUE; return TRUE;
} }
// redirects to specified URL via GET request and conveys an optional message; then exits // redirects to specified URL via GET request and conveys an optional message; then exits
function GracefulExit($location, $message = NULL) { function GracefulExit($location, $message = NULL) {
global $general; global $general;
header($general['statusCode']); header($general['statusCode']);
if (isset($message)) { if (isset($message)) {
$location .= "?" . http_build_query(['msg' => $message]); $location .= '?' . http_build_query(['msg' => $message]);
error_log($location); error_log("Redirecting to {$location} now …");
} }
header("Location: {$location}"); header("Location: {$location}");
exit; exit;

View File

@ -21,13 +21,14 @@ PATH = "content"
ARTICLE_PATHS = ["posts"] ARTICLE_PATHS = ["posts"]
PAGE_PATHS = ["pages"] PAGE_PATHS = ["pages"]
STATIC_PATHS = ["images", "favicon", "php"] STATIC_PATHS = ["images", "favicon", "php"]
# TEMPLATE_PAGES = { 'templates/cform.html': 'cform.html', }
DIRECT_TEMPLATES = ['index', 'tags'] DIRECT_TEMPLATES = ['index', 'tags']
IGNORE_FILES = ['**/.*', '__pycache__', 'favicon-from-svg.sh', '*.metadata'] IGNORE_FILES = ['**/.*', '__pycache__', 'favicon-from-svg.sh', '*.metadata']
EXTRA_PATH_METADATA = { EXTRA_PATH_METADATA = {
'favicon/favicon.ico': {'path': 'favicon.ico'}, 'favicon/favicon.ico': {'path': 'favicon.ico'},
'php/settings.php': {'path': 'newsletter/settings.php'}, 'php/settings.php': {'path': 'settings.php'},
'php/subscribe.php': {'path': 'newsletter/subscribe.php'}, 'php/subscribe.php': {'path': 'newsletter/subscribe.php'},
'php/confirm.php': {'path': 'newsletter/confirm.php'}, 'php/confirm.php': {'path': 'newsletter/confirm.php'},
'php/unsubscribe.php': {'path': 'newsletter/unsubscribe.php'}, 'php/unsubscribe.php': {'path': 'newsletter/unsubscribe.php'},
@ -123,5 +124,5 @@ JINJA_ENVIRONMENT = { "extensions": ["jinja2.ext.debug", "jinja2.ext.do"] }
# Self-defined Settings # # Self-defined Settings #
############################################################################### ###############################################################################
STYLESHEET_FILES = ("pico.amber.css", "custom.css") STYLESHEET_FILES = ("pico.zinc.css", "custom.css")
DEFAULT_METADESC = "Tobias Radloff ist preisgekrönter Schriftsteller von Romanen, Kurzgeschichten und Lyrik auf deutsch und englisch. Zu seinen Genres gehören Fantasy, SF, Krimi, Kinder-/Jugendbuch und mehr. Er organisiert und moderiert die regelmäßigen Lesereihen 'Potsdams andere Welten' und 'Babelsberger Lesesalon'." DEFAULT_METADESC = "Tobias Radloff ist preisgekrönter Schriftsteller von Romanen, Kurzgeschichten und Lyrik auf deutsch und englisch. Zu seinen Genres gehören Fantasy, SF, Krimi, Kinder-/Jugendbuch und mehr. Er organisiert und moderiert die regelmäßigen Lesereihen 'Potsdams andere Welten' und 'Babelsberger Lesesalon'."