-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCleantalk.php
521 lines (448 loc) · 14.6 KB
/
Cleantalk.php
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
<?php
namespace Cleantalk\Common\Antispam;
use Cleantalk\Common\Helper\Helper;
use Cleantalk\Common\Mloader\Mloader;
/**
* Cleantalk base class
*
* @version 2.2
* @package Cleantalk
* @subpackage Base
* @author Cleantalk team (welcome@cleantalk.org)
* @copyright (C) 2014 CleanTalk team (http://cleantalk.org)
* @license GNU/GPL: http://www.gnu.org/copyleft/gpl.html
* @see https://github.com/CleanTalk/php-antispam
*
*/
class Cleantalk
{
/**
* Maximum data size in bytes
* @var int
*/
private $dataMaxSise = 32768;
/**
* Data compression rate
* @var int
*/
private $compressRate = 6;
/**
* Server connection timeout in seconds
* @var int
*/
private $server_timeout = 15;
/**
* Cleantalk server url
* @var string
*/
public $server_url;
/**
* Last work url
* @var string
*/
public $work_url;
/**
* Work url ttl
* @var int
*/
public $server_ttl;
/**
* Time work_url changed
* @var int
*/
public $server_changed;
/**
* Flag is change server url
* @var bool
*/
public $server_change = false;
/**
* Codepage of the data
* @var string
*/
public $data_codepage = '';
/**
* API version to use
* @var string
*/
public $api_version = '/api2.0';
/**
* Minimal server response in milliseconds to catch the server
* @var int
*/
public $min_server_timeout = 50;
/**
* Maximal server response in milliseconds to catch the server
* @var int
*/
public $max_server_timeout = 1500;
/**
* List of the down servers.
* Non responsible moderate servers list
*
* @var array
*/
private $downServers;
/**
* Function checks whether it is possible to publish the message
*
* @param CleantalkRequest $request
*
* @return bool|CleantalkResponse
*/
public function isAllowMessage(CleantalkRequest $request)
{
$msg = $this->createMsg('check_message', $request);
return $this->httpRequest($msg);
}
/**
* Function checks whether it is possible to publish the message
*
* @param CleantalkRequest $request
*
* @return bool|CleantalkResponse
*/
public function isAllowUser(CleantalkRequest $request)
{
$msg = $this->createMsg('check_newuser', $request);
return $this->httpRequest($msg);
}
/**
* Function sends the results of manual moderation
*
* @param CleantalkRequest $request
*
* @return bool|CleantalkResponse
*/
public function sendFeedback(CleantalkRequest $request)
{
$msg = $this->createMsg('send_feedback', $request);
return $this->httpRequest($msg);
}
/**
* Create msg for cleantalk server
*
* @param string $method
* @param CleantalkRequest $request
*
* @return CleantalkRequest
*/
private function createMsg($method, CleantalkRequest $request)
{
switch ( $method ) {
case 'check_message':
// Convert strings to UTF8
$request->message = Helper::toUTF8($request->message, $this->data_codepage);
$request->example = Helper::toUTF8($request->example, $this->data_codepage);
$request->sender_email = Helper::toUTF8($request->sender_email, $this->data_codepage);
$request->sender_nickname = Helper::toUTF8($request->sender_nickname, $this->data_codepage);
$request->message = $this->compressData($request->message);
$request->example = $this->compressData($request->example);
break;
case 'check_newuser':
// Convert strings to UTF8
$request->sender_email = Helper::toUTF8($request->sender_email, $this->data_codepage);
$request->sender_nickname = Helper::toUTF8($request->sender_nickname, $this->data_codepage);
break;
case 'send_feedback':
if ( is_array($request->feedback) ) {
$request->feedback = implode(';', $request->feedback);
}
break;
}
// Removing non UTF8 characters from request, because non UTF8 or malformed characters break json_encode().
foreach ( $request as $param => $value ) {
if ( is_array($request->$param) || is_string($request->$param) ) {
$request->$param = Helper::removeNonUTF8($value);
}
}
$request->method_name = $method;
$request->message = is_array($request->message) ? json_encode($request->message) : $request->message;
// Wiping cleantalk's headers but, not for send_feedback
if ( $request->method_name !== 'send_feedback' ) {
$ct_tmp = Helper::httpGetHeaders();
if ( isset($ct_tmp['Cookie']) ) {
$cookie_name = 'Cookie';
} elseif ( isset($ct_tmp['cookie']) ) {
$cookie_name = 'cookie';
} else {
$cookie_name = 'COOKIE';
}
if ( $ct_tmp ) {
if ( isset($ct_tmp[$cookie_name]) ) {
$ct_tmp[$cookie_name] = preg_replace(array(
'/\s?ct_checkjs=[a-z0-9]*[^;]*;?/',
'/\s?ct_timezone=.{0,1}\d{1,2}[^;]*;?/',
'/\s?ct_pointer_data=.*5D[^;]*;?/',
'/\s?apbct_timestamp=\d*[^;]*;?/',
'/\s?apbct_site_landing_ts=\d*[^;]*;?/',
'/\s?apbct_cookies_test=%7B.*%7D[^;]*;?/',
'/\s?apbct_prev_referer=http.*?[^;]*;?/',
'/\s?ct_ps_timestamp=.*?[^;]*;?/',
'/\s?ct_fkp_timestamp=\d*?[^;]*;?/',
'/\s?wordpress_ct_sfw_pass_key=\d*?[^;]*;?/',
'/\s?apbct_page_hits=\d*?[^;]*;?/',
'/\s?apbct_visible_fields_count=\d*?[^;]*;?/',
'/\s?apbct_visible_fields=%7B.*%7D[^;]*;?/',
'/\s?apbct_visible_fields_\d=%7B.*%7D[^;]*;?/',
), '', $ct_tmp[$cookie_name]);
}
$request->all_headers = json_encode($ct_tmp);
}
}
return $request;
}
/**
* Compress data and encode to base64
*
* @param string $data
*
* @return null|string
*/
private function compressData($data = null)
{
if ( !is_string($data) ) {
return $data;
}
if ( strlen($data) > $this->dataMaxSise && function_exists('\gzencode') && function_exists('base64_encode') ) {
$localData = \gzencode($data, $this->compressRate, FORCE_GZIP);
if ( $localData === false ) {
return $data;
}
return base64_encode($localData);
}
return $data;
}
/**
* httpRequest
*
* @param $msg
*
* @return CleantalkResponse
*/
private function httpRequest($msg)
{
// Using current server without changing it
$result = !empty($this->work_url) && $this->server_changed + 86400 > time()
? $this->sendRequest($msg, $this->work_url, $this->server_timeout)
: false;
// Changing server if no work_url or request has an error
if ( $result === false || (is_object($result) && $result->errno != 0) ) {
if ( !empty($this->work_url) ) {
$this->downServers[] = $this->work_url;
}
$this->rotateModerate();
$result = $this->sendRequest($msg, $this->work_url, $this->server_timeout);
if ( $result !== false && $result->errno === 0 ) {
$this->server_change = true;
}
}
$response = new CleantalkResponse($result);
if ( !empty($this->data_codepage) && $this->data_codepage !== 'UTF-8' ) {
if ( !empty($response->comment) ) {
$response->comment = Helper::fromUTF8($response->comment, $this->data_codepage);
}
if ( !empty($response->errstr) ) {
$response->errstr = Helper::fromUTF8($response->errstr, $this->data_codepage);
}
if ( !empty($response->sms_error_text) ) {
$response->sms_error_text = Helper::fromUTF8($response->sms_error_text, $this->data_codepage);
}
}
return $response;
}
/**
* * @todo Refactor / fix logic errors
*/
public function rotateModerate()
{
// Split server url to parts
preg_match("/^(https?:\/\/)([^\/:]+)(.*)/i", $this->server_url, $matches);
$url_protocol = isset($matches[1]) ? $matches[1] : '';
$url_host = isset($matches[2]) ? $matches[2] : '';
$url_suffix = isset($matches[3]) ? $matches[3] : '';
$servers = $this->getServersIp($url_host);
if ( !$servers ) {
return;
}
// Loop until find work server
foreach ( $servers as $server ) {
$dns = Helper::ipResolveCleantalks($server['ip']);
if ( !$dns ) {
continue;
}
$this->work_url = $url_protocol . $dns . $url_suffix;
// Do not checking previous down server
if ( !empty($this->downServers) && in_array($this->work_url, $this->downServers) ) {
continue;
}
$this->server_ttl = $server['ttl'];
$this->server_change = true;
break;
}
}
/**
* @param $host
* @return array|null
* @todo Refactor / fix logic errors
*
* Function DNS request
*
* @psalm-suppress RedundantCondition
*/
public function getServersIp($host)
{
if ( !isset($host) ) {
return null;
}
$servers = array();
// Get DNS records about URL
if ( function_exists('dns_get_record') ) {
$records = @dns_get_record($host, DNS_A);
if ( $records !== false ) {
foreach ( $records as $server ) {
$servers[] = $server;
}
}
}
// Another try if first failed
if ( count($servers) === 0 && function_exists('gethostbynamel') ) {
$records = gethostbynamel($host);
if ( $records !== false ) {
foreach ( $records as $server ) {
$servers[] = array(
"ip" => $server,
"host" => $host,
"ttl" => $this->server_ttl
);
}
}
}
// If couldn't get records
if ( count($servers) === 0 ) {
$servers[] = array(
"ip" => null,
"host" => $host,
"ttl" => $this->server_ttl
);
// If records received
} else {
$tmp = array();
$fast_server_found = false;
foreach ( $servers as $server ) {
if ( $fast_server_found ) {
$ping = $this->max_server_timeout;
} else {
$ping = $this->httpPing($server['ip']);
$ping *= 1000;
}
$tmp[(int)$ping] = $server;
$fast_server_found = $ping < $this->min_server_timeout;
}
if ( count($tmp) ) {
ksort($tmp);
$response = $tmp;
}
}
return empty($response) ? null : $response;
}
/**
* Function to check response time
*
* @param string $host
*
* @return float|int
*/
public function httpPing($host)
{
// Skip localhost ping cause it raise error at fsockopen.
// And return minimum value
if ( $host === 'localhost' ) {
return 0.001;
}
$starttime = microtime(true);
$file = @fsockopen($host, 443, $errno, $errstr, $this->max_server_timeout / 1000);
$stoptime = microtime(true);
if ( !$file ) {
$status = $this->max_server_timeout / 1000; // Site is down
} else {
fclose($file);
$status = ($stoptime - $starttime);
$status = round($status, 4);
}
return $status;
}
/**
* Send JSON request to servers
*
* @param string|array $data
* @param string $url
* @param int $server_timeout
*
* @return boolean|CleantalkResponse
*/
private function sendRequest($data, $url, $server_timeout = 3)
{
//Cleaning from 'null' values
$tmp_data = array();
foreach ( $data as $key => $value ) {
if ( $value !== null ) {
$tmp_data[$key] = $value;
}
}
$data = $tmp_data;
unset($key, $value, $tmp_data);
// Convert to JSON
$data = json_encode($data);
if ( isset($this->api_version) ) {
$url .= $this->api_version;
}
/** @var \Cleantalk\Common\Http\Request $request_class */
$request_class = Mloader::get('Http\Request');
$http = new $request_class();
$result = $http->setUrl($url)
->setData($data)
->setOptions(['timeout' => $server_timeout])
->request();
$errstr = null;
$response = is_string($result) ? json_decode($result) : false;
if ( $result !== false && is_object($response) ) {
$response->errno = 0;
$response->errstr = $errstr;
} else {
if ( isset($result['error']) ) {
$error = $result['error'];
} else {
if ( is_string($result) ) {
$error = $result;
} else {
$error = '';
}
}
$errstr = 'Unknown response from ' . $url . ': ' . $error;
$response = null;
$response['errno'] = 1;
$response['errstr'] = $errstr;
$response = json_decode(json_encode($response));
}
return $response;
}
/**
* Call check_bot API method
*
* Make a decision if it's bot or not based on limited input JavaScript data
*
* @param CleantalkRequest $request
*
* @return CleantalkResponse
*/
public function checkBot(CleantalkRequest $request)
{
$msg = $this->createMsg('check_bot', $request);
return $this->httpRequest($msg);
}
public static function getLockPageFile()
{
return __DIR__ . '/lock-page-ct-die.html';
}
}