t-r.de/content/misc/subscribe.php

70 lines
2.4 KiB
PHP

<?php
// inspired by https://www.mailgun.com/blog/email/double-opt-in-with-php-mailgun/
$webroot = $_SERVER['DOCUMENT_ROOT'];
require($webroot . '/functions.php');
$successURL = '/success.html';
$errorURL = '/error.html';
$err = 'Anmeldung fehlgeschlagen';
// file name of confirm script
$confirmScript = '/newsletter/confirm.php';
// body template for confirmation email
$body = [
'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
$mailContents = [
'subject' => 'Newsletter-Anmeldung bestaetigen',
'bodyHTML' => '<p>' . implode('</p><p>', $body) . '</p>',
'bodyText' => implode("\n\n", $body),
'fromAddress' => '***REMOVED***', // 'newsletter@tobias-radloff.de'
'fromName' => 'Tobias Radloffs Newsletter'
];
// check if email parameter is set
if ( ! isset($_POST['email']) ) {
GracefulExit($errorURL, "{$err}: Keine Emailadresse angegeben.");
}
// check if it's a well-formed email address
$email = filter_var(trim($_POST['email'], FILTER_SANITIZE_STRING));
if ( ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
GracefulExit($errorURL, "{$err}: Ungültige Emailadresse {$email}");
}
// check whether address is already subscribed
try {
$check = NotYetSubscribed($email);
if ( gettype($check) == 'string' ) {
GracefulExit($errorURL, "{$err}: {$check}.");
}
} catch (\PDOException $e) {
GracefulExit($errorURL, "{$err}: {$e->getMessage()}");
}
// build and add link to
$confirmQuery = http_build_query(['c' => GetConfirmationHash($email), 'e' => $email]);
$confirmLink = $general['site_url'] . $confirmScript . "?" . $confirmQuery;
$mailContents['bodyHTML'] = str_replace('%Placeholder%', "<a href=\"{$confirmLink}\">Anmeldung bestätigen</a>", $mailContents['bodyHTML']);
$mailContents['bodyText'] = str_replace('%Placeholder%', $confirmLink, $mailContents['bodyText']);
// send email
try {
SendEmail($email, $mailContents);
} catch (Exception $e) {
GracefulExit($errorURL, "{$err}: {$e->getMessage()}");
}
// success
$mailContents['subject'] = 'Jemand will den Newsletter abonnieren und hat gerade eine Kopie dieser Mail bekommen';
SendEmail($general['notificationAddress'], $mailContents);
GracefulExit($successURL, "Anmeldung erfolgreich: Email mit Bestätigungslink wurde an {$email} versandt.");
?>