-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevwc-basic.php
More file actions
563 lines (498 loc) · 26.7 KB
/
evwc-basic.php
File metadata and controls
563 lines (498 loc) · 26.7 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
<?php
/*
Plugin Name: EVWC Basic Email Validation
Description: Минимальная безопасная версия. Валидация e‑mail на регистрации/чекауте WooCommerce, вебхук Mailgun и импорт по cron.
Version: 0.4.0
Author: Ama
* Text Domain: evwc-basic
* Domain Path: /languages
*/
// i18n loader
// Security helper: forbid processing if EVWC_MG_KEY is absent
if (!function_exists('evwc__forbid_without_key')) {
function evwc__forbid_without_key() {
if (!defined('EVWC_MG_KEY') || !EVWC_MG_KEY) {
if (function_exists('rest_ensure_response')) {
return new WP_REST_Response(array('ok'=>false,'reason'=>'no_key'), 403);
}
status_header(403);
wp_die('Forbidden: EVWC_MG_KEY missing');
}
return null;
}
}
add_action('init', function () {
if (function_exists('load_plugin_textdomain')) {
load_plugin_textdomain('evwc-basic', false, dirname(plugin_basename(__FILE__)) . '/languages');
}
});
if (!defined('ABSPATH')) { exit; }
/* ---------- Конфиг ---------- */
$__evwc_local_cfg = __DIR__ . '/evwc-config.php';
if (is_file($__evwc_local_cfg)) { @require_once $__evwc_local_cfg; }
if (!defined('EVWC_MG_REGION')) { define('EVWC_MG_REGION', 'US'); }
if (!function_exists('evwc_get_settings')) {
function evwc_get_settings() {
$s = get_option('evwc_settings', array());
return is_array($s) ? $s : array();
}}
$__evwc_s = evwc_get_settings();
if (!defined('EVWC_MG_KEY') && !empty($__evwc_s['key'])) { define('EVWC_MG_KEY', $__evwc_s['key']); }
if (!defined('EVWC_MG_DOMAIN') && !empty($__evwc_s['domain'])) { define('EVWC_MG_DOMAIN', $__evwc_s['domain']); }
if (!defined('EVWC_MG_REGION') && !empty($__evwc_s['region'])) { define('EVWC_MG_REGION', $__evwc_s['region']); }
/* ---------- Активация/деактивация ---------- */
if (!function_exists('evwc_on_activate')) {
function evwc_on_activate() {
global $wpdb;
$table = $wpdb->prefix . 'evwc_suppressions';
$charset = $wpdb->get_charset_collate();
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$sql = "CREATE TABLE {$table} (
email VARCHAR(255) NOT NULL,
type VARCHAR(32) NOT NULL,
reason VARCHAR(255) NULL,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (email)
) {$charset};";
dbDelta($sql);
if (function_exists('wp_next_scheduled') && !wp_next_scheduled('evwc_sync_suppressions_event')) {
if (function_exists('wp_schedule_event')) {
wp_schedule_event(time() + 120, 'daily', 'evwc_sync_suppressions_event');
}
}
}}
register_activation_hook(__FILE__, 'evwc_on_activate');
if (!function_exists('evwc_on_deactivate')) {
function evwc_on_deactivate() {
if (function_exists('wp_clear_scheduled_hook')) {
wp_clear_scheduled_hook('evwc_sync_suppressions_event');
}
}}
register_deactivation_hook(__FILE__, 'evwc_on_deactivate');
/** ===== EVWC: нормальная админка (безопасная) ===== */
if (is_admin()) {
/* Пункты меню: верхний и дубль под «Инструменты» */
add_action('admin_menu', function () {
if (!current_user_can('manage_options')) return;
try { add_menu_page('EVWC', 'EVWC', 'manage_options', 'evwc', 'evwc_admin_render', 'dashicons-shield-alt', 56); } catch (Exception $e) {}
try { add_submenu_page('tools.php', 'EVWC', 'EVWC', 'manage_options', 'evwc-tools', 'evwc_admin_render'); } catch (Exception $e) {}
}, 9);
/* Ссылка «Настройки» на странице плагинов */
add_filter('plugin_action_links_' . plugin_basename(__FILE__), function ($links) {
$url = admin_url('admin.php?page=evwc');
array_unshift($links, '<a href="'.esc_url($url).'">Настройки</a>');
return $links;
});
/* Обработчик ручного импорта (admin-post) */
add_action('admin_post_evwc_sync_now', function () {
if (!current_user_can('manage_options')) wp_die('EVWC: forbidden');
if (!isset($_GET['evwc_nonce']) || !wp_verify_nonce($_GET['evwc_nonce'], 'evwc_sync_now')) wp_die('EVWC: bad nonce');
if (function_exists('evwc_sync_suppressions')) { evwc_sync_suppressions(); }
$back = !empty($_GET['back']) ? esc_url_raw($_GET['back']) : admin_url('admin.php?page=evwc');
wp_safe_redirect(add_query_arg('evwc_synced','1', $back));
exit;
});
/* Рендер страницы */
if (!function_exists('evwc_admin_render')) {
function evwc_admin_render() {
$safe = function () {
/* --- Сохранение настроек --- */
$saved = false; $err = '';
if (isset($_POST['evwc_save']) && function_exists('check_admin_referer') && check_admin_referer('evwc_save_settings')) {
$s = function_exists('evwc_get_settings') ? evwc_get_settings() : array();
// Домен (простая валидация)
$d = isset($_POST['evwc_domain']) ? trim(wp_unslash($_POST['evwc_domain'])) : '';
if ($d === '' || preg_match('/^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/', $d)) { $s['domain'] = $d; }
else { $err = 'Неверный домен.'; }
// Регион
$r = isset($_POST['evwc_region']) ? strtoupper(trim(wp_unslash($_POST['evwc_region']))) : 'US';
if (in_array($r, array('US','EU'), true)) { $s['region'] = $r; } else { $err = 'Неверный регион.'; }
// API key (может быть пустым)
$k = isset($_POST['evwc_key']) ? trim(wp_unslash($_POST['evwc_key'])) : '';
$s['key'] = $k;
if ($err === '') { update_option('evwc_settings', $s, false); $saved = true; }
}
// Текущие опции
$s = function_exists('evwc_get_settings') ? evwc_get_settings() : array();
$opt_domain = isset($s['domain']) ? $s['domain'] : '';
$opt_region = isset($s['region']) ? $s['region'] : 'US';
$opt_key = isset($s['key']) ? $s['key'] : '';
// Эффективные (что реально используется сейчас)
$eff_domain = defined('EVWC_MG_DOMAIN') ? EVWC_MG_DOMAIN : $opt_domain;
$eff_region = defined('EVWC_MG_REGION') ? EVWC_MG_REGION : $opt_region;
$eff_key = defined('EVWC_MG_KEY') ? EVWC_MG_KEY : $opt_key;
// Предупреждение о приоритете констант
$has_const = (defined('EVWC_MG_DOMAIN') || defined('EVWC_MG_REGION') || defined('EVWC_MG_KEY'));
// Webhook URL
$webhook = function_exists('rest_url') ? rest_url('evwc/v1/mg-webhook') : home_url('/wp-json/evwc/v1/mg-webhook');
echo '<div class="wrap"><h1>EVWC</h1>';
if ($saved) echo '<div class="notice notice-success is-dismissible"><p>Настройки сохранены.</p></div>';
if ($err) echo '<div class="notice notice-error is-dismissible"><p>'.esc_html($err).'</p></div>';
if ($has_const) {
echo '<div class="notice notice-warning is-dismissible"><p>Внимание: в wp-config.php/evwc-config.php заданы константы EVWC_MG_*. Они имеют приоритет над значениями из этой формы. Чтобы применились настройки из админки — удалите/закомментируйте константы.</p></div>';
}
if (isset($_GET['evwc_synced']) && $_GET['evwc_synced'] === '1') {
echo '<div class="notice notice-success is-dismissible"><p>Синхронизация завершена.</p></div>';
}
echo '<p>Webhook (Mailgun): <code>'.esc_html($webhook).'</code></p>';
/* --- Форма настроек --- */
echo '<h2>Mailgun</h2>';
echo '<form method="post" action="">';
if (function_exists('wp_nonce_field')) wp_nonce_field('evwc_save_settings');
echo '<table class="form-table" role="presentation"><tbody>';
echo '<tr><th scope="row"><label for="evwc_domain">Домен</label></th><td>';
echo '<input type="text" id="evwc_domain" name="evwc_domain" value="'.esc_attr($opt_domain).'" class="regular-text">';
echo '</td></tr>';
echo '<tr><th scope="row"><label for="evwc_region">Регион</label></th><td>';
echo '<select id="evwc_region" name="evwc_region">';
foreach (array('US'=>'US','EU'=>'EU') as $k=>$v) {
$sel = ($opt_region === $k) ? 'selected' : '';
echo '<option value="'.$k.'" '.$sel.'>'.$v.'</option>';
}
echo '</select>';
echo '</td></tr>';
echo '<tr><th scope="row"><label for="evwc_key">Private API key</label></th><td>';
echo '<div style="display:flex;gap:8px;align-items:center;max-width:420px">';
echo '<input type="password" id="evwc_key" name="evwc_key" value="'.esc_attr($opt_key).'" class="regular-text" autocomplete="new-password" style="flex:1">';
echo '<button type="button" class="button" id="evwc_toggle_key" aria-label="Показать/скрыть ключ">👁</button>';
echo '</div>';
echo '</td></tr>';
echo '</tbody></table>';
echo '<p><button type="submit" class="button button-primary" name="evwc_save" value="1">Сохранить</button></p>';
echo '</form>';
/* --- Кнопка ручного импорта --- */
$nonce = function_exists('wp_create_nonce') ? wp_create_nonce('evwc_sync_now') : '';
$back = urlencode(admin_url('admin.php?page=evwc'));
$sync_url = add_query_arg(array(
'action' => 'evwc_sync_now',
'evwc_nonce' => $nonce,
'back' => $back,
), admin_url('admin-post.php'));
echo '<h2>Suppressions</h2>';
echo '<p><a class="button button-secondary" href="'.esc_url($sync_url).'">Импортировать suppression-листы сейчас</a></p>';
// Статистика
global $wpdb;
if ($wpdb && isset($wpdb->prefix)) {
$table = $wpdb->prefix . 'evwc_suppressions';
$total = $b = $c = $u = 0;
try {
$total = (int)$wpdb->get_var("SELECT COUNT(*) FROM {$table}");
$b = (int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE type=%s", 'bounce'));
$c = (int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE type=%s", 'complaint'));
$u = (int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE type=%s", 'unsub'));
} catch (Exception $e) {}
echo '<p>В стоп-листе: <strong>'.$total.'</strong> (bounces: '.$b.', complaints: '.$c.', unsubs: '.$u.')</p>';
}
// JS: глаз для ключа
echo '<script>
(function(){
var btn = document.getElementById("evwc_toggle_key");
var inp = document.getElementById("evwc_key");
if(btn && inp){
btn.addEventListener("click", function(e){
e.preventDefault();
if(inp.type === "password"){ inp.type = "text"; btn.textContent = "🙈"; }
else { inp.type = "password"; btn.textContent = "👁"; }
});
}
})();
</script>';
echo '</div>'; // .wrap
};
if (class_exists('Throwable')) { try { $safe(); } catch (Throwable $t) { echo '<div class="wrap"><h1>EVWC</h1><div class="notice notice-error"><p>Страница временно недоступна.</p></div></div>'; } }
else { try { $safe(); } catch (Exception $e) { echo '<div class="wrap"><h1>EVWC</h1><div class="notice notice-error"><p>Страница временно недоступна.</p></div></div>'; } }
}}
}
if (!function_exists('evwc_tools_render')) {
function evwc_tools_render() {
if (!current_user_can('manage_options')) return;
$synced = (isset($_GET['evwc_synced']) && $_GET['evwc_synced'] === '1');
$nonce = function_exists('wp_create_nonce') ? wp_create_nonce('evwc_sync_now') : '';
// Эффективные значения (не показываем ключ)
$s = function_exists('evwc_get_settings') ? evwc_get_settings() : array();
$eff_domain = defined('EVWC_MG_DOMAIN') ? EVWC_MG_DOMAIN : (isset($s['domain']) ? $s['domain'] : '(не задан)');
$eff_region = defined('EVWC_MG_REGION') ? EVWC_MG_REGION : (isset($s['region']) ? $s['region'] : 'US');
echo '<div class="wrap"><h1>EVWC Tools</h1>';
if ($synced) echo '<div class="notice notice-success is-dismissible"><p>Синхронизация завершена.</p></div>';
$webhook = function_exists('rest_url') ? rest_url('evwc/v1/mg-webhook') : home_url('/wp-json/evwc/v1/mg-webhook');
echo '<p>Webhook (Mailgun): <code>'.esc_html($webhook).'</code></p>';
echo '<p>Регион: <strong>'.esc_html($eff_region).'</strong>; Домен: <strong>'.esc_html($eff_domain).'</strong></p>';
// Кнопка ручного импорта без формы — через admin-post URL
$sync_url = add_query_arg(array(
'action' => 'evwc_sync_now',
'evwc_nonce' => $nonce,
), admin_url('admin-post.php'));
echo '<p><a class="button button-primary" href="'.esc_url($sync_url).'">Импортировать suppression-листы сейчас</a></p>';
// Лёгкая статистика (мягко)
global $wpdb;
if ($wpdb && isset($wpdb->prefix)) {
$table = $wpdb->prefix . 'evwc_suppressions';
$total = $b = $c = $u = 0;
try {
$total = (int)$wpdb->get_var("SELECT COUNT(*) FROM {$table}");
$b = (int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE type=%s", 'bounce'));
$c = (int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE type=%s", 'complaint'));
$u = (int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE type=%s", 'unsub'));
} catch (Exception $e) { /* игнор */ }
echo '<p>В стоп-листе: <strong>'.$total.'</strong> (bounces: '.$b.', complaints: '.$c.', unsubs: '.$u.')</p>';
}
echo '</div>';
}}
/* ---------- Импорт/вебхук Mailgun ---------- */
if (!function_exists('evwc_sync_suppressions')) {
function evwc_sync_suppressions() {
if (!defined('EVWC_MG_KEY') || !defined('EVWC_MG_DOMAIN')) { return true; }
$base = (defined('EVWC_MG_REGION') && strtoupper(EVWC_MG_REGION) === 'EU') ? 'https://api.eu.mailgun.net' : 'https://api.mailgun.net';
$domain = EVWC_MG_DOMAIN;
$eps = array(
array('type' => 'bounce', 'url' => "{$base}/v3/{$domain}/bounces?limit=500"),
array('type' => 'complaint', 'url' => "{$base}/v3/{$domain}/complaints?limit=500"),
array('type' => 'unsub', 'url' => "{$base}/v3/{$domain}/unsubscribes?limit=500"),
);
foreach ($eps as $e) {
$resp = wp_remote_get($e['url'], array(
'timeout' => 15,
'headers' => array('Authorization' => 'Basic ' . base64_encode('api:' . EVWC_MG_KEY)),
));
if (is_wp_error($resp) || wp_remote_retrieve_response_code($resp) !== 200) { continue; }
$body = json_decode(wp_remote_retrieve_body($resp), true);
$items = (is_array($body) && isset($body['items']) && is_array($body['items'])) ? $body['items'] : array();
foreach ($items as $it) {
$email = isset($it['address']) ? $it['address'] : (isset($it['recipient']) ? $it['recipient'] : '');
$reason = isset($it['error']) ? $it['error'] : (isset($it['tags']) ? (is_array($it['tags']) ? implode(',', $it['tags']) : (string)$it['tags']) : '');
if ($email) { evwc_upsert_suppression($email, $e['type'], $reason); }
}
}
return true;
}}
add_action('evwc_sync_suppressions_event', 'evwc_sync_suppressions');
if (!function_exists('evwc_upsert_suppression')) {
function evwc_upsert_suppression($email, $type, $reason = '') {
global $wpdb;
$email = strtolower(trim($email));
$table = $wpdb->prefix . 'evwc_suppressions';
$exists = $wpdb->get_var($wpdb->prepare("SELECT email FROM {$table} WHERE email=%s", $email));
if ($exists) {
$wpdb->update($table, array('type' => $type, 'reason' => $reason, 'updated_at' => current_time('mysql')), array('email' => $email));
} else {
$wpdb->insert($table, array('email' => $email, 'type' => $type, 'reason' => $reason, 'updated_at' => current_time('mysql')));
}
}}
add_action('rest_api_init', function () {
register_rest_route('evwc/v1', '/mg-webhook', array(
'methods' => 'POST',
'callback' => 'evwc_mg_webhook_handler',
'permission_callback' => '__return_true',
));
});
if (!function_exists('evwc_mg_webhook_handler')) {
function evwc_mg_webhook_handler($request) {
$payload = is_object($request) && method_exists($request, 'get_json_params') ? $request->get_json_params() : array();
if (!is_array($payload)) { return new WP_REST_Response(array('ok' => false, 'reason' => 'bad_json'), 400); }
if (defined('EVWC_MG_KEY')) {
$sig = isset($payload['signature']) ? $payload['signature'] : array();
$ts = isset($sig['timestamp']) ? (string)$sig['timestamp'] : '';
$tok = isset($sig['token']) ? (string)$sig['token'] : '';
$sign= isset($sig['signature']) ? (string)$sig['signature'] : '';
if ($ts && $tok && $sign && function_exists('hash_hmac') && function_exists('hash_equals')) {
$calc = hash_hmac('sha256', $ts . $tok, EVWC_MG_KEY);
if (!hash_equals($calc, $sign)) { return new WP_REST_Response(array('ok' => false, 'reason' => 'bad_signature'), 403); }
}
}
$edata = isset($payload['event-data']) ? $payload['event-data'] : array();
$event = isset($edata['event']) ? $edata['event'] : '';
$email = '';
if (!empty($edata['recipient'])) {
$email = $edata['recipient'];
} elseif (!empty($edata['message']['headers']['to'])) {
$to = $edata['message']['headers']['to'];
if (is_string($to)) {
if (preg_match('/<([^>]+@[^>]+)>/', $to, $m)) { $email = $m[1]; }
else { $email = trim($to); }
}
}
$email = strtolower(trim($email));
$type = '';
if ($event === 'bounced') { $type = 'bounce'; }
elseif ($event === 'complained') { $type = 'complaint'; }
elseif ($event === 'unsubscribed'){ $type = 'unsub'; }
if ($type && $email) {
$reason = isset($edata['delivery-status']['description']) ? $edata['delivery-status']['description'] : '';
evwc_upsert_suppression($email, $type, $reason);
return new WP_REST_Response(array('ok' => true), 200);
}
return new WP_REST_Response(array('ok' => false, 'reason' => 'no_event'), 400);
}}
/* ---------- WooCommerce валидация ---------- */
add_filter('woocommerce_registration_errors', function ($errors, $username, $email) {
$r = evwc_validate_email((string)$email);
if (!$r['ok']) {
if (is_wp_error($errors) && $errors->get_error_message('invalid_email')) { $errors->remove('invalid_email'); }
$errors->add('evwc_' . $r['code'], $r['message']);
}
return $errors;
}, 99, 3);
add_action('woocommerce_checkout_process', function () {
$email = isset($_POST['billing_email']) ? sanitize_text_field(wp_unslash($_POST['billing_email'])) : '';
if (!$email) { return; }
$r = evwc_validate_email($email);
if (!$r['ok'] && function_exists('wc_add_notice')) { wc_add_notice($r['message'], 'error'); }
}, 10);
// Checkout Blocks — без исключений
add_action('woocommerce_store_api_checkout_update_customer_from_request', 'evwc_blocks_validate_from_request', 10, 2);
add_action('woocommerce_store_api_checkout_update_order_from_request', 'evwc_blocks_validate_from_request', 10, 2);
if (!function_exists('evwc_blocks_validate_from_request')) {
function evwc_blocks_validate_from_request($obj, $request) {
$email = evwc_extract_email_from_request($request);
if (!$email) { return; }
$r = evwc_validate_email($email);
if (!$r['ok'] && function_exists('wc_add_notice')) { wc_add_notice($r['message'], 'error'); }
}}
/* ---------- Извлечение e-mail ---------- */
if (!function_exists('evwc_extract_email_from_request')) {
function evwc_extract_email_from_request($request) {
$email = '';
if (is_object($request) && method_exists($request, 'get_param')) {
foreach (array('billing_email', 'email') as $key) {
$val = $request->get_param($key);
if (is_string($val) && strpos($val, '@') !== false) { $email = $val; break; }
}
if (!$email) {
$billing = $request->get_param('billing');
if (is_array($billing) && !empty($billing['email'])) { $email = $billing['email']; }
}
if (!$email) {
$customer = $request->get_param('customer');
if (is_array($customer)) {
if (!empty($customer['email'])) { $email = $customer['email']; }
elseif (!empty($customer['billing_address']['email'])) { $email = $customer['billing_address']['email']; }
}
}
}
if (!$email && is_object($request) && method_exists($request, 'get_json_params')) {
$body = $request->get_json_params();
if (is_array($body)) {
$stack = array($body);
while (!empty($stack)) {
$node = array_pop($stack);
if (is_array($node)) {
foreach ($node as $k => $v) {
if (is_string($k) && strtolower($k) === 'email' && is_string($v) && strpos($v, '@') !== false) { $email = $v; break 2; }
if (is_array($v)) { $stack[] = $v; }
}
}
}
}
}
if (!$email && isset($_POST['billing_email'])) { $email = $_POST['billing_email']; }
return $email ? sanitize_text_field($email) : '';
}}
/* ---------- Валидация ---------- */
if (!function_exists('evwc_validate_email')) {
function evwc_validate_email($email) {
$email = is_string($email) ? trim($email) : '';
$at = strrpos($email, '@');
if ($at === false) { return evwc_fail('format', 'Укажите корректный e-mail адрес.'); }
$local = substr($email, 0, $at);
$domain = substr($email, $at + 1);
$domain_l = function_exists('mb_strtolower') ? mb_strtolower($domain, 'UTF-8') : strtolower($domain);
$domain_ascii = $domain_l;
if (function_exists('idn_to_ascii')) {
$try = @idn_to_ascii($domain_l);
if ($try) { $domain_ascii = $try; }
}
$normalized = $local . '@' . $domain_ascii;
if (!filter_var($normalized, FILTER_VALIDATE_EMAIL)) {
return evwc_fail('format', 'Укажите корректный e-mail адрес.');
}
if (evwc_is_suppressed($normalized)) {
return evwc_fail('suppressed', 'Адрес находится в стоп-листе (bounce/complaint/unsub). Укажите другой e-mail.');
}
if (evwc_is_disposable_domain($domain_ascii)) {
return evwc_fail('disposable', 'Одноразовые адреса не принимаются. Укажите другой e-mail.');
}
if (!evwc_has_mx_cached($domain_ascii)) {
return evwc_fail('mx', 'Похоже, домен не принимает почту (нет MX-записи). Укажите другой e-mail.');
}
return array('ok' => true, 'code' => 'ok', 'message' => '');
}}
if (!function_exists('evwc_is_suppressed')) {
function evwc_is_suppressed($email) {
global $wpdb;
$email = strtolower(trim($email));
$table = $wpdb->prefix . 'evwc_suppressions';
$hit = $wpdb->get_var($wpdb->prepare("SELECT type FROM {$table} WHERE email=%s LIMIT 1", $email));
return !empty($hit);
}}
if (!function_exists('evwc_fail')) { function evwc_fail($code, $msg) { return array('ok' => false, 'code' => $code, 'message' => $msg); } }
if (!function_exists('evwc_is_disposable_domain')) {
function evwc_is_disposable_domain($domain) {
static $bad = array('mailinator.com','guerrillamail.com','10minutemail.com','temp-mail.org','yopmail.com','dropmail.me','trashmail.com','tempmail.plus','getnada.com');
return in_array($domain, $bad, true);
}}
if (!function_exists('evwc_has_mx_cached')) {
function evwc_has_mx_cached($domain) {
$key = 'evwc_mx_' . md5($domain);
$hit = get_transient($key);
if ($hit !== false) { return (bool)$hit; }
$ok = false;
if (function_exists('getmxrr')) {
$hosts = array(); $weights = array();
$ok = @getmxrr($domain, $hosts, $weights) && !empty($hosts);
}
if (!$ok && function_exists('checkdnsrr')) {
$ok = checkdnsrr($domain, 'MX') || checkdnsrr($domain . '.', 'MX');
}
if (!$ok && function_exists('dns_get_record')) {
$records = @dns_get_record($domain, defined('DNS_ANY') ? DNS_ANY : 255);
if (is_array($records)) { foreach ($records as $rec) { if (isset($rec['type']) && $rec['type'] === 'MX') { $ok = true; break; } } }
}
set_transient($key, $ok ? 1 : 0, 6 * HOUR_IN_SECONDS);
return $ok;
}}
/* ---------- Подсказки доменов (безопасно) ---------- */
add_action('wp_enqueue_scripts', function () {
$js = <<<JS
(function(){
function levenshtein(a,b){
var an=a?a.length:0, bn=b?b.length:0;
if(an===0) return bn; if(bn===0) return an;
var m=[]; for(var i=0;i<=bn;i++){m[i]=[i]}
for(var j=0;j<=an;j++){m[0][j]=j}
for(var i=1;i<=bn;i++){
for(var j=1;j<=an;j++){
var cost = (b.charAt(i-1)===a.charAt(j-1)) ? 0 : 1;
m[i][j] = Math.min(m[i-1][j]+1, m[i][j-1]+1, m[i-1][j-1]+cost);
}
}
return m[bn][an];
}
var popular = ['gmail.com','yahoo.com','outlook.com','hotmail.com','yandex.ru','ya.ru','mail.ru','bk.ru','inbox.ru','list.ru','icloud.com','proton.me'];
function suggest(email){
var at=email.lastIndexOf('@'); if(at<0) return '';
var local=email.slice(0,at), domain=email.slice(at+1).toLowerCase();
var best='', bestDist=2;
for(var i=0;i<popular.length;i++){ var d=popular[i];
var dist=levenshtein(domain,d);
if(dist<=bestDist){ bestDist=dist; best=d; }
}
return best ? (local+'@'+best) : '';
}
function mount(input){
if(!input || input.evwcBound) return; input.evwcBound = true;
var hint=document.createElement('div'); hint.className='evwc-hint'; hint.style.fontSize='12px'; hint.style.marginTop='4px'; hint.style.color='rgba(0,0,0,.7)';
input.parentNode.appendChild(hint);
function update(){ var s=suggest(input.value.trim()); hint.textContent = s ? ('Возможно, вы имели в виду: '+s) : ''; }
input.addEventListener('input', update); update();
}
function ready(){
var selectors=['input[name=\"billing_email\"]','#reg_email','input[type=\"email\"]'];
selectors.forEach(function(sel){ var nodes=document.querySelectorAll(sel); for(var i=0;i<nodes.length;i++){ mount(nodes[i]); }});
}
if(document.readyState==='loading'){ document.addEventListener('DOMContentLoaded', ready); } else { ready(); }
})();
JS;
wp_register_script('evwc-inline', '', array(), null, true);
wp_enqueue_script('evwc-inline');
wp_add_inline_script('evwc-inline', $js);
});