Repository navigation
Expand file tree
/
Copy pathcleantalk-common.php
More file actions
1968 lines (1725 loc) · 66.4 KB
/
Copy pathcleantalk-common.php
File metadata and controls
1968 lines (1725 loc) · 66.4 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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
use Cleantalk\Antispam\Cleantalk;
use Cleantalk\Antispam\CleantalkRequest;
use Cleantalk\Antispam\CleantalkResponse;
use Cleantalk\ApbctWP\API;
use Cleantalk\ApbctWP\BaseCall\DefaultParams;
use Cleantalk\ApbctWP\CleantalkSettingsTemplates;
use Cleantalk\ApbctWP\Constant;
use Cleantalk\ApbctWP\Cron;
use Cleantalk\ApbctWP\DB;
use Cleantalk\ApbctWP\DTO\GetFieldsAnyDTO;
use Cleantalk\ApbctWP\Firewall\SFW;
use Cleantalk\ApbctWP\GetFieldsAny;
use Cleantalk\ApbctWP\Helper;
use Cleantalk\ApbctWP\Honeypot;
use Cleantalk\ApbctWP\RequestParameters\RequestParameters;
use Cleantalk\ApbctWP\RequestParameters\SubmitTimeHandler;
use Cleantalk\ApbctWP\Sanitize;
use Cleantalk\ApbctWP\Variables\AltSessions;
use Cleantalk\ApbctWP\Variables\Cookie;
use Cleantalk\ApbctWP\Variables\Get;
use Cleantalk\ApbctWP\Variables\Post;
use Cleantalk\ApbctWP\Variables\Server;
use Cleantalk\Common\TT;
// Prevent direct call
if ( ! defined('ABSPATH') ) {
die('Not allowed!');
}
function apbct_array($array)
{
return new \Cleantalk\Common\Arr($array);
}
$ct_checkjs_frm = 'ct_checkjs_frm';
$ct_checkjs_register_form = 'ct_checkjs_register_form';
$apbct_cookie_request_id_label = 'request_id';
$apbct_cookie_register_ok_label = 'register_ok';
$ct_checkjs_cf7 = 'ct_checkjs_cf7';
$ct_cf7_comment = '';
$ct_checkjs_jpcf = 'ct_checkjs_jpcf';
$ct_jpcf_patched = false;
$ct_jpcf_fields = array('name', 'email');
// Comment already proccessed
$ct_comment_done = false;
// Comment already proccessed
$ct_signup_done = false;
//Contains registration error
$ct_registration_error_comment = false;
// Default value for JS test
$ct_checkjs_def = 0;
// COOKIE label to store request id for last approved
$ct_approved_request_id_label = 'ct_approved_request_id';
// Last request id approved for publication
$ct_approved_request_id = null;
// Trial notice show time in minutes
$trial_notice_showtime = 10;
// Renew notice show time in minutes
$renew_notice_showtime = 10;
// COOKIE label for WP Landing Page proccessing result
$ct_wplp_result_label = 'ct_wplp_result';
// Flag indicates active JetPack comments
$ct_jp_comments = false;
// WP admin email notice interval in seconds
$ct_admin_notoice_period = 21600;
// Sevice negative comment to visitor.
// It uses for BuddyPress registrations to avoid double checks
$ct_negative_comment = null;
/**
* Public action 'plugins_loaded' - Loads locale, see http://codex.wordpress.org/Function_Reference/load_plugin_textdomain
*/
function apbct_plugin_loaded()
{
load_plugin_textdomain('cleantalk-spam-protect', false, APBCT_LANG_REL_PATH);
}
/**
* Inner function - Request's wrapper for anything
*
* @param array Array of parameters:
* 'message' - string
* 'example' - string
* 'checkjs' - int
* 'sender_email' - string
* 'sender_nickname' - string
* 'sender_info' - array
* 'post_info' - string
*
* @return array array('ct'=> Cleantalk, 'ct_result' => CleantalkResponse)
*/
function apbct_base_call($params = array(), $reg_flag = false)
{
global $cleantalk_executed;
if ( isset($params['post_info']['comment_type']) && (
($params['post_info']['comment_type'] === 'site_search_wordpress') ||
($params['post_info']['comment_type'] === 'jetpack_comment')
)) {
Cookie::$force_alt_cookies_global = true;
}
/* Exclusions */
if ( $cleantalk_executed ) {
do_action('apbct_skipped_request', __FILE__ . ' -> ' . __FUNCTION__ . '():' . __LINE__, $_POST);
return array('ct_result' => new CleantalkResponse());
}
// URL, IP, Role, Form signs exclusions
if ( apbct_exclusions_check() ) {
do_action('apbct_skipped_request', __FILE__ . ' -> ' . __FUNCTION__ . '():' . __LINE__, $_POST);
return array('ct_result' => new CleantalkResponse());
}
// Reversed url exclusions. Pass everything except one.
if ( apbct_exclusions_check__url__reversed() ) {
do_action('apbct_skipped_request', __FILE__ . ' -> ' . __FUNCTION__ . '():' . __LINE__, $_POST);
return array('ct_result' => new CleantalkResponse());
}
global $apbct;
$cleantalk_executed = true;
/* Request ID rotation */
$tmp = array();
if ( $apbct->plugin_request_ids && ! empty($apbct->plugin_request_ids) ) {
$plugin_request_id__lifetime = 2;
foreach ( $apbct->plugin_request_ids as $request_id => $request_time ) {
if ( time() - $request_time < $plugin_request_id__lifetime ) {
$tmp[$request_id] = $request_time;
}
}
}
$apbct->plugin_request_ids = $tmp;
$apbct->save('plugin_request_ids');
// Skip duplicate requests
if (
isset($apbct->plugin_request_ids[ $apbct->plugin_request_id ]) &&
current_filter() !== 'woocommerce_registration_errors' && // Prevent skip checking woocommerce registration during checkout
current_filter() !== 'woocommerce_store_api_checkout_order_processed' && // Prevent skip checking woocommerce registration during checkout
current_filter() !== 'um_submit_form_register' // Prevent skip checking UltimateMember register
) {
do_action('apbct_skipped_request', __FILE__ . ' -> ' . __FUNCTION__ . '():' . __LINE__, $_POST);
return array('ct_result' => new CleantalkResponse());
}
$apbct->plugin_request_ids[ $apbct->plugin_request_id ] = time();
$apbct->save('plugin_request_ids');
/* End of Request ID rotation */
if ( ! $apbct->stats['no_cookie_data_taken'] ) {
apbct_form__get_no_cookie_data();
}
$sender_info = apbct_get_sender_info();
if (isset($params['sender_info']) && !empty($params['sender_info'])) {
$sender_info = \Cleantalk\ApbctWP\Helper::arrayMergeSaveNumericKeysRecursive(
$sender_info,
(array)$params['sender_info']
);
}
$default_params_getter = new DefaultParams($apbct->api_key, $sender_info);
$default_params = $default_params_getter->get();
if (!isset($params['post_info']['post_url'])) {
$params['post_info']['post_url'] = Server::get('HTTP_REFERER');
}
// Event Token
$params['event_token'] = apbct_get_event_token($params);
if (Cookie::get('typo')) {
$default_params['sender_info']['typo'] = Cookie::get('typo');
}
/**
* Add exception_action sender email is empty
*/
if (
empty($params['sender_email']) &&
! isset($params['exception_action']) &&
// No need to log excluded requests on the direct integrations
! empty($params['post_info']['comment_type']) &&
strpos($params['post_info']['comment_type'], 'contact_form_wordpress_') === false &&
! preg_match('/comment$/', $params['post_info']['comment_type']) &&
! apbct_is_trackback() &&
! defined('XMLRPC_REQUEST')
) {
/**
* If the constant APBCT_SERVICE__DISABLE_EMPTY_EMAIL_EXCEPTION is defined,
* it means that the exception action should be disabled for empty email checks.
*
* Check all post data option ignore this constant.
* @since 6.58.99
*/
if (
Constant::is(Constant::APBCT_SERVICE__DISABLE_EMPTY_EMAIL_EXCEPTION) &&
!$apbct->settings['data__general_postdata_test']
) {
$params['exception_action'] = 0;
} else {
$params['exception_action'] = 1;
}
}
/**
* Skip checking excepted requests if the "Log excluded requests" option is disabled.
*/
if ( isset($params['exception_action']) && $params['exception_action'] == 1 && ! $apbct->settings['exclusions__log_excluded_requests'] ) {
do_action('apbct_skipped_request', __FILE__ . ' -> ' . __FUNCTION__ . '():' . __LINE__, $_POST);
return array('ct_result' => new CleantalkResponse());
}
// Honeypot
if ( isset($params['honeypot_field']) ) {
$default_params['honeypot_field'] = $params['honeypot_field'];
} else if ( $apbct->settings['data__honeypot_field'] ) {
$honeypot = Honeypot::check();
$params['honeypot_field'] = isset($honeypot['status']) ? $honeypot['status'] : null;
if ( isset($honeypot['value'], $honeypot['source'], $params['sender_info']) ) {
$params['sender_info']['honeypot_field_value'] = $honeypot['value'];
$params['sender_info']['honeypot_field_source'] = $honeypot['source'];
}
}
// Send $_SERVER if couldn't find IP
if ( empty($default_params['sender_ip']) ) {
$default_params['sender_info']['server_info'] = $_SERVER;
}
$ct = new Cleantalk();
$ct_request = new CleantalkRequest(
\Cleantalk\ApbctWP\Helper::arrayMergeSaveNumericKeysRecursive($default_params, $params)
);
// Options store url without scheme because of DB error with ''://'
$config = ct_get_server();
$ct->server_url = APBCT_MODERATE_URL;
$ct->work_url = isset($config['ct_work_url']) && preg_match('/https:\/\/.+/', $config['ct_work_url']) ? $config['ct_work_url'] : null;
$ct->server_ttl = isset($config['ct_server_ttl']) ? $config['ct_server_ttl'] : null;
$ct->server_changed = isset($config['ct_server_changed']) ? $config['ct_server_changed'] : null;
$start = microtime(true);
$ct_result = $reg_flag
? @$ct->isAllowUser($ct_request)
: @$ct->isAllowMessage($ct_request);
$exec_time = microtime(true) - $start;
// Statistics
// Average request time
apbct_statistics_rotate($exec_time);
// Last request
$apbct->stats['last_request']['time'] = time();
$apbct->stats['last_request']['server'] = $ct->work_url;
$apbct->save('stats');
if ( $ct->server_change ) {
update_option(
'cleantalk_server',
array(
'ct_work_url' => $ct->work_url,
'ct_server_ttl' => $ct->server_ttl,
'ct_server_changed' => time(),
)
);
$cron = new Cron();
$cron->updateTask('rotate_moderate', 'apbct_rotate_moderate', 86400); // Rotate moderate server
}
//alternative checks and connection report handler
if ($ct_result instanceof \Cleantalk\Antispam\CleantalkResponse) {
$ct_result = ct_checks_on_cleantalk_errors($ct_request, $ct_result);
}
// Restart submit form counter for failed requests
if ( is_object($ct_result) && $ct_result->allow == 0 ) {
apbct_cookie(); // Setting page timer and cookies
ct_add_event('no');
} else {
ct_add_event('yes');
}
// Set cookies if it's not.
if ( empty($apbct->flags__cookies_setuped) ) {
Cookie::$force_alt_cookies_global = false;
apbct_cookie();
}
//clear POST and REQUEST superglobal from service data
$_POST = apbct_clear_superglobal_service_data($_POST, 'post');
$_REQUEST = apbct_clear_superglobal_service_data($_REQUEST, 'request');
return array('ct' => $ct, 'ct_result' => $ct_result);
}
function apbct_rotate_moderate()
{
$ct = new Cleantalk();
$ct->server_url = APBCT_MODERATE_URL;
$ct->rotateModerate();
if ( $ct->server_change ) {
update_option(
'cleantalk_server',
array(
'ct_work_url' => $ct->work_url,
'ct_server_ttl' => $ct->server_ttl,
'ct_server_changed' => time(),
)
);
}
}
function apbct_exclusions_check($func = null)
{
global $apbct;
if ( Post::get('apbct_do_not_exclude') ) {
return false;
}
// Common exclusions
if (
apbct_exclusions_check__form_signs($_POST) ||
apbct_exclusions_check__url() ||
apbct_is_user_role_in($apbct->settings['exclusions__roles'])
) {
return true;
}
// Personal exclusions
switch ( $func ) {
case 'ct_contact_form_validate_postdata':
if (
(defined('DOING_AJAX') && DOING_AJAX) ||
apbct_array($_POST)->getKeys('members_search_submit')->result()
) {
return true;
}
break;
case 'ct_contact_form_validate':
if (
apbct_array($_POST)->getKeys('members_search_submit')->result()
|| (
(int)$apbct->settings['data__protect_logged_in'] === 1
&& (
Post::equal('wpfaction', 'topic_add')
|| Post::equal('wpfaction', 'post_add')
)
&& apbct_is_plugin_active('wpforo/wpforo.php')
)
) {
return true;
}
break;
default:
return false;
}
return false;
}
/**
* Check if the reversed exclusions is set and doesn't match.
*
* @return bool
*/
function apbct_exclusions_check__url__reversed()
{
return defined('APBCT_URL_EXCLUSIONS__REVERSED') &&
! Server::hasString('REQUEST_URI', APBCT_URL_EXCLUSIONS__REVERSED);
}
/**
* Checks if reuqest URI is in exclusion list
*
* @return bool
*/
function apbct_exclusions_check__url()
{
global $apbct;
if ( ! empty($apbct->settings['exclusions__urls']) ) {
if ( strpos($apbct->settings['exclusions__urls'], "\r\n") !== false ) {
$exclusions = explode("\r\n", $apbct->settings['exclusions__urls']);
} elseif ( strpos($apbct->settings['exclusions__urls'], "\n") !== false ) {
$exclusions = explode("\n", $apbct->settings['exclusions__urls']);
} else {
$exclusions = explode(',', $apbct->settings['exclusions__urls']);
}
//default haystack is request_uri
$url_haystack = Server::getString('REQUEST_URI');
/**
* Fix for AJAX and WP REST API forms
*/
// case for admin-ajax routes, may contain get params(!)
$is_admin_ajax_like = stripos(Server::getString('REQUEST_URI'), '/wp-admin/admin-ajax.php') === 0;
// case for woocommerce-ajax routes, may contain get params(!)
$is_wc_ajax_like = stripos(Server::getString('REQUEST_URI'), '/?wc-ajax=') === 0;
// case for wp-json paths
$is_wp_json_like = stripos(Server::getString('REQUEST_URI'), '/wp-json/') === 0;
// case for rest paths
$rest_url_only_path = apbct_get_rest_url_only_path();
$is_rest_only_path = $rest_url_only_path !== 'index.php' && stripos(Server::getString('REQUEST_URI'), $rest_url_only_path) === 0;
// if need to use http referrer as haystack
$do_use_http_referrer = (
Server::getString('HTTP_REFERER') &&
(
$is_admin_ajax_like ||
$is_wc_ajax_like ||
$is_wp_json_like ||
$is_rest_only_path
)
);
// do combine actions from referrer if so
if ($do_use_http_referrer) {
$url_haystack = str_ireplace(
array('http://', 'https://', strval(TT::toString(Server::get('HTTP_HOST')))),
'',
Server::getString('HTTP_REFERER')
);
}
// if exclusions is full-url like, modify haystack to being full-url also
if ( $apbct->data['check_exclusion_as_url'] ) {
$protocol = ! in_array(Server::get('HTTPS'), ['off', '']) || Server::get('SERVER_PORT') == 443 ? 'https://' : 'http://';
$url_haystack = $protocol . TT::toString(Server::get('SERVER_NAME')) . TT::toString($url_haystack);
}
$url_haystack = TT::toString($url_haystack);
foreach ( $exclusions as $exclusion ) {
if (
(
$apbct->settings['exclusions__urls__use_regexp'] &&
preg_match('@' . $exclusion . '@', $url_haystack) === 1
) ||
stripos($url_haystack, $exclusion) !== false
) {
return true;
}
}
return false;
}
return false;
}
/**
* Check POST array for the exclusion form signs. Listen for array keys or for value in case if key is "action".
* @param array $form_data The POST array or another filtered array of form data.
* @return bool True if exclusion found in the keys of array, false otherwise.
*/
function apbct_exclusions_check__form_signs($form_data)
{
global $apbct;
if ( ! empty($apbct->settings['exclusions__form_signs']) ) {
if ( strpos($apbct->settings['exclusions__form_signs'], "\r\n") !== false ) {
$exclusions = explode("\r\n", $apbct->settings['exclusions__form_signs']);
} elseif ( strpos($apbct->settings['exclusions__form_signs'], "\n") !== false ) {
$exclusions = explode("\n", $apbct->settings['exclusions__form_signs']);
} else {
$exclusions = explode(',', $apbct->settings['exclusions__form_signs']);
}
foreach ( $exclusions as $exclusion ) {
foreach ($form_data as $key => $value) {
$haystack = ($key === 'action' || $key === 'data') ? $value : $key;
if (
$haystack === $exclusion ||
(is_string($haystack) && stripos($haystack, $exclusion) !== false) ||
(is_string($haystack) && preg_match('@' . $exclusion . '@', $haystack) === 1)
) {
return true;
}
}
}
return false;
}
return false;
}
/**
* Inner function - Default data array for senders
* @return array
*/
function apbct_get_sender_info()
{
global $apbct;
// Validate cookie from the backend
$cookie_is_ok = apbct_cookies_test();
if ( count($_POST) > 0 ) {
foreach ( $_POST as $k => $v ) {
if ( preg_match("/^(ct_check|checkjs).+/", (string)$k) ) {
$checkjs_data_post = $v;
}
}
}
// Visible fields processing
$visible_fields = GetFieldsAny::getVisibleFieldsData();
// preparation of some parameters when cookies are disabled and data is received from localStorage
if ($apbct->data['cookies_type'] === 'native') {
$param_email_check = Cookie::getNativeCookieValue('ct_checked_emails');
$param_screen_info = Cookie::getNativeCookieValue('ct_screen_info');
} else {
$param_email_check = Cookie::get('ct_checked_emails') ? json_encode(
Cookie::get('ct_checked_emails')
) : null;
$param_screen_info = Cookie::get('ct_screen_info')
? json_encode(Cookie::get('ct_screen_info'))
: null;
}
$param_mouse_cursor_positions = Cookie::get('ct_pointer_data');
$param_pixel_url = Cookie::get('apbct_pixel_url');
if ($apbct->data['cookies_type'] === 'none') {
$param_email_check = Cookie::get('ct_checked_emails') ? urldecode(
TT::toString(Cookie::get('ct_checked_emails'))
) : null;
$param_mouse_cursor_positions = urldecode(TT::toString(Cookie::get('ct_pointer_data')));
$param_pixel_url = Cookie::get('apbct_pixel_url');
$param_pixel_url = urldecode(is_string($param_pixel_url) ? $param_pixel_url : '');
$param_screen_info = Cookie::get('ct_screen_info')
? urldecode(TT::toString(Cookie::get('ct_screen_info')))
: null;
}
//cache plugins detection
$cache_plugins_detected = apbct_is_cache_plugins_exists(true);
$cache_plugins_detected = empty($cache_plugins_detected) ? false : $cache_plugins_detected;
$cache_plugins_detected = json_encode($cache_plugins_detected);
$apbct_urls = RequestParameters::getCommonStorage('apbct_urls');
if (!empty($apbct_urls)) {
if (is_string($apbct_urls)) {
$apbct_urls = json_encode(json_decode($apbct_urls, true));
} else {
$apbct_urls = json_encode($apbct_urls);
}
}
$apbct_urls = !empty($apbct_urls) ? $apbct_urls : null;
$site_landing_ts = RequestParameters::get('apbct_site_landing_ts', true);
$site_landing_ts = !empty($site_landing_ts) ? TT::toString($site_landing_ts) : null;
$site_referer = RequestParameters::get('apbct_site_referer', true);
$site_referer = !empty($site_referer) ? TT::toString($site_referer) : 'UNKNOWN';
/**
* Important! Do not use just HTTP only flag here. Page hits are handled on JS side
* and could be provided via NoCookie hidden field.
* Also, forms with forced alt cookies does not provide it via hidden field and in the same time other forms do,
* so we need a flag to know the source.
* A.G.
*/
$page_hits = RequestParameters::get('apbct_page_hits', Cookie::$force_alt_cookies_global);
$page_hits = !empty($page_hits) ? TT::toString($page_hits) : null;
$ct_options = json_encode(
array_merge(
(array) $apbct->settings,
['data__bot_detector_enabled' => apbct__is_bot_detector_enabled() ? 1 : 0]
),
JSON_UNESCAPED_SLASHES
);
//Let's keep $data_array for debugging
$data_array = array(
'plugin_request_id' => $apbct->plugin_request_id,
'wpms' => is_multisite() ? 'yes' : 'no',
'remote_addr' => \Cleantalk\ApbctWP\Helper::ipGet('remote_addr', false),
'USER_AGENT' => Server::get('HTTP_USER_AGENT'),
'page_url' => apbct_sender_info___get_page_url(),
'cms_lang' => substr(get_locale(), 0, 2),
'ct_options' => $ct_options,
'fields_number' => sizeof($_POST),
'direct_post' => $cookie_is_ok === null && apbct_is_post() ? 1 : 0,
// Raw data to validated JavaScript test in the cloud
'checkjs_data_cookies' => Cookie::get('ct_checkjs') ?: null,
'checkjs_data_post' => !empty($checkjs_data_post) ? $checkjs_data_post : null,
// PHP cookies
'cookies_enabled' => $cookie_is_ok,
'data__set_cookies' => $apbct->settings['data__set_cookies'],
'data__cookies_type' => $apbct->data['cookies_type'],
'REFFERRER' => Server::getString('HTTP_REFERER'),
'REFFERRER_PREVIOUS' => !empty(Cookie::getString('apbct_prev_referer')) && $cookie_is_ok
? Cookie::getString('apbct_prev_referer')
: null,
'site_landing_ts' => $site_landing_ts,
'page_hits' => $page_hits,
'mouse_cursor_positions' => $param_mouse_cursor_positions,
'js_timezone' => Cookie::get('ct_timezone') ?: null,
'key_press_timestamp' => Cookie::get('ct_fkp_timestamp') ?: null,
'page_set_timestamp' => Cookie::get('ct_ps_timestamp') ?: null,
'form_visible_inputs' => !empty($visible_fields['visible_fields_count'])
? $visible_fields['visible_fields_count']
: null,
'apbct_visible_fields' => !empty($visible_fields['visible_fields'])
? $visible_fields['visible_fields']
: null,
'form_invisible_inputs' => !empty($visible_fields['invisible_fields_count'])
? $visible_fields['invisible_fields_count']
: null,
'apbct_invisible_fields' => !empty($visible_fields['invisible_fields'])
? $visible_fields['invisible_fields']
: null,
// Misc
'site_referer' => $site_referer,
'source_url' => $apbct_urls,
'pixel_url' => $param_pixel_url,
'pixel_setting' => $apbct->settings['data__pixel'],
// Debug stuff
'amp_detected' => apbct_is_amp_request(),
'hook' => current_filter() ? current_filter() : 'no_hook',
'headers_sent' => !empty($apbct->headers_sent) ? $apbct->headers_sent : false,
'headers_sent__hook' => !empty($apbct->headers_sent__hook) ? $apbct->headers_sent__hook : 'no_hook',
'headers_sent__where' => !empty($apbct->headers_sent__where) ? $apbct->headers_sent__where : false,
'request_type' => Server::get('REQUEST_METHOD') ?: 'UNKNOWN',
'email_check' => $param_email_check,
'screen_info' => $param_screen_info,
'has_scrolled' => Cookie::get('ct_has_scrolled') !== ''
? json_encode(Cookie::get('ct_has_scrolled'))
: null,
'mouse_moved' => Cookie::get('ct_mouse_moved') !== ''
? json_encode(Cookie::get('ct_mouse_moved'))
: null,
'emulations_headless_mode' => Cookie::get('apbct_headless') !== ''
? json_encode(Cookie::get('apbct_headless'))
: null,
'no_cookie_data_taken' => isset($apbct->stats['no_cookie_data_taken']) ? $apbct->stats['no_cookie_data_taken'] : null,
'no_cookie_data_post_source' => isset($apbct->stats['no_cookie_data_post_source'])
? $apbct->stats['no_cookie_data_post_source']
: null,
'has_key_up' => Cookie::get('ct_has_key_up') !== ''
? json_encode(Cookie::get('ct_has_key_up'))
: null,
'has_input_focused' => Cookie::get('ct_has_input_focused') !== ''
? json_encode(Cookie::get('ct_has_input_focused'))
: null,
'cache_plugins_detected' => $cache_plugins_detected,
//bot detector data
'bot_detector_fired_form_exclusions' => apbct__bot_detector_get_fired_exclusions(),
'bot_detector_prepared_form_exclusions' => apbct__bot_detector_get_prepared_exclusion(),
'bot_detector_frontend_data_log' => apbct__bot_detector_get_fd_log(),
'submit_time_calculation_enabled' => SubmitTimeHandler::isCalculationDisabled() ? 0 : 1,
'ct_gathering_loaded' => Cookie::getBool('ct_gathering_loaded'),
);
// Unset cookies_enabled from sender_info if cookies_type === none
if ($apbct->data['cookies_type'] === 'none') {
unset($data_array['cookies_enabled']);
}
return $data_array;
}
function apbct_sender_info___get_page_url()
{
if (
( apbct_is_ajax() || apbct_is_rest() )
&& Server::get('HTTP_REFERER')
) {
return TT::toString(Server::get('HTTP_REFERER'));
}
$protocol = ! empty($_SERVER['HTTPS']) && 'off' !== strtolower($_SERVER['HTTPS']) ? "https://" : "http://";
return $protocol . TT::toString(Server::get('SERVER_NAME')) . TT::toString(Server::get('REQUEST_URI'));
}
function apbct_get_pixel_url($direct_call = false)
{
global $apbct;
$ip = Helper::ipGet();
$ip_version = Helper::ipValidate(TT::toString($ip));
$pixel_hash = md5(
$ip
. $apbct->api_key
. Helper::timeGetIntervalStart(3600 * 3) // Unique for every 3 hours
);
//get params for cache plugins exclusion detection
$cache_plugins_detected = apbct_is_cache_plugins_exists(true);
$cache_exclusion_snippet = '';
if ( !empty($cache_plugins_detected) ) {
//NitroPack
if ( in_array('NitroPack', $cache_plugins_detected) ) {
$cache_exclusion_snippet = '?gclid=' . $pixel_hash;
}
}
//construct URL
$server = get_option('cleantalk_server');
$server_url = isset($server['ct_work_url']) ? $apbct->server['ct_work_url'] : APBCT_MODERATE_URL;
$server_url_with_version = $ip_version === 'v4' ? str_replace('.cleantalk.org', '-v4.cleantalk.org', $server_url) : $server_url;
$pixel = '/pixel/' . $pixel_hash . '.gif' . $cache_exclusion_snippet;
$pixel_url = str_replace('http://', 'https://', $server_url_with_version) . $pixel;
if ( $direct_call ) {
return $pixel_url ;
}
die($pixel_url);
}
/**
* Checking email before POST
*/
function apbct_email_check_before_post()
{
$email = trim(TT::toString(Post::get('email')), " \n\r\t\v\x00");
if ( $email ) {
$result = \Cleantalk\ApbctWP\API::methodEmailCheck($email);
if ( isset($result['data']) ) {
die(json_encode(array('result' => $result['data'])));
}
die(json_encode(array('error' => 'ERROR_CHECKING_EMAIL')));
}
die(json_encode(array('error' => 'EMPTY_DATA')));
}
/**
* Checking email exist before POST
*/
function apbct_email_check_exist_post()
{
global $apbct;
$email = trim(TT::toString(Post::get('email')), " \n\r\t\v\x00");
$api_key = $apbct->api_key;
$brandname = $apbct->data['wl_mode_enabled'] ? $apbct->data['wl_brandname'] : 'Anti-Spam by CleanTalk';
if ( $email && $api_key ) {
$result = \Cleantalk\ApbctWP\API::methodEmailCheckExist($email, $api_key);
if ( isset($result['result']) ) {
$text_result = '';
if ( $result['result'] != 'EXISTS' ) {
$text_result = __('The email doesn`t exist, double check the address.', 'cleantalk-spam-protect') . ' ' . $brandname . '.';
} else {
$text_result = __('The email exists and is good to use!', 'cleantalk-spam-protect') . ' ' . $brandname . '.';
}
$result['text_result'] = $text_result;
die(json_encode(array('result' => $result)));
}
die(json_encode(array('error' => 'ERROR_CHECKING_EMAIL')));
}
die(json_encode(array('error' => 'EMPTY_DATA')));
}
/**
* Force protection check bot
*/
function apbct_force_protection_check_bot()
{
die(\Cleantalk\ApbctWP\Antispam\ForceProtection::getInstance()->checkBot());
}
/**
* Get ct_get_checkjs_value
*
* @return int|string|null
*/
function ct_get_checkjs_value()
{
global $apbct;
// Use static JS keys
if ( $apbct->settings['data__use_static_js_key'] == 1 ) {
$key = hash('sha256', $apbct->api_key . ct_get_admin_email() . $apbct->salt);
// Auto detecting. Detected.
} elseif (
$apbct->settings['data__use_static_js_key'] == -1 &&
(apbct_is_cache_plugins_exists() ||
(apbct_is_post() && isset($apbct->data['cache_detected']) && $apbct->data['cache_detected'] == 1)
)
) {
$key = hash('sha256', $apbct->api_key . ct_get_admin_email() . $apbct->salt);
if ( apbct_is_cache_plugins_exists() ) {
$apbct->data['cache_detected'] = 1;
}
$apbct->saveData();
// Using dynamic JS keys
} else {
$keys = $apbct->data['js_keys'];
$keys_checksum = md5(json_encode($keys));
$key = null;
$latest_key_time = 0;
foreach ( $keys as $k => $t ) {
if (!is_object($t)) {
// Removing key if it's to old
if ( time() - $t > $apbct->data['js_keys_store_days'] * 86400 * 7 ) {
unset($keys[$k]);
continue;
}
if ( $t > $latest_key_time ) {
$latest_key_time = $t;
$key = $k;
}
} else {
$keys = array();
}
}
// Set new key if the latest key is too old
if ( time() - $latest_key_time > $apbct->data['js_key_lifetime'] ) {
$key = rand();
$keys[$key] = time();
}
// Save keys if they were changed
if ( md5(json_encode($keys)) != $keys_checksum ) {
$apbct->data['js_keys'] = $keys;
// $apbct->saveData();
}
$apbct->data['cache_detected'] = 0;
$apbct->saveData();
}
return $key;
}
function apbct_is_cache_plugins_exists($return_names = false)
{
$out = array();
$constants_of_cache_plugins = array(
'WP_ROCKET_VERSION' => 'WPRocket',
'LSCWP_DIR' => 'LiteSpeed Cache',
'WPFC_WP_CONTENT_BASENAME' => 'WP Fastest Cache',
'W3TC' => 'W3 Total Cache',
'WPO_VERSION' => 'WP-Optimize – Clean, Compress, Cache',
'AUTOPTIMIZE_PLUGIN_VERSION' => 'Autoptimize',
'WPCACHEHOME' => 'WP Super Cache',
'WPHB_VERSION' => 'Hummingbird – Speed up, Cache, Optimize Your CSS and JS',
'CE_FILE' => 'Cache Enabler – WordPress Cache',
'SiteGround_Optimizer\VERSION' => 'SG Optimizer',
'NITROPACK_VERSION' => 'NitroPack',
'TWO_PLUGIN_FILE' => '10Web Booster',
'FLYING_PRESS_VERSION' => 'Flying Press',
'BREEZE_VERSION' => 'Breeze',
'SPEEDYCACHE_VERSION' => 'SpeedyCache',
);
$classes_of_cache_plugins = array (
'\RedisObjectCache' => 'Redis',
'\WP_Rest_Cache_Plugin\Includes\Plugin' => 'Rest Cache'
);
$headers = array(
'HTTP_X_VARNISH' => 'Varnish',
);
foreach ($constants_of_cache_plugins as $const => $_text) {
if ( defined($const) ) {
$out[] = $_text;
}
}
foreach ($classes_of_cache_plugins as $class => $_text) {
/**
* @psalm-suppress DocblockTypeContradiction
* @psalm-suppress TypeDoesNotContainType
*/
if ( class_exists($class) ) {
$out[] = $_text;
}
}
foreach ($headers as $header => $_text) {
if ( isset($_SERVER[$header]) ) {
$out[] = $_text;
}
}
return $return_names ? $out : !empty($out);
}
function apbct_is_varnish_cache_exists()
{
return isset($_SERVER['HTTP_X_VARNISH']);
}
function apbct_is_advanced_cache_exists()
{
return apbct_is_cache_plugins_exists() && file_exists(untrailingslashit(WP_CONTENT_DIR) . '/advanced-cache.php');
}
function apbct_is_10web_booster_exists()
{
return apbct_is_cache_plugins_exists() && apbct_is_plugin_active('tenweb-speed-optimizer/tenweb_speed_optimizer.php');
}
/**
* Inner function - Current site admin e-mail
* @return string Admin e-mail
*/
function ct_get_admin_email()
{
global $apbct;
if ( ! is_multisite() ) {
// Not WPMS
$admin_email = get_option('admin_email');
} elseif ( is_main_site() || $apbct->network_settings['multisite__work_mode'] != 3) {
// WPMS - Main site, common account
$admin_email = get_site_option('admin_email');
} else {
// WPMS - Individual account, individual Access key
$admin_email = get_blog_option(get_current_blog_id(), 'admin_email');
}
if ( $apbct->data['account_email'] ) {
add_filter('apbct_get_api_key_email', function () {
global $apbct;
return $apbct->data['account_email'];
});
}
return $admin_email;
}
/**
* Inner function - Current CleanTalk working server info
* @return array Array of server data
*/
function ct_get_server()
{
$ct_server = get_option('cleantalk_server');
if ( ! is_array($ct_server) ) {
$ct_server = array(
'ct_work_url' => null,
'ct_server_ttl' => null,
'ct_server_changed' => null
);
}
$ct_server['ct_work_url'] = Sanitize::sanitizeCleantalkServerUrl(TT::getArrayValueAsString($ct_server, 'ct_work_url'));
return $ct_server;
}
/**
* @param $url
*
* @return string|null
*/
function sanitize_cleantalk_server_url($url)
{
if (!is_string($url)) {
return null;
}
return preg_match('/^.*(moderate|api).*\.cleantalk.org(?!\.)[\/\\\\]{0,1}/m', $url)
? $url
: null;
}
/**
* Inner function - Stores ang returns cleantalk hash of current comment
*