| Server IP : 188.114.96.3 / Your IP : 216.73.216.143 Web Server : Apache System : Linux sv058.home.net.pl 6.8.2 husak_dirty_pages_fix #1 SMP PREEMPT_DYNAMIC Tue Apr 2 22:06:51 CEST 2024 x86_64 User : ( 3194769) PHP Version : 8.5.12 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : OFF Directory : /polana/includes/ |
Upload File : |
<?php
declare(strict_types=1);
/* POLANA NEWSLETTER V1.1 */
function newsletter_db(): PDO {
if (!function_exists('db')) {
throw new RuntimeException('Brak funkcji db().');
}
$pdo = db();
if (!$pdo instanceof PDO) throw new RuntimeException('db() nie zwróciło PDO.');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
function newsletter_install_table(): void {
$sql = <<<SQL
CREATE TABLE IF NOT EXISTS newsletter_subscribers (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
email VARCHAR(190) NOT NULL,
name VARCHAR(150) NULL,
source VARCHAR(50) NOT NULL DEFAULT 'footer',
status VARCHAR(20) NOT NULL DEFAULT 'active',
consent_at DATETIME NOT NULL,
withdrawn_at DATETIME NULL,
consent_ip_hash CHAR(64) NULL,
user_agent VARCHAR(255) NULL,
unsubscribe_token CHAR(64) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_newsletter_email (email),
UNIQUE KEY uq_newsletter_token (unsubscribe_token),
KEY idx_newsletter_status (status),
KEY idx_newsletter_consent_at (consent_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL;
newsletter_db()->exec($sql);
}
function newsletter_email_from_post(): string {
foreach (['email','reservation_email','guest_email','customer_email'] as $k) {
$v = trim((string)($_POST[$k] ?? ''));
if ($v !== '' && filter_var($v, FILTER_VALIDATE_EMAIL)) return mb_strtolower($v,'UTF-8');
}
return '';
}
function newsletter_name_from_post(): string {
foreach (['name','guest_name','customer_name','full_name','fullname','first_name'] as $k) {
$v = trim((string)($_POST[$k] ?? ''));
if ($v !== '') return mb_substr($v,0,150,'UTF-8');
}
return '';
}
function newsletter_ip_hash(): ?string {
$ip = trim((string)($_SERVER['REMOTE_ADDR'] ?? ''));
if ($ip === '') return null;
return hash('sha256', 'polana-newsletter|' . $ip);
}
function newsletter_subscribe(string $email, string $name='', string $source='footer'): array {
newsletter_install_table();
$email = mb_strtolower(trim($email),'UTF-8');
$name = trim($name);
$source = trim($source) ?: 'footer';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return ['ok'=>false,'message'=>'Podaj poprawny adres e-mail.'];
}
$pdo = newsletter_db();
$check = $pdo->prepare('SELECT id, unsubscribe_token FROM newsletter_subscribers WHERE email=:email LIMIT 1');
$check->execute([':email'=>$email]);
$row = $check->fetch(PDO::FETCH_ASSOC);
$token = $row && !empty($row['unsubscribe_token'])
? (string)$row['unsubscribe_token']
: bin2hex(random_bytes(32));
$ua = mb_substr(trim((string)($_SERVER['HTTP_USER_AGENT'] ?? '')),0,255,'UTF-8');
$ipHash = newsletter_ip_hash();
if ($row) {
$st = $pdo->prepare(
'UPDATE newsletter_subscribers
SET name=:name, source=:source, status="active", consent_at=NOW(),
withdrawn_at=NULL, consent_ip_hash=:ip, user_agent=:ua,
unsubscribe_token=:token
WHERE id=:id'
);
$st->execute([
':name'=>$name !== '' ? $name : null,
':source'=>$source,
':ip'=>$ipHash,
':ua'=>$ua !== '' ? $ua : null,
':token'=>$token,
':id'=>$row['id'],
]);
} else {
$st = $pdo->prepare(
'INSERT INTO newsletter_subscribers
(email,name,source,status,consent_at,consent_ip_hash,user_agent,unsubscribe_token)
VALUES (:email,:name,:source,"active",NOW(),:ip,:ua,:token)'
);
$st->execute([
':email'=>$email,
':name'=>$name !== '' ? $name : null,
':source'=>$source,
':ip'=>$ipHash,
':ua'=>$ua !== '' ? $ua : null,
':token'=>$token,
]);
}
return ['ok'=>true,'message'=>'Dziękujemy! Jesteś na liście Mojej Polany Smaków.','token'=>$token];
}
function newsletter_unsubscribe(string $token): bool {
newsletter_install_table();
if (!preg_match('/^[a-f0-9]{64}$/i',$token)) return false;
$st = newsletter_db()->prepare(
'UPDATE newsletter_subscribers
SET status="unsubscribed", withdrawn_at=NOW()
WHERE unsubscribe_token=:token'
);
$st->execute([':token'=>$token]);
return $st->rowCount() > 0;
}
function newsletter_handle_reservation_optin(): void {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;
if (empty($_POST['newsletter_optin'])) return;
$email = newsletter_email_from_post();
if ($email === '') return;
try {
newsletter_subscribe($email, newsletter_name_from_post(), 'reservation');
} catch (Throwable $e) {
error_log('[POLANA NEWSLETTER reservation] '.$e->getMessage());
}
}
function newsletter_render_footer(): void {
?>
<section class="newsletter-strip" aria-labelledby="newsletter-title">
<div class="newsletter-strip__inner">
<div class="newsletter-strip__copy">
<span class="newsletter-strip__eyebrow">Z Polany prosto do skrzynki</span>
<h2 id="newsletter-title">Bądź na bieżąco z tym, co dzieje się na Polanie.</h2>
<p>Nowe menu, sezonowe smaki, wydarzenia i rzeczy, o których warto wiedzieć wcześniej.</p>
</div>
<form class="newsletter-strip__form" method="post" action="<?= e(polana_local_path('/newsletter.php')) ?>" autocomplete="on">
<label class="newsletter-strip__label" for="newsletter-email">Twój e-mail</label>
<div class="newsletter-strip__row">
<input id="newsletter-email" type="email" name="email" autocomplete="email" placeholder="[email protected]" required>
<button type="submit">Zapisz mnie</button>
</div>
<label class="newsletter-consent">
<input type="checkbox" name="newsletter_consent" value="1" required>
<span>Chcę otrzymywać newsletter Mojej Polany Smaków z informacjami o menu, wydarzeniach i nowościach. Zgoda jest dobrowolna i mogę ją wycofać w każdej chwili.</span>
</label>
<input type="hidden" name="source" value="footer">
</form>
</div>
</section>
<?php
}