config.php. * Requires PHP 7.4+ (mbstring optional). */ if (!file_exists(__DIR__ . '/config.php')) { http_response_code(500); header('Content-Type: application/json; charset=utf-8'); echo json_encode(['ok' => false, 'error' => 'Server configuration error.'], JSON_UNESCAPED_UNICODE); exit; } require __DIR__ . '/config.php'; // Совместимость с конфигом старого образца (только BOT_TOKEN/TG_CHAT_ID): // отсутствующие константы получают безопасные значения по умолчанию. foreach ([ 'BOT_TOKEN' => '', 'TG_CHAT_ID' => '', 'MAIL_MODE' => 'smtp', 'MAIL_TO' => '', 'MAIL_FROM' => '', 'MAIL_FROM_NAME' => 'Harvey Monster Team', 'MAIL_SUBJECT' => 'Заявка с harveymonsterteam.ru', 'SMTP_HOST' => '', 'SMTP_PORT' => 465, 'SMTP_SECURE' => 'ssl', 'SMTP_USER' => '', 'SMTP_PASS' => '', 'WEBHOOK_URL' => '', 'WEBHOOK_TOKEN' => '', ] as $name => $default) { if (!defined($name)) { define($name, $default); } } unset($name, $default); const MAX_REQUESTS_PER_WINDOW = 5; const WINDOW_SECONDS = 600; const RATE_LIMIT_DIR = __DIR__ . '/var/ratelimit'; const LEADS_DIR = __DIR__ . '/var/leads'; const META_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'yclid', 'gclid', 'referrer', 'page']; /* ---------- helpers ---------- */ function json_out(int $status, bool $ok, string $msg): void { http_response_code($status); header('Content-Type: application/json; charset=utf-8'); echo json_encode($ok ? ['ok' => true, 'message' => $msg] : ['ok' => false, 'error' => $msg], JSON_UNESCAPED_UNICODE); exit; } function u_len(string $s): int { if (function_exists('mb_strlen')) { return mb_strlen($s, 'UTF-8'); } $n = preg_match_all('/./us', $s); return $n === false ? strlen($s) : $n; } /** Strip control characters: они ломают заголовки письма и JSON каналов. */ function clean(string $s): string { $s = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/u', ' ', $s); return trim($s === null ? '' : $s); } function ensure_dir(string $dir): bool { if (is_dir($dir)) { return true; } return @mkdir($dir, 0775, true); } /** api/var/ лежит под docroot: закрываем его от веба, даже если хостинг не читает .htaccess выше. */ function ensure_dir_guard(): void { $guard = dirname(LEADS_DIR) . '/.htaccess'; if (is_dir(dirname(LEADS_DIR)) && !is_file($guard)) { @file_put_contents($guard, "\n Require all denied\n\n\n Deny from all\n\n"); } } function rate_limited(string $ip): bool { if (!ensure_dir(RATE_LIMIT_DIR)) { return false; // storage unavailable — accept rather than block the whole form } $file = RATE_LIMIT_DIR . '/' . md5($ip) . '.json'; $now = time(); $hits = []; if (is_file($file)) { $hits = json_decode((string) file_get_contents($file), true); if (!is_array($hits)) { $hits = []; } foreach ($hits as $i => $t) { if ($now - $t >= WINDOW_SECONDS) { unset($hits[$i]); } } } $hits[] = $now; @file_put_contents($file, json_encode($hits), LOCK_EX); return count($hits) > MAX_REQUESTS_PER_WINDOW; } /** Keep only known attribution keys, scalar, short: meta is untrusted input. */ function sanitize_meta($raw): array { if (!is_array($raw)) { return []; } $out = []; foreach (META_KEYS as $k) { if (!isset($raw[$k]) || !is_scalar($raw[$k])) { continue; } $v = clean((string) $raw[$k]); if ($v !== '') { $out[$k] = function_exists('mb_substr') ? mb_substr($v, 0, 300, 'UTF-8') : substr($v, 0, 300); } } return $out; } function meta_line(array $meta): string { if (!$meta) { return ''; } $pairs = []; foreach ($meta as $k => $v) { $pairs[] = $k . '=' . $v; } return implode(' · ', $pairs); } /* ---------- delivery channels ---------- */ function channel_store(array $lead): bool { if (!ensure_dir(LEADS_DIR)) { return false; } ensure_dir_guard(); $line = json_encode($lead, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n"; return @file_put_contents(LEADS_DIR . '/' . date('Y-m') . '.jsonl', $line, FILE_APPEND | LOCK_EX) !== false; } function channel_telegram(array $lead, string $text): bool { if (BOT_TOKEN === '' || TG_CHAT_ID === '') { return false; } $ctx = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => 'Content-Type: application/json', 'content' => json_encode([ 'chat_id' => TG_CHAT_ID, 'text' => $text, 'parse_mode' => 'HTML', 'disable_web_page_preview' => true, ], JSON_UNESCAPED_UNICODE), 'timeout' => 10, 'ignore_errors' => true, ], ]); $raw = @file_get_contents('https://api.telegram.org/bot' . BOT_TOKEN . '/sendMessage', false, $ctx); $body = $raw === false ? null : json_decode($raw, true); if ($raw === false || !is_array($body) || empty($body['ok'])) { error_log('contact.php: telegram failed: ' . ($raw === false ? 'http error' : (string) $raw)); return false; } return true; } /** Read one (possibly multi-line) SMTP reply. */ function smtp_read($fp): string { $out = ''; while (($line = fgets($fp, 1024)) !== false) { $out .= $line; if (strlen($line) < 4 || $line[3] !== '-') { break; } } return $out; } function smtp_cmd($fp, string $cmd, array $expect): bool { if ($cmd !== '') { fwrite($fp, $cmd . "\r\n"); } $reply = smtp_read($fp); foreach ($expect as $code) { if (strpos($reply, (string) $code) === 0) { return true; } } error_log('contact.php: smtp unexpected reply to "' . substr($cmd, 0, 40) . '": ' . trim($reply)); return false; } /** Minimal dependency-free SMTP client: implicit SSL or STARTTLS, AUTH LOGIN, base64 UTF-8 body. */ function smtp_send(string $to, string $subject, string $body): bool { if (!filter_var($to, FILTER_VALIDATE_EMAIL) || SMTP_HOST === '' || SMTP_USER === '') { return false; } $secure = strtolower(SMTP_SECURE); // 'ssl' | 'tls' | '' $remote = ($secure === 'ssl' ? 'ssl://' : '') . SMTP_HOST . ':' . SMTP_PORT; $fp = @stream_socket_client($remote, $errno, $errstr, 15); if (!$fp) { error_log('contact.php: smtp connect failed: ' . $errstr); return false; } stream_set_timeout($fp, 15); $ehlo = 'EHLO ' . (gethostname() ?: 'localhost'); $ok = smtp_cmd($fp, '', [220]) && smtp_cmd($fp, $ehlo, [250]); if ($ok && $secure === 'tls') { $ok = smtp_cmd($fp, 'STARTTLS', [220]) && @stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) === true && smtp_cmd($fp, $ehlo, [250]); } if ($ok && SMTP_PASS !== '') { $ok = smtp_cmd($fp, 'AUTH LOGIN', [334]) && smtp_cmd($fp, base64_encode(SMTP_USER), [334]) && smtp_cmd($fp, base64_encode(SMTP_PASS), [235]); } $from = filter_var(MAIL_FROM, FILTER_VALIDATE_EMAIL) ? MAIL_FROM : SMTP_USER; if ($ok) { $ok = smtp_cmd($fp, 'MAIL FROM:<' . $from . '>', [250]) && smtp_cmd($fp, 'RCPT TO:<' . $to . '>', [250, 251]) && smtp_cmd($fp, 'DATA', [354]); } if ($ok) { $name = '=?UTF-8?B?' . base64_encode(MAIL_FROM_NAME) . '?='; $subj = '=?UTF-8?B?' . base64_encode($subject) . '?='; $msg = 'From: ' . $name . ' <' . $from . ">\r\n" . 'To: <' . $to . ">\r\n" . 'Subject: ' . $subj . "\r\n" . 'Date: ' . date('r') . "\r\n" . "MIME-Version: 1.0\r\n" . "Content-Type: text/plain; charset=UTF-8\r\n" . "Content-Transfer-Encoding: base64\r\n\r\n" . chunk_split(base64_encode(str_replace("\n", "\r\n", $body)), 76, "\r\n") . '.'; $ok = smtp_cmd($fp, $msg, [250]); } @fwrite($fp, "QUIT\r\n"); @fclose($fp); return $ok; } function mail_body(array $lead): string { $text = "Новое сообщение с harveymonsterteam.ru\n\n" . 'Имя: ' . $lead['name'] . "\n" . 'Связь: ' . $lead['contact'] . "\n\n" . $lead['message'] . "\n"; if ($lead['meta']) { $text .= "\n---\nИсточник: " . meta_line($lead['meta']) . "\n"; } $text .= 'Согласие (152-ФЗ): ' . ($lead['consent'] ? 'да' : 'нет') . "\n" . 'IP: ' . $lead['ip'] . "\n" . 'Время: ' . date('d.m.Y H:i:s') . "\n"; return $text; } function channel_email(array $lead): bool { if (MAIL_TO === '' || !filter_var(MAIL_TO, FILTER_VALIDATE_EMAIL)) { return false; } $body = mail_body($lead); if (MAIL_MODE === 'mail') { $headers = 'From: ' . MAIL_FROM_NAME . ' <' . (MAIL_FROM !== '' ? MAIL_FROM : MAIL_TO) . ">\r\n" . "Content-Type: text/plain; charset=UTF-8\r\n"; $ok = @mail(MAIL_TO, '=?UTF-8?B?' . base64_encode(MAIL_SUBJECT) . '?=', $body, $headers); if (!$ok) { error_log('contact.php: mail() failed'); } return $ok; } return smtp_send(MAIL_TO, MAIL_SUBJECT, $body); } function channel_webhook(array $lead): bool { if (WEBHOOK_URL === '') { return false; } $headers = ['Content-Type: application/json']; if (WEBHOOK_TOKEN !== '') { $headers[] = 'Authorization: Bearer ' . WEBHOOK_TOKEN; } $ctx = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => implode("\r\n", $headers), 'content' => json_encode([ 'site' => 'https://harveymonsterteam.ru/', 'sent_at' => date('c'), 'name' => $lead['name'], 'contact' => $lead['contact'], 'message' => $lead['message'], 'consent' => $lead['consent'], 'meta' => $lead['meta'], ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'timeout' => 12, 'ignore_errors' => true, ], ]); $raw = @file_get_contents(WEBHOOK_URL, false, $ctx); $code = 0; if (isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $m)) { $code = (int) $m[1]; } if ($raw === false || $code < 200 || $code >= 300) { error_log('contact.php: webhook failed: ' . ($raw === false ? 'http error' : 'HTTP ' . $code)); return false; } return true; } /* ---------- request ---------- */ if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') { header('Allow: POST'); json_out(405, false, 'Method not allowed.'); } $body = json_decode((string) file_get_contents('php://input'), true); if (!is_array($body)) { json_out(400, false, 'Expected a JSON body.'); } $name = clean((string) ($body['name'] ?? '')); $contact = clean((string) ($body['contact'] ?? '')); $message = clean((string) ($body['message'] ?? '')); $honey = trim((string) ($body['website'] ?? '')); $consent = ($body['consent'] ?? false) === true; if ($honey !== '') { json_out(200, true, 'Сообщение отправлено. Мы ответим в ближайшее время.'); // lie to bots } if (u_len($name) < 2 || u_len($name) > 100) { json_out(422, false, 'Укажите имя (2–100 символов).'); } // Канал связи не ограничен форматом (telegram, email, телефон, VK) — только длина + экранирование. if (u_len($contact) < 2 || u_len($contact) > 200) { json_out(422, false, 'Укажите предпочтительное средство связи (2–200 символов).'); } if (u_len($message) < 10 || u_len($message) > 4000) { json_out(422, false, 'Опишите задачу (10–4000 символов).'); } if (!$consent) { json_out(422, false, 'Отметьте согласие на обработку персональных данных.'); } $ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'); if (rate_limited($ip)) { json_out(429, false, 'Слишком много запросов. Попробуйте через 10 минут.'); } $lead = [ 'ts' => date('c'), 'name' => $name, 'contact' => $contact, 'message' => $message, 'consent' => $consent, 'meta' => sanitize_meta($body['meta'] ?? []), 'ip' => $ip, 'ua' => substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 300), ]; // Telegram — HTML: значения экранируем. $esc = function (string $s): string { return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }; $tgText = "🛎 Новое сообщение с harveymonsterteam.ru\n" . "Имя: {$esc($name)}\n" . "Связь: {$esc($contact)}\n\n" . $esc($message); if ($lead['meta']) { $tgText .= "\n\nИсточник: " . $esc(meta_line($lead['meta'])); } $stored = channel_store($lead); $configured = 0; $delivered = 0; if (BOT_TOKEN !== '' && TG_CHAT_ID !== '') { $configured++; $delivered += channel_telegram($lead, $tgText) ? 1 : 0; } if (MAIL_TO !== '') { $configured++; $delivered += channel_email($lead) ? 1 : 0; } if (WEBHOOK_URL !== '') { $configured++; $delivered += channel_webhook($lead) ? 1 : 0; } if ($configured === 0) { error_log('contact.php: no delivery channel configured — lead stored=' . ($stored ? 'yes' : 'no')); json_out(500, false, 'Приём заявок не настроен. Напишите на monsterharvi@gmail.com.'); } if ($delivered === 0) { error_log('contact.php: all channels failed — lead stored=' . ($stored ? 'yes' : 'no')); json_out(500, false, 'Не удалось отправить заявку. Напишите на monsterharvi@gmail.com.'); } json_out(200, true, 'Сообщение отправлено. Мы ответим в ближайшее время.');