Ads readiness, lead delivery, project inventory

- SEO/ads: title, description, canonical, OG 1200x630, JSON-LD, robots, sitemap, .htaccess
- Privacy policy page with operator data; server-side consent check; cookie reset in footer
- Metrika loads only after cookie consent; goals lead / email_click / phone_click; utm and yclid stored with the lead
- Form delivery: store, Telegram, SMTP, webhook; config presets; dev stub
- Project window shows public sections only; Moba copy rewritten
- Fix 14 px horizontal overflow in the filter bar on phones
- Move history to archive/; add docs/project-inventory.md and docs/lead-delivery.md
This commit is contained in:
FastD committed 2026-11-10 18:22:55 +03:00
1 parent e352335822
commit b60d00d55c
47 files changed
+1665 -202

No files matched your search

+352 -34
View File
@@ -3,16 +3,25 @@
* Harvey Monster Team Page — contact form endpoint.
* Production: https://harveymonsterteam.ru/api/contact.php
*
* Contract: POST JSON {name, contact, message, website?}
* Contract: POST JSON {name, contact, message, consent, website?, meta?}
* - name: required, 2–100 chars
* - contact: required, any channel (telegram / email / phone / VK), 2–200 chars
* - message: required, 10–4000 chars
* - consent: required, must be true (152-ФЗ)
* - website: honeypot — must be empty (bots fill it)
* - meta: optional {utm_*, yclid, gclid, referrer, page} — attribution for ads
* Responses: JSON {ok:bool, message|error:string}
* - 200 ok / 400 bad JSON / 405 wrong method / 422 validation / 429 rate limit / 500 upstream
* - 200 ok / 400 bad JSON / 405 wrong method / 422 validation / 429 rate limit / 500 delivery
*
* Deploy: upload api/ to the site root, copy config.sample.php -> config.php
* and fill BOT_TOKEN / TG_CHAT_ID. Requires PHP 7.4+ (mbstring optional).
* Delivery pipeline (see api/config.sample.php):
* 1. store — always: api/var/leads/YYYY-MM.jsonl (nothing is lost if channels fail)
* 2. telegram— optional: BOT_TOKEN + TG_CHAT_ID
* 3. email — optional: SMTP (LOGIN / SSL / STARTTLS) or PHP mail()
* 4. webhook — optional: any HTTP endpoint (ESP, CRM, Make/n8n, Bitrix24, amoCRM…)
* The request succeeds when at least one notify channel accepted the lead.
*
* Deploy: upload api/ to the site root, copy config.sample.php -> config.php.
* Requires PHP 7.4+ (mbstring optional).
*/
if (!file_exists(__DIR__ . '/config.php')) {
@@ -21,11 +30,39 @@ if (!file_exists(__DIR__ . '/config.php')) {
echo json_encode(['ok' => false, 'error' => 'Server configuration error.'], JSON_UNESCAPED_UNICODE);
exit;
}
require __DIR__ . '/config.php'; // BOT_TOKEN, TG_CHAT_ID
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 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
{
@@ -44,9 +81,33 @@ function u_len(string $s): int
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, "<IfModule mod_authz_core.c>\n Require all denied\n</IfModule>\n<IfModule !mod_authz_core.c>\n Deny from all\n</IfModule>\n");
}
}
function rate_limited(string $ip): bool
{
if (!is_dir(RATE_LIMIT_DIR) && !@mkdir(RATE_LIMIT_DIR, 0775, true)) {
if (!ensure_dir(RATE_LIMIT_DIR)) {
return false; // storage unavailable — accept rather than block the whole form
}
$file = RATE_LIMIT_DIR . '/' . md5($ip) . '.json';
@@ -68,6 +129,238 @@ function rate_limited(string $ip): bool
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.');
@@ -78,10 +371,11 @@ if (!is_array($body)) {
json_out(400, false, 'Expected a JSON body.');
}
$name = trim((string) ($body['name'] ?? ''));
$contact = trim((string) ($body['contact'] ?? ''));
$message = trim((string) ($body['message'] ?? ''));
$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
@@ -97,39 +391,63 @@ if (u_len($contact) < 2 || u_len($contact) > 200) {
if (u_len($message) < 10 || u_len($message) > 4000) {
json_out(422, false, 'Опишите задачу (10–4000 символов).');
}
if (!$consent) {
json_out(422, false, 'Отметьте согласие на обработку персональных данных.');
}
if (rate_limited($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0')) {
$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']));
}
$text = "🛎 Новое сообщение с harveymonsterteam.ru\n"
. "Имя: {$esc($name)}\n"
. "Связь: {$esc($contact)}\n\n"
. $esc($message);
$stored = channel_store($lead);
$configured = 0;
$delivered = 0;
$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',
], JSON_UNESCAPED_UNICODE),
'timeout' => 10,
'ignore_errors' => true,
],
]);
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;
}
$tg = @file_get_contents('https://api.telegram.org/bot' . BOT_TOKEN . '/sendMessage', false, $ctx);
$tgBody = $tg === false ? null : json_decode($tg, true);
if ($tg === false || !is_array($tgBody) || empty($tgBody['ok'])) {
error_log('contact.php: telegram send failed: ' . ($tg === false ? 'http error' : (string) $tg));
json_out(500, false, 'Ошибка сервера. Попробуйте позже.');
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, 'Сообщение отправлено. Мы ответим в ближайшее время.');