-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsend-request.php
More file actions
345 lines (320 loc) · 13.3 KB
/
Copy pathsend-request.php
File metadata and controls
345 lines (320 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
<?php
declare(strict_types=1);
require_once __DIR__ . '/lib/bootstrap.php';
oll4_json_headers();
function oll4_contact_rate_limit_path(): string {
return oll4_private_file('contact-rate-limits.json');
}
function oll4_contact_full_log_path(): string {
return oll4_private_file('contact-submissions-full.jsonl');
}
function oll4_contact_redacted_log_path(): string {
return oll4_private_file('contact-events.jsonl');
}
function oll4_contact_rate_limit(string $email, string $ua): void {
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? ($_SERVER['REMOTE_ADDR'] ?? 'unknown');
$emailKey = oll4_hash_value('email', strtolower($email) . '|' . $ip);
$ipKey = oll4_hash_value('ip', $ip . '|' . substr(strtolower($ua), 0, 160));
$now = time();
oll4_locked_json_update(oll4_contact_rate_limit_path(), [], static function (array $state) use ($emailKey, $ipKey, $now): array {
$filter = static function ($ts) use ($now): bool {
return is_int($ts) && $ts > $now - 3600;
};
$emailEvents = array_values(array_filter($state[$emailKey] ?? [], $filter));
$ipEvents = array_values(array_filter($state[$ipKey] ?? [], $filter));
if (count($emailEvents) >= 5 || count($ipEvents) >= 8) {
oll4_respond(429, ['ok' => false, 'error' => 'Too many requests. Try again later.']);
}
$emailEvents[] = $now;
$ipEvents[] = $now;
$state[$emailKey] = $emailEvents;
$state[$ipKey] = $ipEvents;
return $state;
});
}
function oll4_contact_mail_body(string $value, int $max = 2400): string {
$value = str_replace(["\r\n", "\r", "\0"], ["\n", "\n", ''], $value);
$value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', ' ', $value) ?? '';
$lines = preg_split("/\n/u", $value) ?: [];
$lines = array_map(static function ($line): string {
$line = preg_replace('/[ \t]+/u', ' ', (string)$line) ?? '';
return trim($line);
}, $lines);
$value = preg_replace("/\n{3,}/u", "\n\n", trim(implode("\n", $lines))) ?? '';
if (function_exists('mb_substr')) {
return mb_substr($value, 0, $max, 'UTF-8');
}
return substr($value, 0, $max);
}
function oll4_contact_reply_draft(array $payload): array {
$target = oll4_public_agent_base_url() . '/contact-reply';
$body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($body === false) {
return ['ok' => false, 'error' => 'contact_reply_encoding_failed'];
}
$ctx = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\nConnection: close\r\n",
'content' => $body,
'timeout' => 45,
'ignore_errors' => true,
],
]);
$raw = @file_get_contents($target, false, $ctx);
if ($raw === false) {
return ['ok' => false, 'error' => 'contact_reply_unavailable'];
}
$json = json_decode($raw, true);
if (!is_array($json)) {
return ['ok' => false, 'error' => 'contact_reply_invalid'];
}
if (empty($json['ok'])) {
return [
'ok' => false,
'error' => oll4_clean_text((string)($json['error'] ?? 'contact_reply_failed'), 80),
'detail' => oll4_clean_text((string)($json['detail'] ?? ''), 240),
];
}
$subject = oll4_header_text((string)($json['subject'] ?? ''), 160);
$mailBody = oll4_contact_mail_body((string)($json['body'] ?? ''), 2400);
if ($subject === '' || $mailBody === '') {
return ['ok' => false, 'error' => 'contact_reply_empty'];
}
return [
'ok' => true,
'subject' => $subject,
'body' => $mailBody,
'language' => oll4_clean_text((string)($json['language'] ?? ''), 12),
'summary' => oll4_clean_text((string)($json['summary'] ?? ''), 320),
];
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
oll4_respond(405, ['ok' => false, 'error' => 'POST required']);
}
if ((int)($_SERVER['CONTENT_LENGTH'] ?? 0) > 12000) {
oll4_respond(413, ['ok' => false, 'error' => 'Payload too large']);
}
if (!oll4_request_is_same_origin()) {
oll4_respond(403, ['ok' => false, 'error' => 'Origin not allowed']);
}
if (!oll4_request_content_type_allows(['application/json'])) {
oll4_respond(415, ['ok' => false, 'error' => 'JSON required']);
}
if (!oll4_fetch_metadata_is_allowed(['same-origin', 'same-site', 'none'], ['cors', 'same-origin'])) {
oll4_respond(403, ['ok' => false, 'error' => 'Fetch metadata blocked']);
}
$data = json_decode((string)file_get_contents('php://input'), true);
if (!is_array($data)) {
oll4_respond(400, ['ok' => false, 'error' => 'Invalid JSON']);
}
if (oll4_clean_text($data['website'] ?? '', 100) !== '') {
oll4_respond(200, ['ok' => true, 'spam_filtered' => true]);
}
$name = oll4_clean_text($data['name'] ?? '', 120);
$email = filter_var(oll4_clean_text($data['email'] ?? '', 220), FILTER_VALIDATE_EMAIL);
$project = oll4_clean_text($data['project'] ?? '', 180);
$scope = oll4_clean_text($data['scope'] ?? '', 120);
$timeline = oll4_clean_text($data['timeline'] ?? '', 120);
$message = oll4_clean_text($data['message'] ?? '', 2200);
$profile = oll4_clean_text($data['profile'] ?? 'OLL4 focus layer', 120);
$profileKey = oll4_clean_text($data['profileKey'] ?? '', 60);
$agentSessionId = oll4_clean_text($data['agentSessionId'] ?? '', 120);
$agentMode = oll4_clean_text($data['agentMode'] ?? '', 40);
$agentLanguage = oll4_clean_text($data['agentLanguage'] ?? '', 12);
$agentRouteType = oll4_clean_text($data['agentRouteType'] ?? '', 80);
$agentHelpMode = oll4_clean_text($data['agentHelpMode'] ?? '', 80);
$agentUrgency = oll4_clean_text($data['agentUrgency'] ?? '', 80);
$leadConfidence = oll4_clean_text($data['leadConfidence'] ?? '', 32);
$agentSummary = oll4_clean_text($data['agentSummary'] ?? '', 800);
if (!$email) {
oll4_respond(422, ['ok' => false, 'error' => 'Valid email required']);
}
$missing = [];
if ($name === '') $missing[] = 'name';
if ($project === '') $missing[] = 'project';
if ($scope === '') $missing[] = 'scope';
if ($timeline === '') $missing[] = 'timeline';
if ($message === '') $missing[] = 'message';
if ($missing) {
oll4_respond(422, ['ok' => false, 'error' => 'All fields are required', 'missing' => $missing]);
}
oll4_verify_turnstile(oll4_clean_text($data['turnstileToken'] ?? '', 4096), true);
$ua = oll4_clean_text($_SERVER['HTTP_USER_AGENT'] ?? 'unknown', 220);
oll4_contact_rate_limit((string)$email, $ua);
$to = 'forge@oll4.com';
$from = 'forge@oll4.com';
$subject = oll4_header_text("oll4.com request [$profile] $project", 180);
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? ($_SERVER['REMOTE_ADDR'] ?? 'unknown');
$time = gmdate('Y-m-d H:i:s') . ' UTC';
$adminBody = implode("\n", array_filter([
'New oll4.com request',
'====================',
"Time: $time",
"Name: $name",
"Email: $email",
"Focus layer: $profile",
"Focus key: $profileKey",
"Project: $project",
"Scope: $scope",
"Timeline: $timeline",
$agentSessionId !== '' ? "Agent session: $agentSessionId" : null,
$agentMode !== '' ? "Agent mode: $agentMode" : null,
$agentLanguage !== '' ? "Agent language: $agentLanguage" : null,
$agentRouteType !== '' ? "Agent route type: $agentRouteType" : null,
$agentHelpMode !== '' ? "Agent help mode: $agentHelpMode" : null,
$agentUrgency !== '' ? "Agent urgency: $agentUrgency" : null,
$leadConfidence !== '' ? "Lead confidence: $leadConfidence" : null,
'',
'Message:',
$message,
$agentSummary !== '' ? '' : null,
$agentSummary !== '' ? 'Agent summary:' : null,
$agentSummary !== '' ? $agentSummary : null,
'',
"IP: $ip",
"User agent: $ua",
]));
$adminHeaders = implode("\r\n", [
'From: oll4.com <' . $from . '>',
'Reply-To: ' . oll4_header_text($name, 80) . ' <' . $email . '>',
'Content-Type: text/plain; charset=UTF-8',
'X-Mailer: oll4.com contact router',
]);
$adminEnvelopeSender = '-f' . $from;
$adminSent = function_exists('mail') ? @mail($to, $subject, $adminBody, $adminHeaders, $adminEnvelopeSender) : false;
$replyDraft = $adminSent ? oll4_contact_reply_draft([
'name' => $name,
'email' => $email,
'project' => $project,
'scope' => $scope,
'timeline' => $timeline,
'message' => $message,
'profile' => $profile,
'profile_key' => $profileKey,
'agent_session_id' => $agentSessionId,
'agent_mode' => $agentMode,
'agent_language' => $agentLanguage,
'agent_route_type' => $agentRouteType,
'agent_help_mode' => $agentHelpMode,
'agent_urgency' => $agentUrgency,
'lead_confidence' => $leadConfidence,
'agent_summary' => $agentSummary,
]) : ['ok' => false, 'error' => 'admin_mail_failed'];
$autoFrom = 'lab@oll4.com';
$autoEnvelopeFrom = 'info@olla.gr';
$autoHeaders = implode("\r\n", [
'From: OLL4 <' . $autoFrom . '>',
'Reply-To: OLL4 <' . $autoFrom . '>',
'Content-Type: text/plain; charset=UTF-8',
'X-Mailer: oll4.com hermes auto responder',
]);
$autoEnvelopeSender = '-f' . $autoEnvelopeFrom;
$autoSent = false;
$autoDeliveryState = 'not_queued';
if ($adminSent && !empty($replyDraft['ok'])) {
$autoBody = str_replace("\n", "\r\n", (string)$replyDraft['body']);
$autoSent = function_exists('mail')
? @mail((string)$email, (string)$replyDraft['subject'], $autoBody, $autoHeaders, $autoEnvelopeSender)
: false;
$autoDeliveryState = $autoSent ? 'queued' : 'not_queued';
}
$replyStatus = !$adminSent
? 'admin_mail_failed'
: (!empty($replyDraft['ok']) ? ($autoSent ? 'queued' : 'auto_reply_mail_rejected') : ($replyDraft['error'] ?? 'contact_reply_failed'));
$athensNow = oll4_athens_now();
oll4_append_jsonl(oll4_contact_full_log_path(), [
'ts' => time(),
'athens_date' => $athensNow->format('Y-m-d'),
'name' => $name,
'email' => $email,
'project' => $project,
'scope' => $scope,
'timeline' => $timeline,
'message' => $message,
'profile' => $profile,
'profile_key' => $profileKey,
'agent_session_id' => $agentSessionId,
'agent_mode' => $agentMode,
'agent_language' => $agentLanguage,
'agent_route_type' => $agentRouteType,
'agent_help_mode' => $agentHelpMode,
'agent_urgency' => $agentUrgency,
'lead_confidence' => $leadConfidence,
'agent_summary' => $agentSummary,
'ip' => $ip,
'user_agent' => $ua,
'admin_sent' => $adminSent,
'auto_reply_sent' => $autoSent,
'auto_reply_mail_accepted' => $autoSent,
'auto_reply_status' => $replyStatus,
'auto_reply_delivery_state' => $autoDeliveryState,
'auto_reply_language' => $replyDraft['language'] ?? '',
'auto_reply_summary' => $replyDraft['summary'] ?? '',
'auto_reply_sender' => $autoFrom,
'auto_reply_envelope_sender' => $autoEnvelopeFrom,
]);
oll4_append_jsonl(oll4_contact_redacted_log_path(), [
'ts' => time(),
'athens_date' => $athensNow->format('Y-m-d'),
'profile' => $profile,
'profile_key' => $profileKey,
'project' => $project,
'scope' => $scope,
'timeline' => $timeline,
'agent_session_sha256' => $agentSessionId !== '' ? oll4_hash_value('session', $agentSessionId) : '',
'agent_mode' => $agentMode,
'agent_language' => $agentLanguage,
'agent_route_type' => $agentRouteType,
'agent_help_mode' => $agentHelpMode,
'agent_urgency' => $agentUrgency,
'lead_confidence' => $leadConfidence,
'admin_sent' => $adminSent,
'auto_reply_sent' => $autoSent,
'auto_reply_mail_accepted' => $autoSent,
'auto_reply_status' => $replyStatus,
'auto_reply_delivery_state' => $autoDeliveryState,
'auto_reply_language' => $replyDraft['language'] ?? '',
'auto_reply_sender' => $autoFrom,
'auto_reply_envelope_sender' => $autoEnvelopeFrom,
]);
if (!$adminSent || empty($replyDraft['ok']) || !$autoSent) {
oll4_update_feed_summary(static function (array $state) use ($adminSent): array {
$state['status'] = 'LIVE';
$state['mail_endpoint'] = 'degraded';
if ($adminSent) {
$state['accepted_today'] = (int)($state['accepted_today'] ?? 0) + 1;
}
$state['event_feed'] = $adminSent ? 'contact accepted / reply not queued' : 'mail endpoint degraded';
return $state;
});
oll4_respond(502, [
'ok' => false,
'error' => !$adminSent ? 'Mail server did not accept the admin message' : 'Request accepted, but the Hermes auto reply could not be queued',
'admin_sent' => $adminSent,
'auto_reply_sent' => $autoSent,
'auto_reply_status' => $replyStatus,
'auto_reply_delivery_state' => $autoDeliveryState,
'auto_reply_sender' => $autoFrom,
'auto_reply_envelope_sender' => $autoEnvelopeFrom,
'auto_reply_error' => empty($replyDraft['ok']) ? ($replyDraft['error'] ?? 'contact_reply_failed') : 'auto_reply_mail_failed',
'auto_reply_detail' => $replyDraft['detail'] ?? '',
]);
}
oll4_update_feed_summary(static function (array $state): array {
$state['status'] = 'LIVE';
$state['mail_endpoint'] = function_exists('mail') ? 'online' : 'degraded';
$state['accepted_today'] = (int)($state['accepted_today'] ?? 0) + 1;
$state['event_feed'] = 'contact accepted';
return $state;
});
oll4_respond(200, [
'ok' => true,
'admin_sent' => true,
'auto_reply_sent' => true,
'auto_reply_status' => 'queued',
'auto_reply_delivery_state' => 'queued',
'auto_reply_sender' => $autoFrom,
'auto_reply_envelope_sender' => $autoEnvelopeFrom,
'timer_seconds' => 0,
]);