├── README.md
├── Cleantalk
└── Antispam
│ ├── registration.php
│ ├── etc
│ ├── module.xml
│ ├── frontend
│ │ ├── controller.xml
│ │ ├── routes.xml
│ │ └── events.xml
│ ├── config.xml
│ └── adminhtml
│ │ └── system.xml
│ ├── Controller
│ └── AjaxHandler
│ │ └── Index.php
│ ├── view
│ └── frontend
│ │ ├── templates
│ │ └── apbct-js-localization.phtml
│ │ ├── layout
│ │ └── default.xml
│ │ └── web
│ │ └── js
│ │ ├── cleantalk.js
│ │ └── ct_external_forms.js
│ ├── composer.json
│ ├── lib
│ ├── Autoloader.php
│ └── Cleantalk
│ │ └── Common
│ │ ├── Templates
│ │ ├── Multiton.php
│ │ └── Singleton.php
│ │ ├── Variables
│ │ ├── Get.php
│ │ ├── Post.php
│ │ ├── Request.php
│ │ ├── Cookie.php
│ │ ├── Server.php
│ │ └── ServerVariables.php
│ │ ├── Http
│ │ ├── Response.php
│ │ └── Request.php
│ │ ├── Cleaner
│ │ ├── Escape.php
│ │ ├── Validate.php
│ │ └── Sanitize.php
│ │ ├── Mloader
│ │ └── Mloader.php
│ │ └── Antispam
│ │ ├── CleantalkResponse.php
│ │ ├── lock-page-ct-die.html
│ │ ├── CleantalkRequest.php
│ │ └── Cleantalk.php
│ ├── Block
│ └── JsLocalization.php
│ ├── Observer
│ ├── error.html
│ └── Predispatch.php
│ └── Model
│ └── Carrier
│ └── Method.php
├── .github
└── workflows
│ ├── releaseNotice.yml
│ └── reviewNotice.yml
├── .gitignore
└── LICENSE
/README.md:
--------------------------------------------------------------------------------
1 | Anti-spam plugin for Magento 2.x
2 | ============
3 |
4 | ## Requirements
5 |
6 | * CleanTalk account https://cleantalk.org/register?product=anti-spam
7 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/registration.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/Controller/AjaxHandler/Index.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/etc/frontend/routes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/view/frontend/templates/apbct-js-localization.phtml:
--------------------------------------------------------------------------------
1 |
6 |
14 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/etc/frontend/events.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cleantalk/antispam",
3 | "description": "Antispam by CleanTalk",
4 | "type": "magento2-module",
5 | "homepage": "https://cleantalk.org",
6 | "version": "1.6.0",
7 | "time": "2016-10-27",
8 | "license": "GPL-2.0",
9 | "authors": [
10 | {
11 | "name": "Roman Safronov",
12 | "email": "welcome@cleantalk.org",
13 | "homepage": "https://cleantalk.org",
14 | "role": "Developer"
15 | }
16 | ],
17 | "autoload": {
18 | "files": [ "registration.php" ],
19 | "psr-4": {
20 | "Cleantalk\\Antispam\\": ""
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/view/frontend/layout/default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/.github/workflows/releaseNotice.yml:
--------------------------------------------------------------------------------
1 | name: Notice about releases via Matrix
2 |
3 | on:
4 | release:
5 | types: [published]
6 |
7 | jobs:
8 |
9 | build:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - name: Send Matrix message on release
13 | uses: Glomberg/matrix-messenger-action@master
14 | with:
15 | server: ${{ secrets.MATRIX_SERVER }}
16 | to: ${{ secrets.MATRIX_NEWS_ROOM }}
17 | token: ${{ secrets.MATRIX_USER_TOKEN }}
18 | message: |
19 | ${{ github.event.repository.description }} v${{github.event.release.name}} released
20 |
${{github.event.release.html_url}}
21 |
22 |
${{ github.event.release.body }}
23 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Autoloader.php:
--------------------------------------------------------------------------------
1 | init($params);
24 | }
25 |
26 | return static::$instances[$instance];
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/Block/JsLocalization.php:
--------------------------------------------------------------------------------
1 | _scopeConfig->getValue($path);
11 |
12 | $params = [
13 | // @ToDo we can make it stronger - add a salt
14 | 'jsKey' => hash('sha256', $config)
15 | ];
16 | return json_encode($params);
17 | }
18 | public function getExternalFormsEnabled()
19 | {
20 | $external_forms_option = 'general/cleantalkantispam/ct_external_forms';
21 | $external_forms = $this->_scopeConfig->getValue($external_forms_option);
22 |
23 | $params = [
24 | 'externalForms' => $external_forms,
25 | 'ajaxUrl' => $this->getUrl('cleantalkajax/ajaxhandler'),
26 | ];
27 | return json_encode($params);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/etc/config.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Cleantalk\Antispam\Model\Carrier\Method
8 | CleanTalk Antispam
9 | 1
10 | None
11 | 1
12 | 1
13 | 1
14 | 1
15 | 0
16 | None
17 | This shipping method is not available. To use this shipping method, please contact us.
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Variables/Get.php:
--------------------------------------------------------------------------------
1 | variables
27 | if (! isset(static::$instance->variables[$name])) {
28 | if ( isset($_GET[$name]) ) {
29 | $value = $this->getAndSanitize($_GET[$name]);
30 | } else {
31 | $value = '';
32 | }
33 |
34 | // Remember for further calls
35 | static::getInstance()->rememberVariable($name, $value);
36 |
37 | return $value;
38 | }
39 |
40 | return static::$instance->variables[$name];
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Variables/Post.php:
--------------------------------------------------------------------------------
1 | variables
28 | if (! isset(static::$instance->variables[$name])) {
29 | if ( isset($_POST[$name]) ) {
30 | $value = $this->getAndSanitize($_POST[$name]);
31 | } else {
32 | $value = '';
33 | }
34 |
35 | // Remember for further calls
36 | static::getInstance()->rememberVariable($name, $value);
37 |
38 | return $value;
39 | }
40 |
41 | return static::$instance->variables[$name];
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Templates/Singleton.php:
--------------------------------------------------------------------------------
1 | init($params);
31 | }
32 | return static::$instance;
33 | }
34 |
35 | /**
36 | * Alternative constructor
37 | */
38 | protected function init()
39 | {
40 | }
41 |
42 | public static function resetInstance()
43 | {
44 | static::$instance = null;
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/.github/workflows/reviewNotice.yml:
--------------------------------------------------------------------------------
1 | name: Notice about review approved via Matrix
2 |
3 | on:
4 | pull_request_review:
5 | types: [ submitted ]
6 |
7 | jobs:
8 |
9 | build:
10 | if: github.event.review.state == 'approved' && toJSON(github.event.pull_request.requested_reviewers) == '[]'
11 | runs-on: ubuntu-latest
12 | steps:
13 | - name: Convert date format
14 | id: date
15 | run: echo "::set-output name=date::$(date -d "${{ github.event.pull_request.created_at }}" +"%Y-%m-%d")"
16 | - name: Send Matrix message on review approved
17 | uses: Glomberg/matrix-messenger-action@master
18 | with:
19 | server: ${{ secrets.MATRIX_SERVER }}
20 | to: ${{ secrets.MATRIX_EXTERNSION_ROOM }}
21 | token: ${{ secrets.MATRIX_USER_TOKEN }}
22 | message: |
23 | 💥🎉🎉🎉💥 Pull-request ${{ github.event.pull_request.title }}
24 | submitted by ${{ github.event.pull_request.user.login }} at ${{ steps.date.outputs.date }}
25 |
26 | was approved and is ready to merge ➡️ !!!
27 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /Cleantalk/Antispam/vendor/
2 | /Cleantalk/Antispam/lib/Cleantalk/Common/Antispam/.github/
3 | /Cleantalk/Antispam/lib/Cleantalk/Common/Antispam/tests
4 | /Cleantalk/Antispam/lib/Cleantalk/Common/Antispam/.gitignore
5 | /Cleantalk/Antispam/lib/Cleantalk/Common/Antispam/composer.json
6 | /Cleantalk/Antispam/lib/Cleantalk/Common/Cleaner/.gitignore
7 | /Cleantalk/Antispam/lib/Cleantalk/Common/Cleaner/composer.json
8 | /Cleantalk/Antispam/lib/Cleantalk/Common/Helper/.github/
9 | /Cleantalk/Antispam/lib/Cleantalk/Common/Helper/tests/
10 | /Cleantalk/Antispam/lib/Cleantalk/Common/Helper/.gitignore
11 | /Cleantalk/Antispam/lib/Cleantalk/Common/Helper/composer.json
12 | /Cleantalk/Antispam/lib/Cleantalk/Common/Http/.gitignore
13 | /Cleantalk/Antispam/lib/Cleantalk/Common/Http/composer.json
14 | /Cleantalk/Antispam/lib/Cleantalk/Common/Http/README.md
15 | /Cleantalk/Antispam/lib/Cleantalk/Common/Mloader/.gitignore
16 | /Cleantalk/Antispam/lib/Cleantalk/Common/Mloader/composer.json
17 | /Cleantalk/Antispam/lib/Cleantalk/Common/Templates/.gitignore
18 | /Cleantalk/Antispam/lib/Cleantalk/Common/Templates/composer.json
19 | /Cleantalk/Antispam/lib/Cleantalk/Common/Variables/.gitignore
20 | /Cleantalk/Antispam/lib/Cleantalk/Common/Variables/composer.json
21 | /Cleantalk/Antispam/composer.lock
22 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Variables/Request.php:
--------------------------------------------------------------------------------
1 | variables
28 | if (isset(static::$instance->variables[$name])) {
29 | return static::$instance->variables[$name];
30 | }
31 |
32 | $value = '';
33 |
34 | $class_name = get_class(self::getInstance());
35 | $reflection_class = new \ReflectionClass($class_name);
36 | $namespace = $reflection_class->getNamespaceName();
37 |
38 | $post_class = $namespace . '\\Post';
39 | $get_class = $namespace . '\\Get';
40 | $cookie_class = $namespace . '\\Cookie';
41 |
42 | if ( $post_class::get($name) ) {
43 | $value = $post_class::get($name);
44 | } elseif ( $get_class::get($name) ) {
45 | $value = $get_class::get($name);
46 | } elseif ( $cookie_class::get($name) ) {
47 | $value = $cookie_class::get($name);
48 | }
49 |
50 | // Remember for further calls
51 | static::getInstance()->rememberVariable($name, $value);
52 |
53 | return $value;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Http/Response.php:
--------------------------------------------------------------------------------
1 | raw = $raw;
22 | $this->processed = $raw;
23 | $this->info = $info;
24 | $this->error = ! empty($raw['error'])
25 | ? $raw
26 | : null;
27 | if ( isset($this->info['http_code']) ) {
28 | $this->response_code = (int)$this->info['http_code'];
29 | }
30 | }
31 |
32 | /**
33 | * @return mixed
34 | */
35 | public function getError()
36 | {
37 | return $this->error;
38 | }
39 |
40 | /**
41 | * @return mixed
42 | */
43 | public function getResponseCode()
44 | {
45 | return $this->response_code;
46 | }
47 |
48 | /**
49 | * @return mixed
50 | */
51 | public function getContentRaw()
52 | {
53 | return $this->raw;
54 | }
55 |
56 | /**
57 | * @return mixed
58 | */
59 | public function getContentProcessed()
60 | {
61 | return $this->processed;
62 | }
63 |
64 | /**
65 | * @param mixed $processed
66 | */
67 | public function setProcessed($processed)
68 | {
69 | $this->processed = $processed;
70 | }
71 |
72 | /**
73 | * @return mixed
74 | */
75 | public function getInfo()
76 | {
77 | return $this->info;
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Cleaner/Escape.php:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 | Blacklisted
8 |
48 |
49 |
50 | CleanTalk. Spam protection
51 | %ERROR_TEXT%
52 |
53 | « Back
54 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Mloader/Mloader.php:
--------------------------------------------------------------------------------
1 | _rateResultFactory = $rateResultFactory;
34 | $this->_rateMethodFactory = $rateMethodFactory;
35 | parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
36 | }
37 |
38 | /**
39 | * get allowed methods
40 | * @return array
41 | */
42 | public function getAllowedMethods()
43 | {
44 | return [$this->_code => $this->getConfigData('name')];
45 | }
46 |
47 | /**
48 | * @param RateRequest $request
49 | * @return bool|Result
50 | */
51 | public function collectRates(RateRequest $request)
52 | {
53 | if (!$this->getConfigFlag('enable')) {
54 | return false;
55 | }
56 |
57 | /** @var \Magento\Shipping\Model\Rate\Result $result */
58 | $result = $this->_rateResultFactory->create();
59 |
60 | /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
61 | $method = $this->_rateMethodFactory->create();
62 |
63 | $method->setCarrier($this->_code);
64 | $method->setCarrierTitle($this->getConfigData('title'));
65 |
66 | $method->setMethod($this->_code);
67 | $method->setMethodTitle($this->getConfigData('name'));
68 |
69 | $amount = $this->getConfigData('price');
70 |
71 | $method->setPrice($amount);
72 | $method->setCost($amount);
73 |
74 | $result->append($method);
75 |
76 | return $result;
77 | }
78 | }
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Cleaner/Validate.php:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 | Magento\Config\Model\Config\Source\Yesno
16 |
17 |
18 |
19 |
20 |
21 |
22 | Magento\Config\Model\Config\Source\Yesno
23 |
24 |
25 |
26 | Magento\Config\Model\Config\Source\Yesno
27 |
28 |
29 |
30 | Magento\Config\Model\Config\Source\Yesno
31 |
32 |
33 |
34 | Magento\Config\Model\Config\Source\Yesno
35 |
36 |
37 |
38 | Magento\Config\Model\Config\Source\Yesno
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Variables/Cookie.php:
--------------------------------------------------------------------------------
1 | variables
27 | if (! isset(static::$instance->variables[$name])) {
28 | if ( isset($_COOKIE[$name]) ) {
29 | $value = $this->getAndSanitize($_COOKIE[$name]);
30 | } else {
31 | $value = '';
32 | }
33 |
34 | // Remember for further calls
35 | static::getInstance()->rememberVariable($name, $value);
36 |
37 | return $value;
38 | }
39 |
40 | return static::$instance->variables[$name];
41 | }
42 |
43 | /**
44 | * Universal method to adding cookies
45 | * Wrapper for setcookie() Conisdering PHP version
46 | *
47 | * @see https://www.php.net/manual/ru/function.setcookie.php
48 | *
49 | * @param string $name Cookie name
50 | * @param string $value Cookie value
51 | * @param int $expires Expiration timestamp. 0 - expiration with session
52 | * @param string $path
53 | * @param string $domain
54 | * @param bool $secure
55 | * @param bool $httponly
56 | * @param string $samesite
57 | *
58 | * @return void
59 | * @psalm-suppress PossiblyUnusedMethod
60 | */
61 | public static function set(
62 | $name,
63 | $value = '',
64 | $expires = 0,
65 | $path = '',
66 | $domain = '',
67 | $secure = null,
68 | $httponly = false,
69 | $samesite = 'Lax'
70 | ) {
71 | if (headers_sent()) {
72 | return;
73 | }
74 |
75 | $secure = ! is_null($secure) ? $secure : ! in_array(Server::get('HTTPS'), ['off', '']) || Server::get('SERVER_PORT') == 443;
76 |
77 | // For PHP 7.3+ and above
78 | if ( version_compare(phpversion(), '7.3.0', '>=') ) {
79 | $params = array(
80 | 'expires' => $expires,
81 | 'path' => $path,
82 | 'domain' => $domain,
83 | 'secure' => $secure,
84 | 'httponly' => $httponly,
85 | );
86 |
87 | if ($samesite) {
88 | $params['samesite'] = $samesite;
89 | }
90 |
91 | /**
92 | * @psalm-suppress InvalidArgument
93 | */
94 | setcookie($name, $value, $params);
95 | // For PHP 5.6 - 7.2
96 | } else {
97 | setcookie($name, $value, $expires, $path, $domain, $secure, $httponly);
98 | }
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/view/frontend/web/js/cleantalk.js:
--------------------------------------------------------------------------------
1 | define(['jquery'], function ($) {
2 | 'use strict';
3 |
4 | /**
5 | * @param {Object} config
6 | */
7 | return function (config) {
8 |
9 | let d = new Date(),
10 | ctTimeMs = new Date().getTime(),
11 | ctMouseEventTimerFlag = true, //Reading interval flag
12 | ctMouseData = "[",
13 | ctMouseDataCounter = 0;
14 |
15 | function ctSetCookie(c_name,value){
16 | document.cookie = c_name + "=" + escape(value) + "; path=/";
17 | }
18 |
19 | setTimeout(function(){
20 | ctSetCookie("ct_checkjs", config.jsKey);
21 | }, 1000);
22 | ctSetCookie("ct_ps_timestamp", Math.floor(new Date().getTime()/1000));
23 | ctSetCookie("ct_timezone", d.getTimezoneOffset()/60*(-1));
24 | ctSetCookie("ct_fkp_timestamp", "0");
25 | ctSetCookie("ct_pointer_data", "0");
26 | //Reading interval
27 | var ctMouseReadInterval = setInterval(function(){
28 | ctMouseEventTimerFlag = true;
29 | }, 150);
30 |
31 | //Writting interval
32 | var ctMouseWriteDataInterval = setInterval(function(){
33 | var ctMouseDataToSend = ctMouseData.slice(0,-1).concat("]");
34 | ctSetCookie("ct_pointer_data", ctMouseDataToSend);
35 | }, 1200);
36 |
37 | //Stop observing function
38 | function ctMouseStopData(){
39 | if(typeof window.addEventListener == "function")
40 | window.removeEventListener("mousemove", ctFunctionMouseMove);
41 | else
42 | window.detachEvent("onmousemove", ctFunctionMouseMove);
43 | clearInterval(ctMouseReadInterval);
44 | clearInterval(ctMouseWriteDataInterval);
45 | }
46 | //Logging mouse position each 300 ms
47 | var ctFunctionMouseMove = function output(event){
48 | if(ctMouseEventTimerFlag == true){
49 | var mouseDate = new Date();
50 | ctMouseData += "[" + Math.round(event.pageY) + "," + Math.round(event.pageX) + "," + Math.round(mouseDate.getTime() - ctTimeMs) + "],";
51 | ctMouseDataCounter++;
52 | ctMouseEventTimerFlag = false;
53 | if(ctMouseDataCounter >= 100)
54 | ctMouseStopData();
55 | }
56 | };
57 |
58 | //Stop key listening function
59 | function ctKeyStopStopListening(){
60 | if(typeof window.addEventListener == "function"){
61 | window.removeEventListener("mousedown", ctFunctionFirstKey);
62 | window.removeEventListener("keydown", ctFunctionFirstKey);
63 | }else{
64 | window.detachEvent("mousedown", ctFunctionFirstKey);
65 | window.detachEvent("keydown", ctFunctionFirstKey);
66 | }
67 | }
68 |
69 | //Writing first key press timestamp
70 | var ctFunctionFirstKey = function output(event){
71 | var KeyTimestamp = Math.floor(new Date().getTime()/1000);
72 | ctSetCookie("ct_fkp_timestamp", KeyTimestamp);
73 | ctKeyStopStopListening();
74 | };
75 |
76 | if(typeof window.addEventListener == "function"){
77 | window.addEventListener("mousemove", ctFunctionMouseMove);
78 | window.addEventListener("mousedown", ctFunctionFirstKey);
79 | window.addEventListener("keydown", ctFunctionFirstKey);
80 | }else{
81 | window.attachEvent("onmousemove", ctFunctionMouseMove);
82 | window.attachEvent("mousedown", ctFunctionFirstKey);
83 | window.attachEvent("keydown", ctFunctionFirstKey);
84 | }
85 |
86 | }
87 | });
88 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Variables/Server.php:
--------------------------------------------------------------------------------
1 | server
27 | if (isset(static::$instance->variables[$name])) {
28 | return static::$instance->variables[$name];
29 | }
30 |
31 | $name = strtoupper($name);
32 |
33 | if ( isset($_SERVER[$name]) ) {
34 | $value = $this->getAndSanitize($_SERVER[$name]);
35 | } else {
36 | $value = '';
37 | }
38 |
39 | // Convert to upper case for REQUEST_METHOD
40 | if ($name === 'REQUEST_METHOD') {
41 | $value = strtoupper($value);
42 | }
43 |
44 | // Convert HTML chars for HTTP_USER_AGENT, HTTP_USER_AGENT, SERVER_NAME
45 | if (in_array($name, array('HTTP_USER_AGENT', 'HTTP_USER_AGENT', 'SERVER_NAME'))) {
46 | $value = htmlspecialchars($value);
47 | }
48 |
49 | // Remember for further calls
50 | static::getInstance()->rememberVariable($name, $value);
51 |
52 | return $value;
53 | }
54 |
55 | /**
56 | * Checks if $_SERVER['REQUEST_URI'] contains string
57 | *
58 | * @param string $needle
59 | *
60 | * @return bool
61 | * @psalm-suppress PossiblyUnusedMethod
62 | */
63 | public static function inUri($needle)
64 | {
65 | return self::hasString('REQUEST_URI', $needle);
66 | }
67 |
68 | /**
69 | * Is the host contains the string
70 | *
71 | * @param string $needle
72 | *
73 | * @return bool
74 | * @psalm-suppress PossiblyUnusedMethod
75 | */
76 | public static function inHost($needle)
77 | {
78 | return self::hasString('HTTP_HOST', $needle);
79 | }
80 |
81 | /**
82 | * Getting domain name
83 | *
84 | * @return false|string
85 | * @psalm-suppress PossiblyUnusedMethod
86 | */
87 | public static function getDomain()
88 | {
89 | preg_match('@\S+\.(\S+)\/?$@', self::get('HTTP_HOST'), $matches);
90 |
91 | return isset($matches[1]) ? $matches[1] : false;
92 | }
93 |
94 | /**
95 | * Checks if $_SERVER['REQUEST_URI'] contains string
96 | *
97 | * @param string $needle needle
98 | *
99 | * @return bool
100 | * @psalm-suppress PossiblyUnusedMethod
101 | */
102 | public static function inReferer($needle)
103 | {
104 | return self::hasString('HTTP_REFERER', $needle);
105 | }
106 |
107 | /**
108 | * Checks if the current request method is POST
109 | *
110 | * @return bool
111 | * @psalm-suppress PossiblyUnusedMethod
112 | */
113 | public static function isPost()
114 | {
115 | return self::get('REQUEST_METHOD') === 'POST';
116 | }
117 |
118 | /**
119 | * Checks if the current request method is GET
120 | *
121 | * @return bool
122 | * @psalm-suppress PossiblyUnusedMethod
123 | */
124 | public static function isGet()
125 | {
126 | return self::get('REQUEST_METHOD') === 'GET';
127 | }
128 |
129 | /**
130 | * Determines if SSL is used.
131 | *
132 | * @return bool True if SSL, otherwise false.
133 | * @psalm-suppress PossiblyUnusedMethod
134 | */
135 | public static function isSSL()
136 | {
137 | return self::get('HTTPS') === 'on' ||
138 | self::get('HTTPS') === '1' ||
139 | self::get('SERVER_PORT') == '443';
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Variables/ServerVariables.php:
--------------------------------------------------------------------------------
1 | getVariable($name);
41 |
42 | // Validate variable
43 | if ( $validation_filter && ! Validate::validate($variable, $validation_filter) ) {
44 | return false;
45 | }
46 |
47 | if ( $sanitize_filter ) {
48 | $variable = Sanitize::sanitize($variable, $sanitize_filter);
49 | }
50 |
51 | return $variable;
52 | }
53 |
54 | /**
55 | * BLUEPRINT
56 | * Gets given ${_SOMETHING} variable and save it to memory
57 | *
58 | * @param $name
59 | *
60 | * @return mixed|string
61 | */
62 | protected function getVariable($name){}
63 |
64 | /**
65 | * Save variable to $this->variables[]
66 | *
67 | * @param string $name
68 | * @param string $value
69 | */
70 | protected function rememberVariable($name, $value)
71 | {
72 | static::$instance->variables[$name] = $value;
73 | }
74 |
75 | /**
76 | * Checks if variable contains given string
77 | *
78 | * @param string $var Haystack to search in
79 | * @param string $string Needle to search
80 | *
81 | * @return bool
82 | */
83 | public static function hasString($var, $string)
84 | {
85 | return stripos(self::get($var), $string) !== false;
86 | }
87 |
88 | /**
89 | * Checks if variable equal to $param
90 | *
91 | * @param string $var Variable to compare
92 | * @param string $param Param to compare
93 | *
94 | * @return bool
95 | * @psalm-suppress PossiblyUnusedMethod
96 | */
97 | public static function equal($var, $param)
98 | {
99 | return self::get($var) === $param;
100 | }
101 |
102 | /**
103 | * @param $value
104 | * @param $nesting
105 | *
106 | * @return string|array
107 | */
108 | public function getAndSanitize($value, $nesting = 0)
109 | {
110 | if ( is_array($value) ) {
111 | foreach ( $value as $_key => & $val ) {
112 | if ( is_array($val) ) {
113 | if ( $nesting > 20 ) {
114 | return $value;
115 | }
116 | $this->getAndSanitize($val, ++$nesting);
117 | } else {
118 | $val = $this->sanitizeDefault($val);
119 | }
120 | }
121 | } else {
122 | $value = $this->sanitizeDefault($value);
123 | }
124 | return $value;
125 | }
126 |
127 | /**
128 | * Sanitize gathering data.
129 | * No sanitizing by default.
130 | * Override this method in the internal class!
131 | *
132 | * @param string $value
133 | *
134 | * @return string
135 | */
136 | protected function sanitizeDefault($value)
137 | {
138 | return $value;
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Antispam/CleantalkResponse.php:
--------------------------------------------------------------------------------
1 | errno = isset($obj->errno) ? $obj->errno : 0;
139 | $this->errstr = isset($obj->errstr) ? preg_replace("/.+(\*\*\*.+\*\*\*).+/", "$1", htmlspecialchars($obj->errstr)) : null;
140 |
141 | $this->stop_words = isset($obj->stop_words) ? Helper::fromUTF8($obj->stop_words, 'ISO-8859-1') : null;
142 | $this->comment = isset($obj->comment) ? strip_tags(Helper::fromUTF8($obj->comment, 'ISO-8859-1'), '
') : null;
143 | $this->blacklisted = isset($obj->blacklisted) ? $obj->blacklisted : null;
144 | $this->allow = isset($obj->allow) ? $obj->allow : 1;
145 | $this->id = isset($obj->id) ? $obj->id : null;
146 | $this->fast_submit = isset($obj->fast_submit) ? $obj->fast_submit : 0;
147 | $this->spam = isset($obj->spam) ? $obj->spam : 0;
148 | $this->js_disabled = isset($obj->js_disabled) ? $obj->js_disabled : 0;
149 | $this->sms_allow = isset($obj->sms_allow) ? $obj->sms_allow : null;
150 | $this->sms = isset($obj->sms) ? $obj->sms : null;
151 | $this->sms_error_code = isset($obj->sms_error_code) ? $obj->sms_error_code : null;
152 | $this->sms_error_text = isset($obj->sms_error_text) ? htmlspecialchars($obj->sms_error_text) : null;
153 | $this->stop_queue = isset($obj->stop_queue) ? $obj->stop_queue : 0;
154 | $this->inactive = isset($obj->inactive) ? $obj->inactive : 0;
155 | $this->account_status = isset($obj->account_status) ? $obj->account_status : -1;
156 | $this->received = isset($obj->received) ? $obj->received : -1;
157 | $this->codes = isset($obj->codes) ? explode(' ', $obj->codes) : array();
158 |
159 | if ( $this->errno !== 0 && $this->errstr !== null && $this->comment === null ) {
160 | $this->comment = '*** ' . $this->errstr . ' Anti-Spam service cleantalk.org ***';
161 | }
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Antispam/lock-page-ct-die.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
17 |
136 |
137 |
138 |
139 |
140 |
141 |
{MESSAGE_TITLE}
142 |
143 |
{MESSAGE}
144 |
145 | {BACK_LINK}
146 |
147 |
148 | {BACK_SCRIPT}
149 |
150 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Cleaner/Sanitize.php:
--------------------------------------------------------------------------------
1 | .*?<#i', '', $variable);
48 |
49 | return $variable === $variable_filtered
50 | ? htmlspecialchars($variable_filtered)
51 | : static::sanitize($variable_filtered, 'xss');
52 | }
53 |
54 | /**
55 | * Simple method: clean url
56 | */
57 | public static function cleanUrl($variable)
58 | {
59 | return preg_replace('#[^a-zA-Z0-9$\-_.+!*\'(),{}|\\^~\[\]`<>\#%";\/?:@&=.]#i', '', $variable);
60 | }
61 |
62 | /**
63 | * Simple method: clean word
64 | */
65 | public static function cleanWord($variable)
66 | {
67 | return preg_replace('#[^a-zA-Z0-9_.\-,]#', '', $variable);
68 | }
69 |
70 | /**
71 | * Simple method: clean int
72 | */
73 | public static function cleanInt($variable)
74 | {
75 | return preg_replace('#[^0-9.,]#', '', $variable);
76 | }
77 |
78 | /**
79 | * Simple method: clean email
80 | */
81 | public static function cleanEmail($variable)
82 | {
83 | // TODO
84 | return $variable;
85 | }
86 |
87 | /**
88 | * Simple method: clean file name
89 | */
90 | public static function cleanFileName($variable)
91 | {
92 | // TODO
93 | }
94 |
95 | /**
96 | * Simple method: clean hex color
97 | */
98 | public static function cleanHexColor($variable)
99 | {
100 | // TODO
101 | }
102 |
103 | /**
104 | * Simple method: clean hex color no hash
105 | */
106 | public static function cleanHexColorNoHash($variable)
107 | {
108 | // TODO
109 | }
110 |
111 | /**
112 | * Simple method: clean html class
113 | */
114 | public static function cleanHtmlClass($variable)
115 | {
116 | // TODO
117 | }
118 |
119 | /**
120 | * Simple method: clean key
121 | */
122 | public static function cleanKey($variable)
123 | {
124 | // TODO
125 | }
126 |
127 | /**
128 | * Simple method: clean meta
129 | */
130 | public static function cleanMeta($meta_key, $meta_value, $object_type)
131 | {
132 | // TODO
133 | }
134 |
135 | /**
136 | * Simple method: clean mime type
137 | */
138 | public static function cleanMimeType($variable)
139 | {
140 | // TODO
141 | }
142 |
143 | /**
144 | * Simple method: clean option
145 | */
146 | public static function cleanOption($option, $value)
147 | {
148 | // TODO
149 | }
150 |
151 | /**
152 | * Simple method: clean sql order by
153 | */
154 | public static function cleanSqlOrderBy($variable)
155 | {
156 | // TODO
157 | }
158 |
159 | /**
160 | * Simple method: clean text field
161 | */
162 | public static function cleanTextField($variable)
163 | {
164 | // TODO
165 | }
166 |
167 | /**
168 | * Simple method: clean textarea field
169 | */
170 | public static function cleanTextareaField($variable)
171 | {
172 | // TODO
173 | }
174 |
175 | /**
176 | * Simple method: clean title
177 | */
178 | public static function cleanTitle($variable)
179 | {
180 | // TODO
181 | }
182 |
183 | /**
184 | * Simple method: clean title for query
185 | */
186 | public static function cleanTitleForQuery($variable)
187 | {
188 | // TODO
189 | }
190 |
191 | /**
192 | * Simple method: clean title with dashes
193 | */
194 | public static function cleanTitleWithDashes($variable)
195 | {
196 | // TODO
197 | }
198 |
199 | /**
200 | * Simple method: clean user
201 | */
202 | public static function cleanUser($variable)
203 | {
204 | // TODO
205 | }
206 | }
207 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Antispam/CleantalkRequest.php:
--------------------------------------------------------------------------------
1 | sender_ip = isset($params['sender_ip']) ? (string)$params['sender_ip'] : null;
224 | $this->x_forwarded_for = isset($params['x_forwarded_for']) ? (string)$params['x_forwarded_for'] : null;
225 | $this->x_real_ip = isset($params['x_real_ip']) ? (string)$params['x_real_ip'] : null;
226 |
227 | // Misc
228 | $this->agent = isset($params['agent']) ? (string)$params['agent'] : null;
229 | $this->auth_key = isset($params['auth_key']) ? (string)$params['auth_key'] : null;
230 | $this->sender_email = isset($params['sender_email']) ? (string)$params['sender_email'] : null;
231 |
232 | // crunch for "PHP Notice: Array to string conversion". Error appears only on Gravity forms
233 | // @todo fix gat_fields_any
234 | if ( isset($params['sender_nickname']) && is_array($params['sender_nickname']) ) {
235 | $params['sender_nickname'] = current($params['sender_nickname']);
236 | }
237 |
238 | $this->page_url = !empty($params['page_url']) ? (string)$params['page_url'] : null;
239 | $this->referrer = !empty($params['referrer']) ? (string)$params['referrer'] : null;
240 | $this->sender_nickname = !empty($params['sender_nickname']) ? (string)$params['sender_nickname'] : null;
241 | $this->phone = !empty($params['phone']) ? (string)$params['phone'] : null;
242 | $this->js_on = isset($params['js_on']) ? (int)$params['js_on'] : null;
243 | $this->submit_time = isset($params['submit_time']) ? (int)$params['submit_time'] : null;
244 | $this->post_info = isset($params['post_info']) ? (string)json_encode($params['post_info']) : null;
245 | $this->sender_info = isset($params['sender_info']) ? (string)json_encode($params['sender_info']) : null;
246 | $this->honeypot_field = isset($params['honeypot_field']) ? (int)$params['honeypot_field'] : null;
247 | $this->exception_action = isset($params['exception_action']) ? (int)$params['exception_action'] : null;
248 |
249 | $this->event_token = isset($params['event_token']) ? (string)$params['event_token'] : null;
250 | $this->event_javascript_data = isset($params['event_javascript_data']) ? (string)$params['event_javascript_data'] : null;
251 | $this->browser_sign = isset($params['browser_sign']) ? (string)$params['browser_sign'] : null;
252 | $this->event_type = isset($params['event_type']) ? (string)$params['event_type'] : null;
253 | $this->message_to_log = isset($params['message_to_log']) ? (string)$params['message_to_log'] : null;
254 |
255 | $serializer = \Magento\Framework\App\ObjectManager::getInstance()
256 | ->get(\Magento\Framework\Serialize\Serializer\Serialize::class);
257 | $this->message = !empty($params['message'])
258 | ? (!is_scalar($params['message'])
259 | ? $serializer->serialize($params['message'])
260 | : $params['message'])
261 | : null;
262 | $this->example = !empty($params['example'])
263 | ? (!is_scalar($params['example'])
264 | ? $serializer->serialize($params['example'])
265 | : $params['example'])
266 | : null;
267 |
268 | // Feedback
269 | $this->feedback = !empty($params['feedback']) ? $params['feedback'] : null;
270 | }
271 | }
272 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Antispam/Cleantalk.php:
--------------------------------------------------------------------------------
1 | createMsg('check_message', $request);
113 |
114 | return $this->httpRequest($msg);
115 | }
116 |
117 | /**
118 | * Function checks whether it is possible to publish the message
119 | *
120 | * @param CleantalkRequest $request
121 | *
122 | * @return bool|CleantalkResponse
123 | */
124 | public function isAllowUser(CleantalkRequest $request)
125 | {
126 | $msg = $this->createMsg('check_newuser', $request);
127 |
128 | return $this->httpRequest($msg);
129 | }
130 |
131 | /**
132 | * Function sends the results of manual moderation
133 | *
134 | * @param CleantalkRequest $request
135 | *
136 | * @return bool|CleantalkResponse
137 | */
138 | public function sendFeedback(CleantalkRequest $request)
139 | {
140 | $msg = $this->createMsg('send_feedback', $request);
141 |
142 | return $this->httpRequest($msg);
143 | }
144 |
145 | /**
146 | * Create msg for cleantalk server
147 | *
148 | * @param string $method
149 | * @param CleantalkRequest $request
150 | *
151 | * @return CleantalkRequest
152 | */
153 | private function createMsg($method, CleantalkRequest $request)
154 | {
155 | switch ( $method ) {
156 | case 'check_message':
157 | // Convert strings to UTF8
158 | $request->message = Helper::toUTF8($request->message, $this->data_codepage);
159 | $request->example = Helper::toUTF8($request->example, $this->data_codepage);
160 | $request->sender_email = Helper::toUTF8($request->sender_email, $this->data_codepage);
161 | $request->sender_nickname = Helper::toUTF8($request->sender_nickname, $this->data_codepage);
162 | $request->message = $this->compressData($request->message);
163 | $request->example = $this->compressData($request->example);
164 | break;
165 |
166 | case 'check_newuser':
167 | // Convert strings to UTF8
168 | $request->sender_email = Helper::toUTF8($request->sender_email, $this->data_codepage);
169 | $request->sender_nickname = Helper::toUTF8($request->sender_nickname, $this->data_codepage);
170 | break;
171 |
172 | case 'send_feedback':
173 | if ( is_array($request->feedback) ) {
174 | $request->feedback = implode(';', $request->feedback);
175 | }
176 | break;
177 | }
178 |
179 | // Removing non UTF8 characters from request, because non UTF8 or malformed characters break json_encode().
180 | foreach ( $request as $param => $value ) {
181 | if ( is_array($request->$param) || is_string($request->$param) ) {
182 | $request->$param = Helper::removeNonUTF8($value);
183 | }
184 | }
185 |
186 | $request->method_name = $method;
187 | $request->message = is_array($request->message) ? json_encode($request->message) : $request->message;
188 |
189 | // Wiping cleantalk's headers but, not for send_feedback
190 | if ( $request->method_name !== 'send_feedback' ) {
191 | $ct_tmp = Helper::httpGetHeaders();
192 |
193 | if ( isset($ct_tmp['Cookie']) ) {
194 | $cookie_name = 'Cookie';
195 | } elseif ( isset($ct_tmp['cookie']) ) {
196 | $cookie_name = 'cookie';
197 | } else {
198 | $cookie_name = 'COOKIE';
199 | }
200 |
201 | if ( $ct_tmp ) {
202 | if ( isset($ct_tmp[$cookie_name]) ) {
203 | $ct_tmp[$cookie_name] = preg_replace(array(
204 | '/\s?ct_checkjs=[a-z0-9]*[^;]*;?/',
205 | '/\s?ct_timezone=.{0,1}\d{1,2}[^;]*;?/',
206 | '/\s?ct_pointer_data=.*5D[^;]*;?/',
207 | '/\s?apbct_timestamp=\d*[^;]*;?/',
208 | '/\s?apbct_site_landing_ts=\d*[^;]*;?/',
209 | '/\s?apbct_cookies_test=%7B.*%7D[^;]*;?/',
210 | '/\s?apbct_prev_referer=http.*?[^;]*;?/',
211 | '/\s?ct_ps_timestamp=.*?[^;]*;?/',
212 | '/\s?ct_fkp_timestamp=\d*?[^;]*;?/',
213 | '/\s?wordpress_ct_sfw_pass_key=\d*?[^;]*;?/',
214 | '/\s?apbct_page_hits=\d*?[^;]*;?/',
215 | '/\s?apbct_visible_fields_count=\d*?[^;]*;?/',
216 | '/\s?apbct_visible_fields=%7B.*%7D[^;]*;?/',
217 | '/\s?apbct_visible_fields_\d=%7B.*%7D[^;]*;?/',
218 | ), '', $ct_tmp[$cookie_name]);
219 | }
220 | $request->all_headers = json_encode($ct_tmp);
221 | }
222 | }
223 |
224 | return $request;
225 | }
226 |
227 | /**
228 | * Compress data and encode to base64
229 | *
230 | * @param string $data
231 | *
232 | * @return null|string
233 | */
234 | private function compressData($data = null)
235 | {
236 | if ( !is_string($data) ) {
237 | return $data;
238 | }
239 |
240 | if ( strlen($data) > $this->dataMaxSise && function_exists('\gzencode') && function_exists('base64_encode') ) {
241 | $localData = \gzencode($data, $this->compressRate, FORCE_GZIP);
242 |
243 | if ( $localData === false ) {
244 | return $data;
245 | }
246 |
247 | return base64_encode($localData);
248 | }
249 |
250 | return $data;
251 | }
252 |
253 | /**
254 | * httpRequest
255 | *
256 | * @param $msg
257 | *
258 | * @return CleantalkResponse
259 | */
260 | private function httpRequest($msg)
261 | {
262 | // Using current server without changing it
263 | $result = !empty($this->work_url) && $this->server_changed + 86400 > time()
264 | ? $this->sendRequest($msg, $this->work_url, $this->server_timeout)
265 | : false;
266 |
267 | // Changing server if no work_url or request has an error
268 | if ( $result === false || (is_object($result) && $result->errno != 0) ) {
269 | if ( !empty($this->work_url) ) {
270 | $this->downServers[] = $this->work_url;
271 | }
272 | $this->rotateModerate();
273 | $result = $this->sendRequest($msg, $this->work_url, $this->server_timeout);
274 | if ( $result !== false && $result->errno === 0 ) {
275 | $this->server_change = true;
276 | }
277 | }
278 | $response = new CleantalkResponse($result);
279 |
280 | if ( !empty($this->data_codepage) && $this->data_codepage !== 'UTF-8' ) {
281 | if ( !empty($response->comment) ) {
282 | $response->comment = Helper::fromUTF8($response->comment, $this->data_codepage);
283 | }
284 | if ( !empty($response->errstr) ) {
285 | $response->errstr = Helper::fromUTF8($response->errstr, $this->data_codepage);
286 | }
287 | if ( !empty($response->sms_error_text) ) {
288 | $response->sms_error_text = Helper::fromUTF8($response->sms_error_text, $this->data_codepage);
289 | }
290 | }
291 |
292 | return $response;
293 | }
294 |
295 | /**
296 | * * @todo Refactor / fix logic errors
297 | */
298 | public function rotateModerate()
299 | {
300 | // Split server url to parts
301 | preg_match("/^(https?:\/\/)([^\/:]+)(.*)/i", $this->server_url, $matches);
302 |
303 | $url_protocol = isset($matches[1]) ? $matches[1] : '';
304 | $url_host = isset($matches[2]) ? $matches[2] : '';
305 | $url_suffix = isset($matches[3]) ? $matches[3] : '';
306 |
307 | $servers = $this->getServersIp($url_host);
308 |
309 | if ( !$servers ) {
310 | return;
311 | }
312 |
313 | // Loop until find work server
314 | foreach ( $servers as $server ) {
315 | $dns = Helper::ipResolveCleantalks($server['ip']);
316 | if ( !$dns ) {
317 | continue;
318 | }
319 |
320 | $this->work_url = $url_protocol . $dns . $url_suffix;
321 |
322 | // Do not checking previous down server
323 | if ( !empty($this->downServers) && in_array($this->work_url, $this->downServers) ) {
324 | continue;
325 | }
326 |
327 | $this->server_ttl = $server['ttl'];
328 | $this->server_change = true;
329 | break;
330 | }
331 | }
332 |
333 | /**
334 | * @param $host
335 | * @return array|null
336 | * @todo Refactor / fix logic errors
337 | *
338 | * Function DNS request
339 | *
340 | * @psalm-suppress RedundantCondition
341 | */
342 | public function getServersIp($host)
343 | {
344 | if ( !isset($host) ) {
345 | return null;
346 | }
347 |
348 | $servers = array();
349 |
350 | // Get DNS records about URL
351 | if ( function_exists('dns_get_record') ) {
352 | $records = @dns_get_record($host, DNS_A);
353 | if ( $records !== false ) {
354 | foreach ( $records as $server ) {
355 | $servers[] = $server;
356 | }
357 | }
358 | }
359 |
360 | // Another try if first failed
361 | if ( count($servers) === 0 && function_exists('gethostbynamel') ) {
362 | $records = gethostbynamel($host);
363 | if ( $records !== false ) {
364 | foreach ( $records as $server ) {
365 | $servers[] = array(
366 | "ip" => $server,
367 | "host" => $host,
368 | "ttl" => $this->server_ttl
369 | );
370 | }
371 | }
372 | }
373 |
374 | // If couldn't get records
375 | if ( count($servers) === 0 ) {
376 | $servers[] = array(
377 | "ip" => null,
378 | "host" => $host,
379 | "ttl" => $this->server_ttl
380 | );
381 | // If records received
382 | } else {
383 | $tmp = array();
384 | $fast_server_found = false;
385 |
386 | foreach ( $servers as $server ) {
387 | if ( $fast_server_found ) {
388 | $ping = $this->max_server_timeout;
389 | } else {
390 | $ping = $this->httpPing($server['ip']);
391 | $ping *= 1000;
392 | }
393 |
394 | $tmp[(int)$ping] = $server;
395 |
396 | $fast_server_found = $ping < $this->min_server_timeout;
397 | }
398 |
399 | if ( count($tmp) ) {
400 | ksort($tmp);
401 | $response = $tmp;
402 | }
403 | }
404 |
405 | return empty($response) ? null : $response;
406 | }
407 |
408 | /**
409 | * Function to check response time
410 | *
411 | * @param string $host
412 | *
413 | * @return float|int
414 | */
415 | public function httpPing($host)
416 | {
417 | // Skip localhost ping cause it raise error at fsockopen.
418 | // And return minimum value
419 | if ( $host === 'localhost' ) {
420 | return 0.001;
421 | }
422 |
423 | $starttime = microtime(true);
424 | $file = @fsockopen($host, 443, $errno, $errstr, $this->max_server_timeout / 1000);
425 | $stoptime = microtime(true);
426 |
427 | if ( !$file ) {
428 | $status = $this->max_server_timeout / 1000; // Site is down
429 | } else {
430 | fclose($file);
431 | $status = ($stoptime - $starttime);
432 | $status = round($status, 4);
433 | }
434 |
435 | return $status;
436 | }
437 |
438 | /**
439 | * Send JSON request to servers
440 | *
441 | * @param string|array $data
442 | * @param string $url
443 | * @param int $server_timeout
444 | *
445 | * @return boolean|CleantalkResponse
446 | */
447 | private function sendRequest($data, $url, $server_timeout = 3)
448 | {
449 | //Cleaning from 'null' values
450 | $tmp_data = array();
451 | foreach ( $data as $key => $value ) {
452 | if ( $value !== null ) {
453 | $tmp_data[$key] = $value;
454 | }
455 | }
456 | $data = $tmp_data;
457 | unset($key, $value, $tmp_data);
458 |
459 | $js_on = ( isset($data['js_on']) && (int)$data['js_on'] === 1 ) ||
460 | ( isset($data['event_token']) && Validate::isHash($data['event_token']) );
461 |
462 | // Convert to JSON
463 | $data = json_encode($data);
464 |
465 | if ( isset($this->api_version) ) {
466 | $url .= $this->api_version;
467 | }
468 |
469 | /** @var \Cleantalk\Common\Http\Request $request_class */
470 | $request_class = Mloader::get('Http\Request');
471 | $http = new $request_class();
472 |
473 | $result = $http->setUrl($url)
474 | ->setData($data)
475 | ->setOptions(['timeout' => $server_timeout])
476 | ->request();
477 |
478 | $errstr = null;
479 | $response = is_string($result) ? json_decode($result) : false;
480 | if ( $result !== false && is_object($response) ) {
481 | $response->errno = 0;
482 | $response->errstr = $errstr;
483 | } else {
484 | if ( isset($result['error']) ) {
485 | $error = $result['error'];
486 | } else {
487 | if ( is_string($result) ) {
488 | $error = $result;
489 | } else {
490 | $error = '';
491 | }
492 | }
493 |
494 | $errstr = 'Unknown response from ' . $url . ': ' . $error;
495 |
496 | $response = null;
497 | $response['errno'] = 1;
498 | $response['errstr'] = $errstr;
499 |
500 | if ( ! $js_on ) {
501 | $response['allow'] = 0;
502 | $response['spam'] = '1';
503 | $response['comment'] = sprintf(
504 | 'We\'ve got an issue: %s. Forbidden. Please, enable Javascript.',
505 | $errstr
506 | );
507 | }
508 | $response = json_decode(json_encode($response));
509 | }
510 |
511 | return $response;
512 | }
513 |
514 | /**
515 | * Call check_bot API method
516 | *
517 | * Make a decision if it's bot or not based on limited input JavaScript data
518 | *
519 | * @param CleantalkRequest $request
520 | *
521 | * @return CleantalkResponse
522 | */
523 | public function checkBot(CleantalkRequest $request)
524 | {
525 | $msg = $this->createMsg('check_bot', $request);
526 |
527 | return $this->httpRequest($msg);
528 | }
529 |
530 | public static function getLockPageFile()
531 | {
532 | return __DIR__ . '/lock-page-ct-die.html';
533 | }
534 | }
535 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/view/frontend/web/js/ct_external_forms.js:
--------------------------------------------------------------------------------
1 | define(['jquery'], function ($) {
2 | 'use strict';
3 |
4 | /**
5 | * @param {Object} config
6 | */
7 | return function (config) {
8 |
9 | /**
10 | * Handle external forms
11 | */
12 | function ctProtectExternal() {
13 | clearInterval(dynamicRenderedFormInterval);
14 | console.log('ctProtectExternal');
15 | for (let i = 0; i < document.forms.length; i++) {
16 | if (document.forms[i].cleantalk_hidden_action === undefined &&
17 | document.forms[i].cleantalk_hidden_method === undefined) {
18 | // current form
19 | const currentForm = document.forms[i];
20 |
21 | if (typeof(currentForm.action) == 'string') {
22 |
23 | // Ajax checking for the integrated forms
24 | if ( isIntegratedForm(currentForm) ) {
25 | console.log('isIntegratedForm');
26 | apbctProcessExternalForm(currentForm, i, document);
27 |
28 | // Common flow - modify form's action
29 | } else if (currentForm.action.indexOf('http://') !== -1 ||
30 | currentForm.action.indexOf('https://') !== -1) {
31 | console.log('currentForm.action.indexOf');
32 | let tmp = currentForm.action.split('//');
33 | tmp = tmp[1].split('/');
34 | const host = tmp[0].toLowerCase();
35 |
36 | if (host !== location.hostname.toLowerCase()) {
37 | const ctAction = document.createElement('input');
38 | ctAction.name = 'cleantalk_hidden_action';
39 | ctAction.value = currentForm.action;
40 | ctAction.type = 'hidden';
41 | currentForm.appendChild(ctAction);
42 |
43 | const ctMethod = document.createElement('input');
44 | ctMethod.name = 'cleantalk_hidden_method';
45 | ctMethod.value = currentForm.method;
46 | ctMethod.type = 'hidden';
47 |
48 | currentForm.method = 'POST';
49 |
50 | currentForm.appendChild(ctMethod);
51 |
52 | currentForm.action = document.location;
53 | }
54 | }
55 | }
56 | }
57 | }
58 | }
59 |
60 | window.onload = function() {
61 | console.log('window.onload');
62 | console.log(config);
63 | if ( ! +config.externalForms ) {
64 | return;
65 | }
66 |
67 | setTimeout(function() {
68 | ctProtectExternal();
69 | catchDynamicRenderedForm();
70 | }, 1500);
71 | };
72 |
73 | let dynamicRenderedFormInterval = null;
74 |
75 | /**
76 | * Catching dynamic rendered forms
77 | *
78 | * @return {void}
79 | */
80 | function catchDynamicRenderedForm() {
81 | if (isIntegratedDynamicFormOnPage()) {
82 | dynamicRenderedFormInterval = setInterval(function() {
83 | ctProtectExternal();
84 | }, 1000);
85 | }
86 | }
87 |
88 | /**
89 | * Checking the dynamic rendered forms
90 | *
91 | * @return {boolean}
92 | */
93 | function isIntegratedDynamicFormOnPage() {
94 | let result = false;
95 |
96 | document.querySelectorAll('script[src]').forEach(el => {
97 | if (el.src.includes('ctctcdn.com')) result = true;
98 | });
99 |
100 | return result;
101 | }
102 |
103 | /**
104 | * Checking the form integration
105 | * @param {HTMLElement} formObj
106 | * @return {boolean}
107 | */
108 | function isIntegratedForm(formObj) {
109 | const formId = formObj.getAttribute('id') !== null ? formObj.getAttribute('id') : '';
110 | if (
111 | formId.indexOf('ctct_form_') !== -1
112 | ) {
113 | return true;
114 | }
115 | return false;
116 | }
117 |
118 | /**
119 | * Process external forms
120 | * @param {HTMLElement} currentForm
121 | * @param {int} iterator
122 | * @param {HTMLElement} documentObject
123 | */
124 | function apbctProcessExternalForm(currentForm, iterator, documentObject) {
125 | console.log('apbctProcessExternalForm');
126 | const cleantalkPlaceholder = document.createElement('i');
127 | cleantalkPlaceholder.className = 'cleantalk_placeholder';
128 | cleantalkPlaceholder.style = 'display: none';
129 |
130 | currentForm.parentElement.insertBefore(cleantalkPlaceholder, currentForm);
131 |
132 | // Deleting form to prevent submit event
133 | const prev = currentForm.previousSibling;
134 | const formHtml = currentForm.outerHTML;
135 | const formOriginal = currentForm;
136 |
137 | // Remove the original form
138 | currentForm.parentElement.removeChild(currentForm);
139 |
140 | // Insert a clone
141 | const placeholder = document.createElement('div');
142 | placeholder.innerHTML = formHtml;
143 | prev.after(placeholder.firstElementChild);
144 |
145 | const forceAction = document.createElement('input');
146 | forceAction.name = 'action';
147 | forceAction.value = 'cleantalk_force_ajax_check';
148 | forceAction.type = 'hidden';
149 |
150 | const reUseCurrentForm = documentObject.forms[iterator];
151 |
152 | reUseCurrentForm.appendChild(forceAction);
153 | reUseCurrentForm.apbctPrev = prev;
154 | reUseCurrentForm.apbctFormOriginal = formOriginal;
155 |
156 | documentObject.forms[iterator].onsubmit = function(event) {
157 | event.preventDefault();
158 | console.log('send');
159 | sendAjaxCheckingFormData(event.currentTarget);
160 | };
161 | }
162 |
163 | /**
164 | * Sending Ajax for checking form data
165 | * @param {HTMLElement} form
166 | */
167 | function sendAjaxCheckingFormData(form) {
168 | const data = {};
169 | let elems = form.elements;
170 | elems = Array.prototype.slice.call(elems);
171 |
172 | elems.forEach( function( elem, y ) {
173 | if ( elem.name === '' ) {
174 | data['input_' + y] = elem.value;
175 | } else {
176 | data[elem.name] = elem.value;
177 | }
178 | });
179 |
180 | $.ajax({
181 | url: config.ajaxUrl,
182 | type: 'POST',
183 | data: data,
184 | complete: function(response) {
185 | if ( result.apbct === undefined || ! +result.apbct.blocked ) {
186 | const formNew = form;
187 | form.parentElement.removeChild(form);
188 | const prev = form.apbctPrev;
189 | const formOriginal = form.apbctFormOriginal;
190 | let mauticIntegration = false;
191 |
192 | apbctReplaceInputsValuesFromOtherForm(formNew, formOriginal);
193 |
194 | // mautic forms integration
195 | if (formOriginal.id.indexOf('mautic') !== -1) {
196 | mauticIntegration = true;
197 | }
198 |
199 | prev.after( formOriginal );
200 |
201 | // Clear visible_fields input
202 | for (const el of formOriginal.querySelectorAll('input[name="apbct_visible_fields"]')) {
203 | el.remove();
204 | }
205 |
206 | for (const el of formOriginal.querySelectorAll('input[value="cleantalk_force_ajax_check"]')) {
207 | el.remove();
208 | }
209 |
210 | // Common click event
211 | let submButton = formOriginal.querySelectorAll('button[type=submit]');
212 | if ( submButton.length !== 0 ) {
213 | submButton[0].click();
214 | if (mauticIntegration) {
215 | setTimeout(function() {
216 | ctProtectExternal();
217 | }, 1500);
218 | }
219 | return;
220 | }
221 |
222 | submButton = formOriginal.querySelectorAll('input[type=submit]');
223 | if ( submButton.length !== 0 ) {
224 | submButton[0].click();
225 | return;
226 | }
227 |
228 | // ConvertKit direct integration
229 | submButton = formOriginal.querySelectorAll('button[data-element="submit"]');
230 | if ( submButton.length !== 0 ) {
231 | submButton[0].click();
232 | return;
233 | }
234 |
235 | // Paypal integration
236 | submButton = formOriginal.querySelectorAll('input[type="image"][name="submit"]');
237 | if ( submButton.length !== 0 ) {
238 | submButton[0].click();
239 | }
240 | }
241 | if (result.apbct !== undefined && +result.apbct.blocked) {
242 | ctParseBlockMessage(result);
243 | }
244 | },
245 | error: function (xhr, status, errorThrown) {
246 | console.log('Error happens. Try again.');
247 | }
248 | });
249 | }
250 |
251 | function ctParseBlockMessage(response) {
252 | if (typeof response.apbct !== 'undefined') {
253 | response = response.apbct;
254 | if (response.blocked) {
255 | document.dispatchEvent(
256 | new CustomEvent( 'apbctAjaxBockAlert', {
257 | bubbles: true,
258 | detail: {message: response.comment},
259 | } ),
260 | );
261 |
262 | // Show the result by modal
263 | cleantalkModal.loaded = response.comment;
264 | cleantalkModal.open();
265 |
266 | if (+response.stop_script === 1) {
267 | window.stop();
268 | }
269 | }
270 | }
271 | }
272 |
273 | /* Cleantalk Modal object */
274 | let cleantalkModal = {
275 |
276 | // Flags
277 | loaded: false,
278 | loading: false,
279 | opened: false,
280 | opening: false,
281 |
282 | // Methods
283 | load: function( action ) {
284 | if ( ! this.loaded ) {
285 | this.loading = true;
286 | let callback = function( result, data, params, obj ) {
287 | cleantalkModal.loading = false;
288 | cleantalkModal.loaded = result;
289 | document.dispatchEvent(
290 | new CustomEvent( 'cleantalkModalContentLoaded', {
291 | bubbles: true,
292 | } ),
293 | );
294 | };
295 | // eslint-disable-next-line camelcase
296 | if ( typeof apbct_admin_sendAJAX === 'function' ) {
297 | apbct_admin_sendAJAX( {'action': action}, {'callback': callback, 'notJson': true} );
298 | } else {
299 | apbct_public_sendAJAX( {'action': action}, {'callback': callback, 'notJson': true} );
300 | }
301 | }
302 | },
303 |
304 | open: function() {
305 | /* Cleantalk Modal CSS start */
306 | let renderCss = function() {
307 | let cssStr = '';
308 | // eslint-disable-next-line guard-for-in
309 | for ( const key in this.styles ) {
310 | cssStr += key + ':' + this.styles[key] + ';';
311 | }
312 | return cssStr;
313 | };
314 | let overlayCss = {
315 | styles: {
316 | 'z-index': '9999999999',
317 | 'position': 'fixed',
318 | 'top': '0',
319 | 'left': '0',
320 | 'width': '100%',
321 | 'height': '100%',
322 | 'background': 'rgba(0,0,0,0.5)',
323 | 'display': 'flex',
324 | 'justify-content': 'center',
325 | 'align-items': 'center',
326 | },
327 | toString: renderCss,
328 | };
329 | let innerCss = {
330 | styles: {
331 | 'position': 'relative',
332 | 'padding': '30px',
333 | 'background': '#FFF',
334 | 'border': '1px solid rgba(0,0,0,0.75)',
335 | 'border-radius': '4px',
336 | 'box-shadow': '7px 7px 5px 0px rgba(50,50,50,0.75)',
337 | },
338 | toString: renderCss,
339 | };
340 | let closeCss = {
341 | styles: {
342 | 'position': 'absolute',
343 | 'background': '#FFF',
344 | 'width': '20px',
345 | 'height': '20px',
346 | 'border': '2px solid rgba(0,0,0,0.75)',
347 | 'border-radius': '15px',
348 | 'cursor': 'pointer',
349 | 'top': '-8px',
350 | 'right': '-8px',
351 | 'box-sizing': 'content-box',
352 | },
353 | toString: renderCss,
354 | };
355 | let closeCssBefore = {
356 | styles: {
357 | 'content': '""',
358 | 'display': 'block',
359 | 'position': 'absolute',
360 | 'background': '#000',
361 | 'border-radius': '1px',
362 | 'width': '2px',
363 | 'height': '16px',
364 | 'top': '2px',
365 | 'left': '9px',
366 | 'transform': 'rotate(45deg)',
367 | },
368 | toString: renderCss,
369 | };
370 | let closeCssAfter = {
371 | styles: {
372 | 'content': '""',
373 | 'display': 'block',
374 | 'position': 'absolute',
375 | 'background': '#000',
376 | 'border-radius': '1px',
377 | 'width': '2px',
378 | 'height': '16px',
379 | 'top': '2px',
380 | 'left': '9px',
381 | 'transform': 'rotate(-45deg)',
382 | },
383 | toString: renderCss,
384 | };
385 | let bodyCss = {
386 | styles: {
387 | 'overflow': 'hidden',
388 | },
389 | toString: renderCss,
390 | };
391 | let cleantalkModalStyle = document.createElement( 'style' );
392 | cleantalkModalStyle.setAttribute( 'id', 'cleantalk-modal-styles' );
393 | cleantalkModalStyle.innerHTML = 'body.cleantalk-modal-opened{' + bodyCss + '}';
394 | cleantalkModalStyle.innerHTML += '#cleantalk-modal-overlay{' + overlayCss + '}';
395 | cleantalkModalStyle.innerHTML += '#cleantalk-modal-close{' + closeCss + '}';
396 | cleantalkModalStyle.innerHTML += '#cleantalk-modal-close:before{' + closeCssBefore + '}';
397 | cleantalkModalStyle.innerHTML += '#cleantalk-modal-close:after{' + closeCssAfter + '}';
398 | document.body.append( cleantalkModalStyle );
399 | /* Cleantalk Modal CSS end */
400 |
401 | let overlay = document.createElement( 'div' );
402 | overlay.setAttribute( 'id', 'cleantalk-modal-overlay' );
403 | document.body.append( overlay );
404 |
405 | document.body.classList.add( 'cleantalk-modal-opened' );
406 |
407 | let inner = document.createElement( 'div' );
408 | inner.setAttribute( 'id', 'cleantalk-modal-inner' );
409 | inner.setAttribute( 'style', innerCss );
410 | overlay.append( inner );
411 |
412 | let close = document.createElement( 'div' );
413 | close.setAttribute( 'id', 'cleantalk-modal-close' );
414 | inner.append( close );
415 |
416 | let content = document.createElement( 'div' );
417 | if ( this.loaded ) {
418 | const urlRegex = /(https?:\/\/[^\s]+)/g;
419 | const serviceContentRegex = /.*\/inc/g;
420 | if (serviceContentRegex.test(this.loaded)) {
421 | content.innerHTML = this.loaded;
422 | } else {
423 | content.innerHTML = this.loaded.replace(urlRegex, '$1');
424 | }
425 | } else {
426 | content.innerHTML = 'Loading...';
427 | // @ToDo Here is hardcoded parameter. Have to get this from a 'data-' attribute.
428 | this.load( 'get_options_template' );
429 | }
430 | content.setAttribute( 'id', 'cleantalk-modal-content' );
431 | inner.append( content );
432 |
433 | this.opened = true;
434 | },
435 |
436 | close: function() {
437 | document.body.classList.remove( 'cleantalk-modal-opened' );
438 | document.getElementById( 'cleantalk-modal-overlay' ).remove();
439 | document.getElementById( 'cleantalk-modal-styles' ).remove();
440 | document.dispatchEvent(
441 | new CustomEvent( 'cleantalkModalClosed', {
442 | bubbles: true,
443 | } ),
444 | );
445 | },
446 |
447 | };
448 |
449 | /* Cleantalk Modal helpers */
450 | document.addEventListener('click', function( e ) {
451 | if ( e.target && (e.target.id === 'cleantalk-modal-overlay' || e.target.id === 'cleantalk-modal-close') ) {
452 | cleantalkModal.close();
453 | }
454 | });
455 | document.addEventListener('cleantalkModalContentLoaded', function( e ) {
456 | if ( cleantalkModal.opened && cleantalkModal.loaded ) {
457 | document.getElementById( 'cleantalk-modal-content' ).innerHTML = cleantalkModal.loaded;
458 | }
459 | });
460 | }
461 | });
462 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/lib/Cleantalk/Common/Http/Request.php:
--------------------------------------------------------------------------------
1 | $url,
53 | * CURLOPT_TIMEOUT => 15,
54 | * CURLOPT_LOW_SPEED_TIME => 10,
55 | * CURLOPT_RETURNTRANSFER => true,
56 | * )
57 | */
58 | protected $options = [];
59 |
60 | /**
61 | * @var array [callable] Callback function to process after the request is performed without error to process received data
62 | * If passed will be fired for both single and multi requests
63 | */
64 | protected $callbacks = [];
65 |
66 | /**
67 | * @var Response|array
68 | */
69 | public $response;
70 |
71 | /**
72 | * @param mixed $url
73 | *
74 | * @return Request
75 | */
76 | public function setUrl($url)
77 | {
78 | $this->url = $url;
79 |
80 | return $this;
81 | }
82 |
83 | /**
84 | * @param mixed $data
85 | *
86 | * @return Request
87 | */
88 | public function setData($data)
89 | {
90 | // If $data scalar converting it to array
91 | $this->data = ! empty($data) && ! self::isJson($data) && is_scalar($data)
92 | ? array((string)$data => 1)
93 | : $data;
94 |
95 | return $this;
96 | }
97 |
98 | /**
99 | * Set one or more presets which change the way of the processing Request::request
100 | *
101 | * @param mixed $presets Array with presets
102 | * Example: array('get_code', 'async')
103 | * Or space separated string with presets
104 | * Example: 'get_code async get'
105 | *
106 | * May use the following presets(combining is possible):
107 | * dont_follow_redirects - ignore 300-family response code and don't follow redirects
108 | * get_code - getting only HTTP response code
109 | * async - async requests. Sends request and return 'true' value. Doesn't wait for response.
110 | * get - makes GET-type request instead of default POST-type
111 | * ssl - uses SSL
112 | * cache - allow caching for this request
113 | * retry_with_socket - make another request with socket if cURL failed to retrieve data
114 | *
115 | * @return Request
116 | */
117 | public function setPresets($presets)
118 | {
119 | // Prepare $presets to process
120 | $this->presets = ! is_array($presets)
121 | ? explode(' ', $presets)
122 | : $presets;
123 |
124 | return $this;
125 | }
126 |
127 | /**
128 | * @param mixed $options
129 | *
130 | * @return Request
131 | */
132 | public function setOptions($options)
133 | {
134 | $this->options = $options;
135 |
136 | return $this;
137 | }
138 |
139 | /**
140 | * Set callback and additional arguments which will be passed to callback function
141 | *
142 | * @param callable $callback
143 | * @param array $arguments
144 | * @param int $priority
145 | * @param bool $pass_response
146 | *
147 | * @return Request
148 | * @psalm-suppress UnusedVariable
149 | */
150 | public function addCallback($callback, $arguments = array(), $priority = null, $pass_response = false)
151 | {
152 | $priority = $priority ?: 100;
153 | if ( isset($this->callbacks[$priority]) ) {
154 | return $this->addCallback($callback, $arguments, ++$priority);
155 | }
156 |
157 | $this->callbacks[$priority] = [
158 | 'function' => $callback,
159 | 'arguments' => $arguments,
160 | 'pass_response' => $pass_response,
161 | ];
162 |
163 | return $this;
164 | }
165 |
166 | /**
167 | * Function sends raw http request
168 | *
169 | * @return array|bool (array || array('error' => true))
170 | */
171 | public function request()
172 | {
173 | // Return the error if cURL is not installed
174 | if ( ! function_exists('curl_init') ) {
175 | return array('error' => 'CURL_NOT_INSTALLED');
176 | }
177 |
178 | if ( empty($this->url) ) {
179 | return array('error' => 'URL_IS_NOT_SET');
180 | }
181 |
182 | $this->convertOptionsTocURLFormat();
183 | $this->appendOptionsObligatory();
184 | $this->processPresets();
185 |
186 | // Call cURL multi request if many URLs passed
187 | $this->response = is_array($this->url)
188 | ? $this->requestMulti()
189 | : $this->requestSingle();
190 |
191 | // Process the error. Unavailable for multiple URLs.
192 | if (
193 | ! is_array($this->url) &&
194 | $this->response->getError() &&
195 | in_array('retry_with_socket', $this->presets, true)
196 | ) {
197 | $this->response = $this->requestWithSocket();
198 | if ( $this->response->getError() ) {
199 | return $this->response->getError();
200 | }
201 | }
202 |
203 | return $this->runCallbacks();
204 | }
205 |
206 | /**
207 | * @return Response
208 | */
209 | protected function requestSingle()
210 | {
211 | // Make a request
212 | $ch = curl_init();
213 |
214 | curl_setopt_array($ch, $this->options);
215 |
216 | $request_result = curl_exec($ch); // Gather request result
217 | $curl_info = curl_getinfo($ch); // Gather HTTP response information
218 |
219 | // Do not catch timeout error for async requests.
220 | if( in_array('async', $this->presets, true) ){
221 | $request_result = true;
222 | }
223 |
224 | if ( $request_result === false ) {
225 | $request_result = array('error' => curl_error($ch));
226 | }
227 |
228 | curl_close($ch);
229 |
230 |
231 | return new Response($request_result, $curl_info);
232 | }
233 |
234 |
235 | /**
236 | * Do multi curl requests without processing it.
237 | *
238 | * @return array
239 | */
240 | protected function requestMulti()
241 | {
242 | $urls_count = count($this->url);
243 | $curl_arr = array();
244 | $mh = curl_multi_init();
245 | $this->response = [];
246 |
247 | for ( $i = 0; $i < $urls_count; $i++ ) {
248 | $this->options[CURLOPT_URL] = $this->url[$i];
249 | $curl_arr[$i] = curl_init($this->url[$i]);
250 |
251 | curl_setopt_array($curl_arr[$i], $this->options);
252 | curl_multi_add_handle($mh, $curl_arr[$i]);
253 | }
254 |
255 | do {
256 | curl_multi_exec($mh, $running);
257 | usleep(1000);
258 | } while ( $running > 0 );
259 |
260 | for ( $i = 0; $i < $urls_count; $i++ ) {
261 | $curl_info = curl_getinfo($curl_arr[$i]); // Gather HTTP response information
262 | $received_data = curl_multi_getcontent($curl_arr[$i]);
263 |
264 | // Do not catch timeout error for async requests.
265 | if( in_array('async', $this->presets, true) ){
266 | $received_data = true;
267 | }
268 |
269 | if ( $received_data === '' ) {
270 | $received_data = array('error' => curl_error($curl_arr[$i]));
271 | }
272 |
273 | $this->response[$this->url[$i]] = new Response($received_data, $curl_info);
274 | }
275 |
276 | return $this->response;
277 | }
278 |
279 | /**
280 | * Make a request with socket, exactly with file_get_contents()
281 | *
282 | * @return Response
283 | */
284 | private function requestWithSocket()
285 | {
286 | if ( ! ini_get('allow_url_fopen') ) {
287 | return new Response(['error' => 'ALLOW_URL_FOPEN_IS_DISABLED'], []);
288 | }
289 |
290 | $context = stream_context_create(
291 | [
292 | 'http' => [
293 | 'method' => 'GET', //in_array('get', $this->presets, true) ? 'GET' : 'POST',
294 | 'timeout' => $this->options[CURLOPT_TIMEOUT],
295 | 'content' => $this->data,
296 | ],
297 | ]
298 | );
299 |
300 | $response_content = @file_get_contents($this->url, false, $context)
301 | ?: ['error' => 'FAILED_TO_USE_FILE_GET_CONTENTS'];
302 |
303 | return new Response($response_content, []);
304 | }
305 |
306 | // Process with callback if passed. Save the processed result.
307 | protected function runCallbacks()
308 | {
309 | $return_value = [];
310 |
311 | // Cast to array to precess result from $this->requestSingle as $this->requestMulti results
312 | $responses = is_object($this->response)
313 | ? [$this->response]
314 | : $this->response;
315 |
316 | // Sort callback to keep the priority order
317 | ksort($this->callbacks);
318 |
319 | foreach ( $responses as $url => &$response ) {
320 | // Skip the processing if the error occurred in this specific result
321 | if ( $response->getError() ) {
322 | $return_value[] = $response->getError();
323 | continue;
324 | }
325 |
326 | // Get content to process
327 | $content = $response->getContentProcessed();
328 |
329 | // Perform all provided callback functions to each request result
330 | if ( ! empty($this->callbacks) ) {
331 | foreach ( $this->callbacks as $callback ) {
332 | if ( is_callable($callback['function']) ) {
333 | // Run callback
334 | $content = call_user_func_array(
335 | $callback['function'],
336 | array_merge(
337 | array(
338 | $callback['pass_response'] ? $response : $content, // Pass Response or content
339 | $url
340 | ),
341 | $callback['arguments']
342 | )
343 | );
344 |
345 | // Foolproof
346 | if ( ! $content instanceof Response ) {
347 | $response->setProcessed($content);
348 | }
349 | }
350 | }
351 | }
352 |
353 | $return_value[$url] = $content instanceof Response ? $content->getContentProcessed() : $content;
354 | }
355 | unset($response);
356 |
357 | // Return a single content if it was a single request
358 | return is_array($this->response) && count($this->response) > 1
359 | ? $return_value
360 | : reset($return_value);
361 | }
362 |
363 | /**
364 | * Convert given options from simple naming like 'timeout' or 'ssl'
365 | * to sophisticated and standardized cURL defined constants
366 | *
367 | * !! Called only after we make sure that cURL is exists !!
368 | */
369 | private function convertOptionsTocURLFormat()
370 | {
371 | $temp_options = [];
372 | foreach ( $this->options as $option_name => &$option_value ) {
373 | switch ( $option_name ) {
374 | case 'timeout':
375 | $temp_options[CURLOPT_TIMEOUT] = $option_value; // String
376 | unset($this->options[$option_name]);
377 | break;
378 | case 'sslverify':
379 | if ( $option_value ) {
380 | $temp_options[CURLOPT_SSL_VERIFYPEER] = (bool)$option_value; // Boolean
381 | $temp_options[CURLOPT_SSL_VERIFYHOST] = (int)(bool)$option_value; // Int 0|1
382 | unset($this->options[$option_name]);
383 | }
384 | break;
385 | case 'sslcertificates':
386 | $temp_options[CURLOPT_CAINFO] = $option_name; // String
387 | unset($this->options[$option_name]);
388 | break;
389 | case 'headers':
390 | $temp_options[CURLOPT_HTTPHEADER] = $option_name; // String[]
391 | unset($this->options[$option_name]);
392 | break;
393 | case 'user-agent':
394 | $temp_options[CURLOPT_USERAGENT] = $option_name; // String
395 | unset($this->options[$option_name]);
396 | break;
397 |
398 | // Unset unsupported string names in options
399 | default:
400 | if ( ! is_int($option_name) ) {
401 | unset($this->options[$option_name]);
402 | }
403 | break;
404 | }
405 | }
406 | unset($option_value);
407 |
408 | $this->options = array_replace($this->options, $temp_options);
409 | }
410 |
411 | /**
412 | * Set default options to make a request
413 | */
414 | protected function appendOptionsObligatory()
415 | {
416 | // Merging OBLIGATORY options with GIVEN options
417 | $this->options = array_replace(
418 | array(
419 | CURLOPT_URL => ! is_array($this->url) ? $this->url : null,
420 | CURLOPT_TIMEOUT => 10,
421 | CURLOPT_LOW_SPEED_TIME => 7,
422 | CURLOPT_RETURNTRANSFER => true,
423 | CURLOPT_CONNECTTIMEOUT => 5000,
424 | CURLOPT_FORBID_REUSE => true,
425 | CURLOPT_USERAGENT => self::AGENT,
426 | CURLOPT_POST => true,
427 | CURLOPT_POSTFIELDS => $this->data,
428 | CURLOPT_SSL_VERIFYPEER => false,
429 | CURLOPT_SSL_VERIFYHOST => 0,
430 | CURLOPT_HTTPHEADER => array(
431 | 'Expect:',
432 | // Fix for large data and old servers http://php.net/manual/ru/function.curl-setopt.php#82418
433 | 'Expires: ' . date(DATE_RFC822, mktime(0, 0, 0, 1, 1, 1971)),
434 | 'Cache-Control: no-store, no-cache, must-revalidate',
435 | 'Cache-Control: post-check=0, pre-check=0',
436 | 'Pragma: no-cache',
437 | ),
438 | CURLOPT_FOLLOWLOCATION => true,
439 | CURLOPT_MAXREDIRS => 5,
440 | ),
441 | $this->options
442 | );
443 | }
444 |
445 | /**
446 | * Append options considering passed presets
447 | */
448 | protected function processPresets()
449 | {
450 | foreach ( $this->presets as $preset ) {
451 | switch ( $preset ) {
452 | // Do not follow redirects
453 | case 'dont_follow_redirects':
454 | $this->options[CURLOPT_FOLLOWLOCATION] = false;
455 | $this->options[CURLOPT_MAXREDIRS] = 0;
456 | break;
457 |
458 | // Get headers only
459 | case 'get_code':
460 | $this->options[CURLOPT_HEADER] = true;
461 | $this->options[CURLOPT_NOBODY] = true;
462 | $this->addCallback(
463 | static function (Response $response, $_url) {
464 | return $response->getResponseCode();
465 | },
466 | array(),
467 | 60,
468 | true
469 | );
470 | break;
471 |
472 | // Get headers only
473 | case 'split_to_array':
474 | $this->addCallback(
475 | static function ($response_content, $_url) {
476 | return explode(PHP_EOL, $response_content);
477 | },
478 | array(),
479 | 50
480 | );
481 | break;
482 |
483 | // Make a request, don't wait for an answer
484 | case 'async':
485 | $this->options[CURLOPT_CONNECTTIMEOUT] = 3;
486 | $this->options[CURLOPT_TIMEOUT] = 3;
487 | break;
488 |
489 | case 'get':
490 | $this->options[CURLOPT_CUSTOMREQUEST] = 'GET';
491 | $this->options[CURLOPT_POST] = false;
492 | $this->options[CURLOPT_POSTFIELDS] = null;
493 | // Append parameter in a different way for single and multiple requests
494 | if ( is_array($this->url) ) {
495 | $this->url = array_map(function ($elem) {
496 | return self::appendParametersToURL($elem, $this->data);
497 | }, $this->url);
498 | } else {
499 | $this->options[CURLOPT_URL] = self::appendParametersToURL(
500 | $this->options[CURLOPT_URL],
501 | $this->data
502 | );
503 | }
504 | break;
505 |
506 | case 'ssl':
507 | $this->options[CURLOPT_SSL_VERIFYPEER] = true;
508 | $this->options[CURLOPT_SSL_VERIFYHOST] = 2;
509 | if ( defined('CLEANTALK_CASERT_PATH') && CLEANTALK_CASERT_PATH ) {
510 | $this->options[CURLOPT_CAINFO] = CLEANTALK_CASERT_PATH;
511 | }
512 | break;
513 |
514 | case 'no_cache':
515 | // Append parameter in a different way for single and multiple requests
516 | if ( is_array($this->url) ) {
517 | $this->url = array_map(static function ($elem) {
518 | return self::appendParametersToURL($elem, ['no_cache' => random_int(PHP_INT_MIN, PHP_INT_MAX)]);
519 | }, $this->url);
520 | } else {
521 | $this->options[CURLOPT_URL] = self::appendParametersToURL(
522 | $this->options[CURLOPT_URL],
523 | ['no_cache' => random_int(PHP_INT_MIN, PHP_INT_MAX)]
524 | );
525 | }
526 | break;
527 | }
528 | }
529 | }
530 |
531 | /**
532 | * Appends given parameter(s) to URL considering other parameters
533 | * Adds ? or & before the append
534 | *
535 | * @param string $url
536 | * @param string|array $parameters
537 | *
538 | * @return string
539 | */
540 | public static function appendParametersToURL($url, $parameters)
541 | {
542 | if ( empty($parameters) ) {
543 | return $url;
544 | }
545 |
546 | $parameters = is_array($parameters)
547 | ? http_build_query($parameters)
548 | : $parameters;
549 |
550 | $url .= strpos($url, '?') === false
551 | ? ('?' . $parameters)
552 | : ('&' . $parameters);
553 |
554 | return $url;
555 | }
556 |
557 | /**
558 | * Checks if the string is JSON type
559 | *
560 | * @param string $string
561 | *
562 | * @return bool
563 | */
564 | public static function isJson($string)
565 | {
566 | return is_string($string) && is_array(json_decode($string, true));
567 | }
568 | }
569 |
--------------------------------------------------------------------------------
/Cleantalk/Antispam/Observer/Predispatch.php:
--------------------------------------------------------------------------------
1 | scopeConfig = $scopeConfig;
41 | $this->_cookieManager = $cookieManager;
42 | $this->_sessionManager = $sessionManager;
43 | $this->config_writer = $configWriter;
44 | $this->_actionFlag = $actionFlag;
45 | }
46 |
47 | // * Get a configuration value
48 | public function getConfigValue($settings)
49 | {
50 | return $this->scopeConfig->getValue(
51 | 'general/cleantalkantispam/' . $settings,
52 | \Magento\Store\Model\ScopeInterface::SCOPE_STORE
53 | );
54 | }
55 |
56 | //Get cookie
57 | public function getCookie($cookie_name)
58 | {
59 | $result = $this->_cookieManager->getCookie($cookie_name, 'default value');
60 | return $result;
61 | }
62 |
63 | //Set cookie
64 | public function setCookie($value)
65 | {
66 | // set public cookie (can be accessed by JS)
67 | $meta = new \Magento\Framework\Stdlib\Cookie\PublicCookieMetadata();
68 | $meta->setPath('/'); // use meta to define cookie props: domain, duration, security, ...
69 | $meta->setDurationOneYear();
70 | $this->_cookieManager->setPublicCookie(self::COOKIE_REFERRAL, $value, $meta);
71 |
72 | // or set HTTP only cookie (is not accessible from JavaScript )
73 | /** @var \Magento\Framework\Stdlib\Cookie\SensitiveCookieMetadata $meta */
74 | $meta = null; // use meta to define cookie props: domain, duration, security, ...
75 | $this->_cookieManager->setSensitiveCookie(self::COOKIE_REFERRAL, $value, $meta);
76 | }
77 |
78 | public function process()
79 | {
80 | // save variable with name 'referral_code' into the session (using 'magic' methods)
81 | $this->_sessionManager->setReferralCode('u54321');
82 |
83 | // restore saved value from the session
84 | $saved = $this->_sessionManager->getReferralCode();
85 | }
86 |
87 |
88 | public function execute(Observer $observer)
89 | {
90 | //Go out if CleanTalk disabled
91 | if ( !$this->getConfigValue('ct_enabled') ) {
92 | return;
93 | }
94 |
95 | $controller = $observer->getControllerAction();
96 | if (!method_exists($controller, 'getRequest')) {
97 | return;
98 | }
99 |
100 | $this->_post = $controller->getRequest()->getPostValue();
101 |
102 | if (
103 | strpos($_SERVER['REQUEST_URI'], '/ajaxcart/') !== false ||
104 | strpos($_SERVER['REQUEST_URI'], 'sagepay') !== false ||
105 | strpos($_SERVER['REQUEST_URI'], 'paypal') !== false ||
106 | strpos($_SERVER['REQUEST_URI'], 'customer/address/edit') !== false ||
107 | strpos($_SERVER['REQUEST_URI'], 'customer/account/createpassword') !== false ||
108 | strpos($_SERVER['REQUEST_URI'], 'customer/address/new') !== false ||
109 | (isset($this->_post['action_url']) && strpos($this->_post['action_url'], 'checkout/cart/add') !== false) ||
110 | strpos($_SERVER['REQUEST_URI'], 'wishlist/index/add') !== false ||
111 | strpos($_SERVER['REQUEST_URI'], 'instagrampro/gallery/instalist') !== false ||
112 | (isset($this->_post['customerEmail']) && strpos($_SERVER['REQUEST_URI'], 'isEmailAvailable') !== false)
113 | ) {
114 | return;
115 | }
116 | $this->cookies_set();
117 | //Exeptions for spam protection
118 | if ( isset($this->_post) && count($this->_post) ) {
119 | //Flag to disable custom contact form checking
120 | $ct_already_checked = false;
121 |
122 | //Registrations
123 | $registration_test_enabled = $this->getConfigValue('ct_registrations');
124 | if (
125 | $registration_test_enabled &&
126 | (
127 | (
128 | strpos($_SERVER['REQUEST_URI'], 'account/createpost') !== false &&
129 | isset($this->_post['firstname'], $this->_post['lastname'], $this->_post['email'])
130 | ) ||
131 | (
132 | strpos($_SERVER['REQUEST_URI'], 'account/create') !== false &&
133 | isset($this->_post['email'], $this->_post['password'], $this->_post['confirmation'])
134 | )
135 | )
136 | ) {
137 | $ct_fields = $this->cleantalkGetFields($this->_post);
138 | $result_array = $this->setArrayToSend($ct_fields, 'register');
139 |
140 | $ct_already_checked = true;
141 | }
142 |
143 | //Contacts
144 | $contact_test_enabled = $this->getConfigValue('ct_contact_forms');
145 | if (
146 | $contact_test_enabled &&
147 | strpos($_SERVER['REQUEST_URI'], 'contact/index') !== false &&
148 | isset($this->_post['name'], $this->_post['email'], $this->_post['telephone'], $this->_post['comment'], $this->_post['hideit'])
149 | ) {
150 | $ct_fields = $this->cleantalkGetFields($this->_post);
151 | $result_array = $this->setArrayToSend($ct_fields, 'feedback_general_contact_form');
152 |
153 | $ct_already_checked = true;
154 | }
155 | //Reviews
156 | $reviews_test_enabled = $this->getConfigValue('ct_reviews');
157 | if (
158 | $reviews_test_enabled &&
159 | strpos($_SERVER['REQUEST_URI'], 'review') !== false &&
160 | isset($this->_post['nickname'], $this->_post['title'], $this->_post['detail'])
161 | ) {
162 | $ct_fields = $this->cleantalkGetFields($this->_post);
163 | $result_array = $this->setArrayToSend($ct_fields, 'feedback_general_contact_form');
164 |
165 | $ct_already_checked = true;
166 | }
167 | //Custom Forms
168 | $custom_forms_test_enabled = $this->getConfigValue('ct_custom_contact_forms');
169 | if ( $custom_forms_test_enabled &&
170 | !$ct_already_checked &&
171 | strpos($_SERVER['REQUEST_URI'], 'login') === false &&
172 | strpos($_SERVER['REQUEST_URI'], 'forgotpassword') === false &&
173 | strpos($_SERVER['REQUEST_URI'], 'account/create') === false &&
174 | strpos($_SERVER['REQUEST_URI'], 'account/createpost') === false &&
175 | strpos($_SERVER['REQUEST_URI'], 'account/login') === false &&
176 | strpos($_SERVER['REQUEST_URI'], 'account/edit') === false
177 | ) {
178 | $ct_fields = $this->cleantalkGetFields($this->_post);
179 | $result_array = $this->setArrayToSend($ct_fields, 'feedback_general_contact_form');
180 | }
181 |
182 | //Rrequest and block if needed
183 | if ( isset($result_array) ) {
184 | $aResult = $this->CheckSpam($result_array);
185 | if ( isset($aResult) && is_array($aResult) ) {
186 | if ( $aResult['errno'] == 0 ) {
187 | if ( $aResult['allow'] == 0 ) {
188 | $response = $observer->getControllerAction()->getResponse();
189 | $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
190 | return $response->setBody($this->CleantalkDie($aResult['ct_result_comment']));
191 | }
192 | }
193 | }
194 | }
195 | }
196 | }
197 |
198 | //Prepares data to request
199 | private function setArrayToSend($arr, $type)
200 | {
201 | $result_array = array();
202 | $result_array['type'] = $type;
203 | $result_array['sender_email'] = ($arr['email'] ? $arr['email'] : '');
204 | $result_array['sender_nickname'] = ($arr['nickname'] ? $arr['nickname'] : '');
205 | $result_array['message_title'] = '';
206 | $result_array['message_body'] = ($arr['message'] ? $arr['message'] : '');
207 | $result_array['example_title'] = '';
208 | $result_array['example_body'] = '';
209 | $result_array['example_comments'] = '';
210 | $result_array['send_request'] = ($arr['message'] || $arr['email']) ? true : false;
211 | return $result_array;
212 | }
213 |
214 | /**
215 | * Cookie test
216 | * @return
217 | */
218 | private function cookies_set()
219 | {
220 | // Cookie names to validate
221 | $cookie_test_value = array(
222 | 'cookies_names' => array(),
223 | 'check_value' => $this->getConfigValue('ct_access_key'),
224 | );
225 | // Pervious referer
226 | if ( !empty($_SERVER['HTTP_REFERER']) ) {
227 | setcookie('ct_prev_referer', $_SERVER['HTTP_REFERER'], 0, '/');
228 | $cookie_test_value['cookies_names'][] = 'ct_prev_referer';
229 | $cookie_test_value['check_value'] .= $_SERVER['HTTP_REFERER'];
230 | }
231 | // Submit time
232 | $ct_timestamp = time();
233 | setcookie('ct_timestamp', $ct_timestamp, 0, '/');
234 | $cookie_test_value['cookies_names'][] = 'ct_timestamp';
235 | $cookie_test_value['check_value'] .= $ct_timestamp;
236 |
237 | // Landing time
238 | if ( isset($_COOKIE['ct_site_landing_ts']) ) {
239 | $site_landing_timestamp = $_COOKIE['ct_site_landing_ts'];
240 | } else {
241 | $site_landing_timestamp = time();
242 | setcookie('ct_site_landing_ts', $site_landing_timestamp, 0, '/');
243 | }
244 | $cookie_test_value['cookies_names'][] = 'ct_site_landing_ts';
245 | $cookie_test_value['check_value'] .= $site_landing_timestamp;
246 |
247 | // Cookies test
248 | $cookie_test_value['check_value'] = hash("sha256", $cookie_test_value['check_value']);
249 | setcookie('ct_cookies_test', json_encode($cookie_test_value), 0, '/');
250 | }
251 |
252 | /**
253 | * Cookie test
254 | * @return int
255 | */
256 | private function cookies_test()
257 | {
258 | if ( isset($_COOKIE['ct_cookies_test']) ) {
259 | $cookie_test = json_decode(stripslashes($_COOKIE['ct_cookies_test']), true);
260 |
261 | $check_srting = $this->getConfigValue('ct_access_key');
262 | foreach ( $cookie_test['cookies_names'] as $cookie_name ) {
263 | $check_srting .= isset($_COOKIE[$cookie_name]) ? $_COOKIE[$cookie_name] : '';
264 | }
265 | unset($cokie_name);
266 |
267 | if ( $cookie_test['check_value'] == hash("sha256", $check_srting) ) {
268 | return 1;
269 | } else {
270 | return 0;
271 | }
272 | } else {
273 | return null;
274 | }
275 | }
276 |
277 | //Recursevely gets data from array
278 | private function cleantalkGetFields(
279 | $arr,
280 | $message = array(),
281 | $email = null,
282 | $nickname = array('nick' => '', 'first' => '', 'last' => ''),
283 | $subject = null,
284 | $contact = true,
285 | $prev_name = ''
286 | ) {
287 | //Skip request if fields exists
288 | $skip_params = array(
289 | 'ipn_track_id', // PayPal IPN #
290 | 'txn_type', // PayPal transaction type
291 | 'payment_status', // PayPal payment status
292 | 'ccbill_ipn', // CCBill IPN
293 | 'ct_checkjs', // skip ct_checkjs field
294 | 'api_mode', // DigiStore-API
295 | 'loadLastCommentId' // Plugin: WP Discuz. ticket_id=5571
296 | );
297 |
298 | // Fields to replace with ****
299 | $obfuscate_params = array(
300 | 'password',
301 | 'password_confirmation',
302 | 'pass',
303 | 'pwd',
304 | 'pswd'
305 | );
306 |
307 | // Skip feilds with these strings and known service fields
308 | $skip_fields_with_strings = array(
309 | // Common
310 | 'ct_checkjs', //Do not send ct_checkjs
311 | 'nonce', //nonce for strings such as 'rsvp_nonce_name'
312 | 'security',
313 | // 'action',
314 | 'http_referer',
315 | 'timestamp',
316 | 'captcha',
317 | // Formidable Form
318 | 'form_key',
319 | 'submit_entry',
320 | // Custom Contact Forms
321 | 'form_id',
322 | 'ccf_form',
323 | 'form_page',
324 | // Qu Forms
325 | 'iphorm_uid',
326 | 'form_url',
327 | 'post_id',
328 | 'iphorm_ajax',
329 | 'iphorm_id',
330 | // Fast SecureContact Froms
331 | 'fs_postonce_1',
332 | 'fscf_submitted',
333 | 'mailto_id',
334 | 'si_contact_action',
335 | // Ninja Forms
336 | 'formData_id',
337 | 'formData_settings',
338 | 'formData_fields_\d+_id',
339 | 'formData_fields_\d+_files.*',
340 | // E_signature
341 | 'recipient_signature',
342 | 'output_\d+_\w{0,2}',
343 | // Contact Form by Web-Settler protection
344 | '_formId',
345 | '_returnLink',
346 | // Social login and more
347 | '_save',
348 | '_facebook',
349 | '_social',
350 | 'user_login-',
351 | 'submit',
352 | 'form_token',
353 | 'creation_time',
354 | 'uenc',
355 | 'product',
356 | 'qty',
357 |
358 | );
359 |
360 | foreach ( $skip_params as $value ) {
361 | if ( array_key_exists($value, $this->_post) ) {
362 | $contact = false;
363 | }
364 | }
365 | unset($value);
366 |
367 | if ( count($arr) ) {
368 | foreach ( $arr as $key => $value ) {
369 | if ( gettype($value) == 'string' ) {
370 | $decoded_json_value = json_decode($value, true);
371 | if ( $decoded_json_value !== null ) {
372 | $value = $decoded_json_value;
373 | }
374 | }
375 |
376 | if ( !is_array($value) && !is_object($value) ) {
377 | if ( in_array($key, $skip_params, true) && $key != 0 && $key != '' || preg_match(
378 | "/^ct_checkjs/",
379 | $key
380 | ) ) {
381 | $contact = false;
382 | }
383 |
384 | if ( $value === '' ) {
385 | continue;
386 | }
387 |
388 | // Skipping fields names with strings from (array)skip_fields_with_strings
389 | foreach ( $skip_fields_with_strings as $needle ) {
390 | if ( preg_match("/" . $needle . "/", $prev_name . $key) == 1 ) {
391 | continue(2);
392 | }
393 | }
394 | unset($needle);
395 | // Obfuscating params
396 | foreach ( $obfuscate_params as $needle ) {
397 | if ( strpos($key, $needle) !== false ) {
398 | $value = self::obfuscate_param($value);
399 | }
400 | }
401 | unset($needle);
402 |
403 | // Removes whitespaces
404 | $value = urldecode(trim($value)); // Fully cleaned message
405 | $value_for_email = trim(
406 | $value
407 | ); // Removes shortcodes to do better spam filtration on server side.
408 |
409 | // Email
410 | if ( !$email && preg_match("/^\S+@\S+\.\S+$/", $value_for_email) ) {
411 | $email = $value_for_email;
412 | // Names
413 | } elseif ( preg_match("/name/i", $key) ) {
414 | preg_match("/(first.?name)?(name.?first)?(forename)?/", $key, $match_forename);
415 | preg_match("/(last.?name)?(family.?name)?(second.?name)?(surname)?/", $key, $match_surname);
416 | preg_match("/(nick.?name)?(user.?name)?(nick)?/", $key, $match_nickname);
417 |
418 | if ( count($match_forename) > 1 ) {
419 | $nickname['first'] = $value;
420 | } elseif ( count($match_surname) > 1 ) {
421 | $nickname['last'] = $value;
422 | } elseif ( count($match_nickname) > 1 ) {
423 | $nickname['nick'] = $value;
424 | } else {
425 | $message[$prev_name . $key] = $value;
426 | }
427 | // Subject
428 | } elseif ( $subject === null && preg_match("/subject/i", $key) ) {
429 | $subject = $value;
430 | // Message
431 | } else {
432 | $message[$prev_name . $key] = $value;
433 | }
434 | } elseif ( !is_object($value) ) {
435 | $prev_name_original = $prev_name;
436 | $prev_name = ($prev_name === '' ? $key . '_' : $prev_name . $key . '_');
437 |
438 | $temp = self::cleantalkGetFields(
439 | $value,
440 | $message,
441 | $email,
442 | $nickname,
443 | $subject,
444 | $contact,
445 | $prev_name
446 | );
447 |
448 | $message = $temp['message'];
449 | $email = ($temp['email'] ? $temp['email'] : null);
450 | $nickname = ($temp['nickname'] ? $temp['nickname'] : null);
451 | $subject = ($temp['subject'] ? $temp['subject'] : null);
452 | if ( $contact === true ) {
453 | $contact = ($temp['contact'] === false ? false : true);
454 | }
455 | $prev_name = $prev_name_original;
456 | }
457 | }
458 | unset($key, $value);
459 | }
460 |
461 | //If top iteration, returns compiled name field. Example: "Nickname Firtsname Lastname".
462 | if ( $prev_name === '' ) {
463 | if ( !empty($nickname) ) {
464 | $nickname_str = '';
465 | foreach ( $nickname as $value ) {
466 | $nickname_str .= ($value ? $value . " " : "");
467 | }
468 | unset($value);
469 | }
470 | $nickname = $nickname_str;
471 | }
472 |
473 | $return_param = array(
474 | 'email' => $email,
475 | 'nickname' => $nickname,
476 | 'subject' => $subject,
477 | 'contact' => $contact,
478 | 'message' => $message
479 | );
480 | return $return_param;
481 | }
482 |
483 | /**
484 | * Masks a value with asterisks (*)
485 | * @return string
486 | */
487 | private function obfuscate_param($value = null)
488 | {
489 | if ( $value && (!is_object($value) || !is_array($value)) ) {
490 | $length = strlen($value);
491 | $value = str_repeat('*', $length);
492 | }
493 | return $value;
494 | }
495 |
496 | /**
497 | * Die function - Get HTML for the die page
498 | *
499 | * @param $message
500 | * @return string
501 | */
502 | private function CleantalkDie($message)
503 | {
504 | $error_tpl = file_get_contents(dirname(__FILE__) . "/error.html");
505 | return str_replace('%ERROR_TEXT%', $message, $error_tpl);
506 | }
507 |
508 | /**
509 | * Universal method for checking comment or new user for spam
510 | * It makes checking itself
511 | * @param &array Entity to check (comment or new user)
512 | * @param boolean Notify admin about errors by email or not (default FALSE)
513 | * @return array|null Checking result or NULL when bad params
514 | */
515 | private function CheckSpam($arEntity)
516 | {
517 | if ( !is_array($arEntity) || !array_key_exists('type', $arEntity) || $arEntity['send_request'] === false ) {
518 | return;
519 | }
520 | $url_exclusions_config = $this->getConfigValue('ct_exclude_urls');
521 | if ( !empty($url_exclusions_config) && !is_null($url_exclusions_config) ) {
522 | $get_exclusions = explode(',', trim($url_exclusions_config));
523 | if ( $get_exclusions && is_array($get_exclusions) && count($get_exclusions) > 0 ) {
524 | foreach ( $get_exclusions as $key => $value ) {
525 | if ( strpos($_SERVER['REQUEST_URI'], $value) !== false ) { // Simple string checking
526 | return;
527 | }
528 | }
529 | }
530 | }
531 | $type = $arEntity['type'];
532 | if ( $type != 'feedback_general_contact_form' && $type != 'register' ) {
533 | return;
534 | }
535 |
536 | $ct_key = $this->getConfigValue('ct_access_key');
537 |
538 | $ct_ws = array(
539 | 'work_url' => 'https://moderate.cleantalk.org',
540 | 'server_url' => 'https://moderate.cleantalk.org',
541 | 'server_ttl' => 0,
542 | 'server_changed' => 0,
543 | );
544 | if ( !(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower(
545 | $_SERVER['HTTP_X_REQUESTED_WITH']
546 | ) == 'xmlhttprequest') ) {
547 | if ( !session_id() ) {
548 | session_start();
549 | }
550 | } //This one is causing errors with ajax
551 |
552 | $checkjs = $this->getCookie('ct_checkjs') == hash('sha256', $this->getConfigValue('ct_access_key')) ? 1 : 0;
553 | $timezone = $this->getCookie('ct_timezone');
554 | $ref_pref = $this->getCookie('ct_prev_referer');
555 | $fkp_timestamp = $this->getCookie('ct_fkp_timestamp');
556 | $pointer_data = $this->getCookie('ct_pointer_data');
557 | $ps_timestamp = $this->getCookie('ct_ps_timestamp');
558 | $ct_timestamp = $this->getCookie('ct_timestamp');
559 | if ( isset($_SERVER['HTTP_USER_AGENT']) ) {
560 | $user_agent = htmlspecialchars((string)$_SERVER['HTTP_USER_AGENT']);
561 | } else {
562 | $user_agent = null;
563 | }
564 |
565 | if ( isset($_SERVER['HTTP_REFERER']) ) {
566 | $refferrer = htmlspecialchars((string)$_SERVER['HTTP_REFERER']);
567 | } else {
568 | $refferrer = null;
569 | }
570 |
571 | $ct_language = 'en';
572 |
573 | $sender_info = array(
574 | 'cms_lang' => $ct_language,
575 | 'REFFERRER' => $refferrer,
576 | 'post_url' => $refferrer,
577 | 'USER_AGENT' => $user_agent,
578 | 'js_timezone' => ($timezone && $timezone !== 'default value') ? $timezone : '',
579 | 'REFFERRER_PREVIOUS' => ($ref_pref && $ref_pref !== 'default value') ? $ref_pref : null,
580 | 'cookies_enabled' => $this->cookies_test(),
581 | 'mouse_cursor_positions' => ($pointer_data) ? json_decode($pointer_data) : '',
582 | 'key_press_timestamp' => ($fkp_timestamp && $fkp_timestamp !== 'default value') ? $fkp_timestamp : 0,
583 | 'page_set_timestamp' => ($ps_timestamp && $ps_timestamp !== 'default value') ? $ps_timestamp : 0,
584 | );
585 | $sender_info = json_encode($sender_info);
586 |
587 | $ct = new Cleantalk();
588 | $ct->work_url = $ct_ws['work_url'];
589 | $ct->server_url = $ct_ws['server_url'];
590 | $ct->server_ttl = $ct_ws['server_ttl'];
591 | $ct->server_changed = $ct_ws['server_changed'];
592 |
593 | $sender_ip = Helper::ipGet('remote_addr', false);
594 | $ct_request = new CleantalkRequest();
595 | $ct_request->auth_key = $ct_key;
596 | $ct_request->sender_email = isset($arEntity['sender_email']) ? $arEntity['sender_email'] : '';
597 | $ct_request->sender_nickname = isset($arEntity['sender_nickname']) ? $arEntity['sender_nickname'] : '';
598 | $ct_request->sender_ip = isset($arEntity['sender_ip']) ? $arEntity['sender_ip'] : $sender_ip;
599 | $ct_request->agent = 'magento2-1.6.0';
600 | $ct_request->js_on = $checkjs;
601 | $ct_request->sender_info = $sender_info;
602 | $ct_request->submit_time = ($ct_timestamp) ? time() - intval($ct_timestamp) : 0;
603 |
604 | switch ( $type ) {
605 | case 'feedback_general_contact_form':
606 | // Skip submission if no data found
607 | if ( $ct_request->sender_email === '' && $ct_request->sender_nickname === '' ) {
608 | return false;
609 | }
610 | $timelabels_key = 'mail_error_comment';
611 | if ( isset($arEntity['message_title']) ) {
612 | $message_title = is_array($arEntity['message_title']) ? implode(
613 | " ",
614 | $arEntity['message_title']
615 | ) : $arEntity['message_title'];
616 | } else {
617 | $message_title = '';
618 | }
619 | if ( isset($arEntity['message_body']) ) {
620 | $message_body = is_array($arEntity['message_body']) ? implode(
621 | " ",
622 | $arEntity['message_body']
623 | ) : $arEntity['message_body'];
624 | } else {
625 | $message_body = '';
626 | }
627 | $ct_request->message = $message_title . " \n\n" . $message_body;
628 |
629 | $example = '';
630 | $a_example['title'] = isset($arEntity['example_title']) ? $arEntity['example_title'] : '';
631 | $a_example['body'] = isset($arEntity['example_body']) ? $arEntity['example_body'] : '';
632 | $a_example['comments'] = isset($arEntity['example_comments']) ? $arEntity['example_comments'] : '';
633 |
634 | // Additional info.
635 | $post_info = '';
636 | $a_post_info['comment_type'] = 'feedback_general_contact_form';
637 |
638 | // JSON format.
639 | $example = json_encode($a_example);
640 | $post_info = json_encode($a_post_info);
641 |
642 | // Plain text format.
643 | if ( $example === false ) {
644 | $example = '';
645 | $example .= $a_example['title'] . " \n\n";
646 | $example .= $a_example['body'] . " \n\n";
647 | $example .= $a_example['comments'];
648 | }
649 | if ( $post_info === false ) {
650 | $post_info = '';
651 | }
652 |
653 | // Example text + last N comments in json or plain text format.
654 | $ct_request->example = $example;
655 | $ct_request->post_info = $post_info;
656 | $ct_result = $ct->isAllowMessage($ct_request);
657 | break;
658 | case 'register':
659 | $timelabels_key = 'mail_error_reg';
660 | $ct_request->tz = isset($arEntity['user_timezone']) ? $arEntity['user_timezone'] : null;
661 | $ct_result = $ct->isAllowUser($ct_request);
662 | }
663 | $ret_val = array();
664 | $ret_val['ct_request_id'] = $ct_result->id;
665 |
666 | // First check errstr flag.
667 | if ( !empty($ct_result->errstr)
668 | || (!empty($ct_result->inactive) && $ct_result->inactive == 1)
669 | ) {
670 | // Cleantalk error so we go default way (no action at all).
671 | $ret_val['errno'] = 1;
672 | $err_title = $_SERVER['SERVER_NAME'] . ' - CleanTalk module error';
673 |
674 | if ( !empty($ct_result->errstr) ) {
675 | if ( preg_match('//u', $ct_result->errstr) ) {
676 | $err_str = preg_replace('/^[^\*]*?\*\*\*|\*\*\*[^\*]*?$/iu', '', $ct_result->errstr);
677 | } else {
678 | $err_str = preg_replace('/^[^\*]*?\*\*\*|\*\*\*[^\*]*?$/i', '', $ct_result->errstr);
679 | }
680 | } else {
681 | if ( preg_match('//u', $ct_result->comment) ) {
682 | $err_str = preg_replace('/^[^\*]*?\*\*\*|\*\*\*[^\*]*?$/iu', '', $ct_result->comment);
683 | } else {
684 | $err_str = preg_replace('/^[^\*]*?\*\*\*|\*\*\*[^\*]*?$/i', '', $ct_result->comment);
685 | }
686 | }
687 | $ret_val['errstr'] = $err_str;
688 |
689 | return $ret_val;
690 | }
691 | $ret_val['errno'] = 0;
692 | if ( $ct_result->allow == 1 ) {
693 | // Not spammer.
694 | $ret_val['allow'] = 1;
695 | } else {
696 | $ret_val['allow'] = 0;
697 | $ret_val['ct_result_comment'] = $ct_result->comment;
698 | // Spammer.
699 | // Check stop_queue flag.
700 | if ( $type == 'comment' && $ct_result->stop_queue == 0 ) {
701 | // Spammer and stop_queue == 0 - to manual approvement.
702 | $ret_val['stop_queue'] = 0;
703 | } else {
704 | // New user or Spammer and stop_queue == 1 - display message and exit.
705 | $ret_val['stop_queue'] = 1;
706 | }
707 | }
708 | return $ret_val;
709 | }
710 | }
711 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------