Completed
Push — master ( 1490b2...827c13 )
by Владислав
02:03
created

DeCaptchaAbstract::getCurlResponse()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 17
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 0
cts 15
cp 0
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 14
nc 4
nop 1
crap 30
1
<?php
2
3
namespace jumper423\decaptcha\core;
4
5
use Exception;
6
7
/**
8
 * Class DeCaptchaAbstract
9
 * @package jumper423
10
 */
11
abstract class DeCaptchaAbstract implements DeCaptchaInterface
12
{
13
    public $lang = 'en';
14
    /**
15
     * Сервис на который будем загружать капчу
16
     * @var string
17
     */
18
    public $domain;
19
    /**
20
     * Ваш API key
21
     * @var string
22
     */
23
    protected $apiKey;
24
    /**
25
     * false(commenting OFF), true(commenting ON)
26
     * @var bool
27
     */
28
    public $isVerbose;
29
    /**
30
     * Таймаут проверки ответа
31
     * @var int
32
     */
33
    public $requestTimeout;
34
    /**
35
     * Максимальное время ожидания ответа
36
     * @var int
37
     */
38
    public $maxTimeout;
39
    /**
40
     * 0 OR 1 - капча из двух или более слов
41
     * @var int
42
     */
43
    public $isPhrase;
44
    /**
45
     * 0 OR 1 - регистр ответа важен
46
     * @var int
47
     */
48
    public $isRegSense;
49
    /**
50
     * 0 OR 1 OR 2 OR 3 - 0 = параметр не задействован (значение по умолчанию) 1 = капча состоит только из цифр 2 =
51
     * Капча состоит только из букв 3 = Капча состоит либо только из цифр, либо только из букв.
52
     * @var int
53
     */
54
    public $isNumeric;
55
    /**
56
     * 0 если не ограничено, иначе обозначает минимальную длину ответа
57
     * @var int
58
     */
59
    public $minLen;
60
    /**
61
     * 0 если не ограничено, иначе обозначает минимальную длину ответа
62
     * @var int
63
     */
64
    public $maxLen;
65
    /**
66
     * 0 OR 1 OR 2 0 = параметр не задействован (значение по умолчанию) 1 = капча на кириллице 2 = капча на латинице
67
     * @var int
68
     */
69
    public $language;
70
    /**
71
     * Ошибка
72
     * @var null|string
73
     */
74
    protected $error = null;
75
    /**
76
     * Результат
77
     * @var null|string
78
     */
79
    protected $result = null;
80
    /**
81
     * @var int
82
     */
83
    protected $captchaId;
84
85
    const RESPONSE_TYPE_STRING = 0;
86
    const RESPONSE_TYPE_JSON = 1;
87
88
    public $errorLang = DeCaptchaErrors::LANG_EN;
89
90
    public $responseType = self::RESPONSE_TYPE_STRING;
91
92 3
    public function setApiKey($apiKey)
93
    {
94 3
        if (is_callable($apiKey)) {
95 1
            $this->apiKey = $apiKey();
96 1
        } else {
97 3
            $this->apiKey = $apiKey;
98
        }
99 3
    }
100
101
    /**
102
     * @return void
103
     */
104
    abstract public function notTrue();
105
106
    /**
107
     * Узнаём путь до файла
108
     * Если передана ссылка, то скачиваем и кладём во временную директорию
109
     *
110
     * @param string $fileName
111
     * @return string
112
     * @throws Exception
113
     */
114 3
    protected function getFilePath($fileName) {
115 3
        if (strpos($fileName, 'http://') !== false || strpos($fileName, 'https://') !== false) {
116 2
            $current = @file_get_contents($fileName);
117 2
            if ($current) {
118 1
                $path = tempnam(sys_get_temp_dir(), 'captcha');
119 1
                if (file_put_contents($path, $current)) {
120 1
                    $fileName = $path;
121 1
                } else {
122
                    throw new DeCaptchaErrors(DeCaptchaErrors::ERROR_WRITE_ACCESS_FILE, null, $this->errorLang);
123
                }
124 1
            } else {
125 1
                throw new DeCaptchaErrors(DeCaptchaErrors::ERROR_FILE_IS_NOT_LOADED, $fileName, $this->errorLang);
126
            }
127 2
        } elseif (!file_exists($fileName)) {
128 1
            throw new DeCaptchaErrors(DeCaptchaErrors::ERROR_FILE_NOT_FOUND, $fileName, $this->errorLang);
129
        }
130 1
        return $fileName;
131
    }
132
133
    /**
134
     * @return string
135
     */
136 4
    protected function getBaseUrl() {
137 4
        return "http://{$this->domain}/";
138
    }
139
140
    /**
141
     * @param string $action
142
     * @return string
143
     */
144 2
    protected function getActionUrl($action) {
145 2
        return "{$this->getBaseUrl()}res.php?key={$this->apiKey}&action={$action}&id={$this->captchaId}";
146
    }
147
148
    /**
149
     * @param string $action
150
     * @return string
151
     */
152 1
    protected function getResponse($action) {
153 1
        return file_get_contents($this->getActionUrl($action));
154
    }
155
156
    /**
157
     * @return string
158
     */
159 1
    protected function getInUrl() {
160 1
        return "{$this->getBaseUrl()}in.php";
161
    }
162
163
    /**
164
     * Проверка на то произошла ли ошибка
165
     *
166
     * @param $error
167
     * @throws DeCaptchaErrors
168
     */
169 2
    protected function isError($error)
170
    {
171 2
        if (strpos($error, 'ERROR') !== false) {
172 1
            throw new DeCaptchaErrors($error, null, $this->errorLang);
173
        }
174 1
    }
175
176
    protected $lastRunTime = null;
177
178
    /**
179
     * Задержка выполнения
180
     *
181
     * @param int $delay Количество секунд
182
     * @param \Closure|null $callback
183
     * @return mixed
184
     */
185 1
    protected function executionDelayed($delay = 0, $callback = null) {
186 1
        $time = microtime(true);
187 1
        $timePassed = $time - $this->lastRunTime;
188 1
        if ($timePassed < $delay) {
189 1
            usleep(($delay - $timePassed) * 1000000);
190 1
        }
191 1
        $this->lastRunTime = microtime(true);
192 1
        return $callback instanceof \Closure ? $callback($this) : $callback;
193
    }
194
195
    /**
196
     * @param $postData
197
     * @return string
198
     * @throws Exception
199
     */
200
    protected function getCurlResponse($postData) {
201
        $ch = curl_init();
202
        curl_setopt($ch, CURLOPT_URL, $this->getInUrl());
203
        if (version_compare(PHP_VERSION, '5.5.0') >= 0 && version_compare(PHP_VERSION, '7.0') < 0 && defined('CURLOPT_SAFE_UPLOAD')) {
204
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
205
        }
206
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
207
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
208
        curl_setopt($ch, CURLOPT_POST, 1);
209
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
210
        $result = curl_exec($ch);
211
        if (curl_errno($ch)) {
212
            throw new DeCaptchaErrors(DeCaptchaErrors::ERROR_CURL, curl_error($ch), $this->errorLang);
213
        }
214
        curl_close($ch);
215
        return $result;
216
    }
217
218
    abstract protected function decodeResponse($data, $type, $format = self::RESPONSE_TYPE_STRING);
219
}
220