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
summary: Ein Fehler ist aufgetreten
lang: de
slug: error
save_as: newsletter/error.html
url: newsletter/error.html
save_as: error.html
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
credit: Elisa Ventur on Unsplash.com
---

View File

@ -1,18 +1,37 @@
<?php
//source: https://www.unixdude.net/posts/2017/Nov/29/pelican-contact-form/
if(isset($_POST['address']) && $_POST['address'] == ''){
//The form was submitted
$ouremail = 'kontakt@tobias-radloff.de';
// Important: if we add any form fields to the HTML,
// and want them included in the email, we will need to add them here also
$body = "Diese Nachricht wurde soeben durch das Kontaktformular auf t-r.de übermittelt:
Name: $_POST[name]
Emailadresse: $_POST[email]
Nachricht: $_POST[nachricht]";
// From:
$headers = "From: $_POST[email]";
// send the message
mail($ouremail, 'Nachricht ueber das Kontaktformular von t-r.de!', $body, $headers );
header('Location: /kontakt/danke/');
// inspired by: https://www.unixdude.net/posts/2017/Nov/29/pelican-contact-form/
// 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
if ( $_POST['address'] != '' ) {
header('Location: /');
exit;
}
require(dirname(__FILE__) . '/../settings.php');
$successURL = '/success.html';
$errorURL = '/error.html';
$err = 'Nachrichtversand fehlgeschlagen';
$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;
$dname = dirname(__FILE__);
require $dname . '/../Exception.php';
require $dname . '/../PHPMailer.php';
require $dname . '/../SMTP.php';
require $dname . '/Exception.php';
require $dname . '/PHPMailer.php';
require $dname . '/SMTP.php';
// general constants
$general = [
@ -39,23 +39,6 @@ $smtp = [
'username' => 'tobias',
'password' => '***REMOVED***',
'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
@ -83,36 +66,38 @@ function getPDO($dbType = 'sqlite') {
return new \PDO($db[$dbType]['dsn']);
}
// Sends an email to single recipient with subject and body specified in an array
function SendEmail($recipientAddress, $mailContents, $link = NULL) {
// Sends an email to single recipient with subject, body and sender info specified in an array
function SendEmail($recipientAddress, $mailContents) {
global $general, $smtp;
$mail = new PHPMailer(true);
//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->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`
$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"]);
// recipient
$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";
// content
$mail->CharSet = 'UTF-8';
if ( isset($mailContents['bodyHTML']) and $mailContents['bodyHTML'] != '' ) {
$mail->isHTML(true);
$mail->Subject = $mailContents["subject"];
$mail->Body = $mailContents["bodyHTML"];
$mail->AltBody = $mailContents["bodyText"];
$mail->Body = $mailContents['bodyHTML'];
$mail->AltBody = $mailContents['bodyText'];
} else {
$mail->isHTML(false);
$mail->Body = $mailContents['bodyText'];
}
$mail->Subject = $mailContents['subject'];
$mail->setFrom($mailContents['fromAddress'], $mailContents['fromName']);
// send
$mail->send();
}
@ -121,33 +106,29 @@ function MakeSureTableExists($pdo) {
global $general;
$query = $pdo->prepare($general['sql']['create_table']);
if ( ! $query->execute() ) {
// error_log('Unbekannter Datenbankfehler beim Prüfen/Erzeugen der Tabelle.');
return "Unbekannter Datenbankfehler";
return 'Unbekannter Datenbankfehler';
}
return TRUE;
}
// 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)) {
$pdo = getPDO();
}
$result = MakeSureTableExists($pdo);
if ( gettype($result) == "string" ) {
// error_log("Datenbankfehler beim Adresscheck: {$result}");
if ( gettype($result) == 'string' ) {
return $result;
}
global $general;
$query = $pdo->prepare($general['sql']['read_record']);
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() ) {
// error_log("Adresscheck: Emailadresse {$email} ist bereits eingetragen.");
return "Emailadresse {$email} ist bereits eingetragen";
}
@ -155,13 +136,14 @@ function NotAlreadySubscribed($email, $pdo = NULL) {
return TRUE;
}
// redirects to specified URL via GET request and conveys an optional message; then exits
function GracefulExit($location, $message = NULL) {
global $general;
header($general['statusCode']);
if (isset($message)) {
$location .= "?" . http_build_query(['msg' => $message]);
error_log($location);
$location .= '?' . http_build_query(['msg' => $message]);
error_log("Redirecting to {$location} now …");
}
header("Location: {$location}");
exit;

View File

@ -21,13 +21,14 @@ PATH = "content"
ARTICLE_PATHS = ["posts"]
PAGE_PATHS = ["pages"]
STATIC_PATHS = ["images", "favicon", "php"]
# TEMPLATE_PAGES = { 'templates/cform.html': 'cform.html', }
DIRECT_TEMPLATES = ['index', 'tags']
IGNORE_FILES = ['**/.*', '__pycache__', 'favicon-from-svg.sh', '*.metadata']
EXTRA_PATH_METADATA = {
'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/confirm.php': {'path': 'newsletter/confirm.php'},
'php/unsubscribe.php': {'path': 'newsletter/unsubscribe.php'},
@ -123,5 +124,5 @@ JINJA_ENVIRONMENT = { "extensions": ["jinja2.ext.debug", "jinja2.ext.do"] }
# 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'."