Files
eportfolio/www/contact.php
T

166 lines
5.8 KiB
PHP

<?php
/**
* Portfolio contact form -> Proton Mail (SMTP submission)
*
* Receives the form as JSON from js/main.js and sends it to your inbox
* through smtp.protonmail.ch:587 (STARTTLS).
* No secret lives in this file: the SMTP token is read from
* ../portfolio-private/smtp-config.php, outside the web root.
*/
declare(strict_types=1);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as MailException;
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store');
function reply(int $code, bool $ok, string $msg): never
{
http_response_code($code);
echo json_encode(['success' => $ok, 'message' => $msg]);
exit;
}
// ---------- Private folder (outside the web root) ----------
$private = getenv('PORTFOLIO_PRIVATE_DIR') ?: dirname(__DIR__) . '/portfolio-private';
$configFile = $private . '/smtp-config.php';
if (!is_readable($configFile)) {
error_log("contact.php: config not readable at $configFile");
reply(500, false, 'The contact form is not configured yet.');
}
$cfg = require $configFile;
require $private . '/PHPMailer/Exception.php';
require $private . '/PHPMailer/PHPMailer.php';
require $private . '/PHPMailer/SMTP.php';
// ---------- Request checks ----------
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
reply(405, false, 'Method not allowed.');
}
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if ($origin !== '' && !in_array($origin, $cfg['allowed_origins'] ?? [], true)) {
reply(403, false, 'Forbidden.');
}
$raw = (string) file_get_contents('php://input', false, null, 0, 20000);
$in = json_decode($raw, true);
if (!is_array($in)) {
reply(400, false, 'Invalid request.');
}
// Honeypot: bots tick the hidden box. Pretend it worked, send nothing.
if (!empty($in['botcheck'])) {
reply(200, true, 'Message sent.');
}
// ---------- Validation ----------
function field(array $in, string $key, int $max): string
{
return mb_substr(trim((string) ($in[$key] ?? '')), 0, $max);
}
$first = field($in, 'first_name', 60);
$last = field($in, 'last_name', 60);
$name = trim($first . ' ' . $last);
$phone = field($in, 'phone', 30);
$email = field($in, 'email', 150);
$company = field($in, 'company', 100);
$subject = field($in, 'subject', 150);
$message = field($in, 'message', 4000);
// Header-bound fields must not contain line breaks (header injection).
foreach ([$first, $last, $email, $phone, $company, $subject] as $v) {
if (preg_match('/[\r\n]/', $v)) {
reply(400, false, 'Invalid characters in the form.');
}
}
if ($first === '' || $last === '' || $subject === '' || $message === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
reply(422, false, 'Fill in the required fields (*) with a valid email address.');
}
if ($phone !== '' && !preg_match('/^[0-9+().\/ -]{6,30}$/', $phone)) {
reply(422, false, 'The phone number looks invalid.');
}
if (empty($in['consent'])) {
reply(422, false, 'Please tick the consent box so I can reply to you.');
}
// ---------- Rate limit per IP ----------
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$store = sys_get_temp_dir() . '/portfolio-contact-' . hash('sha256', $ip . ($cfg['rate_salt'] ?? ''));
$now = time();
$hits = [];
// Forget visitors after one hour: delete expired rate-limit files
foreach (glob(sys_get_temp_dir() . '/portfolio-contact-*') ?: [] as $old) {
if (@filemtime($old) < $now - 3600) {
@unlink($old);
}
}
if (is_readable($store)) {
foreach (explode(',', (string) file_get_contents($store)) as $t) {
if ((int) $t > $now - 3600) {
$hits[] = (int) $t;
}
}
}
if (count($hits) >= (int) ($cfg['max_per_hour'] ?? 5)) {
reply(429, false, 'Too many messages from your connection. Try again in an hour.');
}
// ---------- Send through Proton ----------
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = $cfg['smtp_host'] ?? 'smtp.protonmail.ch';
$mail->Port = (int) ($cfg['smtp_port'] ?? 587);
$mail->SMTPSecure = $cfg['smtp_secure'] ?? PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPAutoTLS = $mail->SMTPSecure !== '';
$mail->SMTPAuth = $cfg['smtp_auth'] ?? true;
$mail->Username = $cfg['smtp_user'];
$mail->Password = $cfg['smtp_token'];
$mail->CharSet = PHPMailer::CHARSET_UTF8;
$mail->Timeout = 15;
// Proton only accepts the address tied to the token as sender.
$mail->setFrom($cfg['smtp_user'], 'Portfolio: ' . $name);
$mail->addAddress($cfg['to']);
$mail->addReplyTo($email, $name); // "Reply" answers the visitor directly
$mail->Subject = '[Portfolio] ' . $subject;
$mail->isHTML(false);
// Site name: from the (already validated) Origin, else the configured name
$site = $cfg['site_name'] ?? '';
if ($site === '') {
$site = (string) (parse_url($origin, PHP_URL_HOST) ?: ($_SERVER['HTTP_HOST'] ?? 'portfolio'));
}
date_default_timezone_set($cfg['timezone'] ?? 'Europe/Paris');
$line = str_repeat('-', 60);
$or = fn(string $v): string => $v !== '' ? $v : '-';
$body = str_replace(["\r\n", "\r"], "\n", $message);
$mail->Body =
"Nouveau message depuis le formulaire de contact de $site\n"
. "$line\n"
. "Prénom : $first\n"
. "Nom : $last\n"
. "E-mail : $email\n"
. 'Téléphone: ' . $or($phone) . "\n"
. 'Société : ' . $or($company) . "\n"
. "Objet : $subject\n"
. "$line\n\n"
. $body . "\n\n"
. "$line\n"
. "IP: $ip — " . date('Y-m-d H:i:s') . "\n";
$mail->send();
$hits[] = $now;
file_put_contents($store, implode(',', $hits), LOCK_EX);
reply(200, true, "Message sent. Thanks, I'll get back to you soon.");
} catch (MailException $e) {
error_log('contact.php SMTP error: ' . $mail->ErrorInfo);
reply(502, false, 'The message could not be sent.');
}