-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Дмитрий Гладышев
committed
Dec 19, 2015
0 parents
commit 1368582
Showing
17 changed files
with
743 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
# JetBrains cool IDE | ||
/.idea | ||
|
||
# Composer | ||
/vendor/ | ||
/composer.phar | ||
/composer.lock | ||
|
||
# PHPUnit library | ||
phpunit.phar | ||
|
||
# private files | ||
/tests/private/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
The MIT License (MIT) | ||
|
||
Copyright (c) 2015 Dmitry Gladyshev | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
# rucaptcha-client # | ||
|
||
**PHP 5.6** | ||
|
||
## Пример ## | ||
|
||
```php | ||
$rucaptcha = new Rucaptcha\Client('YOUR_API_KEY', [ | ||
'verbose' => true | ||
]); | ||
|
||
$captchaText = $rucaptcha->recognizeFile('/captcha.png', [ | ||
'regsense' => 1 | ||
]); | ||
|
||
print_r($captchaText); | ||
``` | ||
|
||
## Методы `Rucaptcha\Client` ## | ||
|
||
```php | ||
Client Client::setOptions(array $options); | ||
string Client::recognize(string $content, array $extra = []); | ||
string Client::recognizeFile(string $path, array $extra = []); | ||
string Client::getLastCaptchaId(); | ||
string Client::getBalance(); | ||
bool Client::badCaptcha(string $captchaId); | ||
array Client::getLoad(array $paramsList = []); | ||
``` | ||
## Опции клиента ## | ||
|
||
Параметр | Тип | По умолчанию | Возможные значения | ||
---| --- | --- | --- | ||
`verbose` | bool | false | Включает/отключает логирование | ||
`apiKey`| string | '' | Ключ API с которым вызывается сервис | ||
`rTimeout`| integer | 5 | Период между опросами серевера при получении результата распознавания | ||
`mTimeout` | integer | 120 | Таймаут ожидания ответа при получении результата распознавания | ||
`serverBaseUri`| string | 'http://rucaptcha.com' | Базовый URI сервиса | ||
|
||
## Параметры распознавания капчи `$extra` ## | ||
|
||
Параметр | Тип | По умолчанию | Возможные значения | ||
---| --- | --- | --- | ||
`phrase` | integer | 0 | 0 = одно слово <br/> 1 = капча имеет два слова | ||
`regsense`| integer | 0 | 0 = регистр ответа не имеет значения <br> 1 = регистр ответа имеет значение | ||
`question`| integer | 0 | 0 = параметр не задействован <br> 1 = на изображении задан вопрос, работник должен написать ответ | ||
`numeric` | integer | 0 | 0 = параметр не задействован <br> 1 = капча состоит только из цифр<br> 2 = Капча состоит только из букв<br> 3 = Капча состоит либо только из цифр, либо только из букв. | ||
`calc`| integer | 0 | 0 = параметр не задействован <br> 1 = работнику нужно совершить математическое действие с капчи | ||
`min_len` | 0..20 | 0 | 0 = параметр не задействован <br> 1..20 = минимальное количество знаков в ответе | ||
`max_len` | 1..20 | 0 | 0 = параметр не задействован<br> 1..20 = максимальное количество знаков в ответе | ||
`is_russian` | integer | 0 | параметр больше не используется, т.к. он означал "слать данную капчу русским исполнителям", а в системе находятся только русскоязычные исполнители. Смотрите новый параметр language, однозначно обозначающий язык капчи | ||
`soft_id` | string | | ID разработчика приложения. Разработчику приложения отчисляется 10% от всех капч, пришедших из его приложения. | ||
`language` | integer | 0 | 0 = параметр не задействован <br> 1 = на капче только кириллические буквы <br>2 = на капче только латинские буквы | ||
`header_acao` | integer | 0 | 0 = значение по умолчанию <br> 1 = in.php передаст Access-Control-Allow-Origin: * параметр в заголовке ответа. (Необходимо для кросс-доменных AJAX запросов в браузерных приложениях. Работает также для res.php.) | ||
`textinstructions` | string | |Текст, который будет показан работнику. Может содержать в себе инструкции по разгадке капчи. Ограничение - 140 символов. Текст необходимо слать в кодировке UTF-8. | ||
`textcaptcha` | string | | Текстовая капча. Картинка при этом не загружается, работник получает только текст и вводит ответ на этот текст. Ограничение - 140 символов. Текст необходимо слать в кодировке UTF-8. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
{ | ||
"name": "gladyshev/rucaptcha-client", | ||
"keywords": ["php", "library", "client", "captcha recognition", "rucaptcha"], | ||
"minimum-stability": "stable", | ||
"type": "library", | ||
"license": "MIT", | ||
"authors": [ | ||
{ | ||
"name": "Dmitry Gladyshev", | ||
"email": "[email protected]", | ||
"homepage": "https://github.com/gladyshev" | ||
} | ||
], | ||
"require": { | ||
"php" : ">=5.6", | ||
"guzzlehttp/guzzle": "6.1.*", | ||
"psr/log": "*" | ||
}, | ||
"autoload": { | ||
"psr-4": { | ||
"Rucaptcha\\" : "src/" | ||
} | ||
}, | ||
"autoload-dev": { | ||
"psr-4": { | ||
"Rucaptcha\\tests\\" : "tests/" | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
<phpunit | ||
bootstrap="vendor/autoload.php" | ||
verbose="true" | ||
backupGlobals="false" | ||
colors="true" | ||
convertErrorsToExceptions="true" | ||
convertNoticesToExceptions="true" | ||
convertWarningsToExceptions="true" | ||
> | ||
<testsuites> | ||
<testsuite> | ||
<directory suffix="Test.php">./tests/functional</directory> | ||
</testsuite> | ||
</testsuites> | ||
</phpunit> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
<?php | ||
/** | ||
* @author Dmitry Gladyshev <[email protected]> | ||
*/ | ||
|
||
namespace Rucaptcha; | ||
|
||
|
||
use Rucaptcha\Exception\RuntimeException; | ||
|
||
class Client extends GenericClient | ||
{ | ||
const STATUS_OK_REPORT_RECORDED = 'OK_REPORT_RECORDED'; | ||
|
||
/** | ||
* @var string | ||
*/ | ||
protected $serverBaseUri = 'http://rucaptcha.com'; | ||
|
||
/** | ||
* @var string | ||
*/ | ||
private $softId = ''; | ||
|
||
/** | ||
* @inheritdoc | ||
*/ | ||
public function recognize($content, array $extra = []) | ||
{ | ||
if ($this->softId !== '') { | ||
$extra[Extra::SOFT_ID] = $this->softId; | ||
} | ||
return parent::recognize($content, $extra); | ||
} | ||
|
||
/** | ||
* @return string | ||
*/ | ||
public function getBalance() | ||
{ | ||
$response = $this->getClient()->request('GET', "/res.php?key={$this->apiKey}&action=getbalance"); | ||
return $response->getBody()->__toString(); | ||
} | ||
|
||
/** | ||
* @param $captchaId | ||
* @return bool | ||
* @throws RuntimeException | ||
*/ | ||
public function badCaptcha($captchaId) | ||
{ | ||
$response = $this->getClient()->request('GET', "/res.php?action=reportbad&id={$captchaId}"); | ||
if ($response->getBody()->__toString() === self::STATUS_OK_REPORT_RECORDED) | ||
return true; | ||
|
||
throw new RuntimeException('Report sending trouble: ' . $response->getBody() . '.'); | ||
} | ||
|
||
/** | ||
* @param array $paramsList | ||
* @return array | ||
*/ | ||
public function getLoad(array $paramsList = ['waiting', 'load', 'minbid', 'averageRecognitionTime']) | ||
{ | ||
$response = $this->getClient()->request('GET', "/load.php"); | ||
$responseText = $response->getBody()->__toString(); | ||
$statusData = []; | ||
|
||
foreach ($paramsList as $item) { | ||
// Fast parse tags | ||
$value = substr($responseText, | ||
strpos($responseText, '<' . $item . '>') + mb_strlen('<' . $item . '>'), | ||
strpos($responseText, '</' . $item . '>') - strpos($responseText, '<' . $item . '>') - mb_strlen('<' . $item . '>') | ||
); | ||
|
||
if ($value !== false) { | ||
$statusData[$item] = $value; | ||
} | ||
} | ||
return $statusData; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
<?php | ||
/** | ||
* @author Dmitry Gladyshev <[email protected]> | ||
*/ | ||
|
||
namespace Rucaptcha; | ||
|
||
|
||
use Rucaptcha\Exception\InvalidArgumentException; | ||
|
||
trait ConfigurableTrait | ||
{ | ||
public function setOptions(array $properties, $ignoreMissingProperties = false) | ||
{ | ||
foreach ($properties as $property => $value) { | ||
$setter = 'set' . ucfirst($property); | ||
|
||
if (method_exists($this, $setter)) { | ||
$this->$setter($value); | ||
continue; | ||
} | ||
|
||
if (property_exists($this, $property)) { | ||
$this->$property = $value; | ||
continue; | ||
} | ||
|
||
if (!$ignoreMissingProperties) { | ||
throw new InvalidArgumentException("Property `{$property}` not found in class `" . __CLASS__ . "`."); | ||
} | ||
} | ||
return $this; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
<?php | ||
/** | ||
* @author Dmitry Gladyshev <[email protected]> | ||
*/ | ||
|
||
namespace Rucaptcha; | ||
|
||
|
||
class Error | ||
{ | ||
const KEY_DOES_NOT_EXIST = 'ERROR_KEY_DOES_NOT_EXIST'; | ||
const WRONG_ID_FORMAT = 'ERROR_WRONG_ID_FORMAT'; | ||
const ZERO_BALANCE = 'ERROR_ZERO_BALANCE'; | ||
const CAPTCHA_UNSOLVABLE = 'ERROR_CAPTCHA_UNSOLVABLE'; | ||
const NO_SLOT_AVAILABLE = 'ERROR_NO_SLOT_AVAILABLE'; | ||
const WRONG_CAPTCHA_ID = 'ERROR_WRONG_CAPTCHA_ID'; | ||
const ZERO_CAPTCHA_FILESIZE = 'ERROR_ZERO_CAPTCHA_FILESIZE'; | ||
const BAD_DUPLICATES = 'ERROR_BAD_DUPLICATES'; | ||
const TOO_BIG_CAPTCHA_FILESIZE = 'ERROR_TOO_BIG_CAPTCHA_FILESIZE'; | ||
const WRONG_FILE_EXTENSION = 'ERROR_WRONG_FILE_EXTENSION'; | ||
const IMAGE_TYPE_NOT_SUPPORTED = 'ERROR_IMAGE_TYPE_NOT_SUPPORTED'; | ||
const IP_NOT_ALLOWED = 'ERROR_IP_NOT_ALLOWED'; | ||
const IP_BANNED = 'ERROR_IP_BANNED'; | ||
|
||
static $messages = [ | ||
self::KEY_DOES_NOT_EXIST => 'Использован несуществующий key.', | ||
self::WRONG_ID_FORMAT => 'Неверный формат ID капчи. ID должен содержать только цифры.', | ||
self::ZERO_BALANCE => 'Баланс Вашего аккаунта нулевой.', | ||
self::CAPTCHA_UNSOLVABLE => 'Капчу не смогли разгадать 3 разных работника. Списанные средства за это изображение возвращаются обратно на баланс.', | ||
self::NO_SLOT_AVAILABLE => 'Текущая ставка распознования выше, чем максимально установленная в настройках Вашего аккаунта. Либо на сервере скопилась очередь и работники не успевают её разобрать, повторите загрузку через 5 секунд.', | ||
self::WRONG_CAPTCHA_ID => 'Вы пытаетесь получить ответ на капчу или пожаловаться на капчу, которая была загружена более 15 минут назад.', | ||
self::ZERO_CAPTCHA_FILESIZE => 'Размер капчи меньше 100 Байт.', | ||
self::BAD_DUPLICATES => 'Ошибка появляется при включённом 100%м распознании. Было использовано максимальное количество попыток, но необходимое количество одинаковых ответов не было набрано.', | ||
self::TOO_BIG_CAPTCHA_FILESIZE => 'Размер капчи более 100 КБайт.', | ||
self::WRONG_FILE_EXTENSION => 'Ваша капча имеет неверное расширение, допустимые расширения jpg,jpeg,gif,png.', | ||
self::IMAGE_TYPE_NOT_SUPPORTED => 'Сервер не может определить тип файла капчи.', | ||
self::IP_NOT_ALLOWED => 'В Вашем аккаунте настроено ограничения по IP с которых можно делать запросы. И IP, с которого пришёл данный запрос не входит в список разрешённых.', | ||
self::IP_BANNED => 'IP-адрес, с которого пришёл запрос заблокирован из-за частых обращений с различными неверными ключами. Блокировка снимается через час.', | ||
]; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
<?php | ||
/** | ||
* @author Dmitry Gladyshev <[email protected]> | ||
*/ | ||
|
||
namespace Rucaptcha\Exception; | ||
|
||
|
||
class InvalidArgumentException extends RucaptchaException | ||
{ | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
<?php | ||
/** | ||
* @author Dmitry Gladyshev <[email protected]> | ||
*/ | ||
|
||
namespace Rucaptcha\Exception; | ||
|
||
|
||
use Exception; | ||
|
||
class RucaptchaException extends Exception | ||
{ | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
<?php | ||
/** | ||
* @author Dmitry Gladyshev <[email protected]> | ||
*/ | ||
|
||
namespace Rucaptcha\Exception; | ||
|
||
|
||
class RuntimeException extends RucaptchaException | ||
{ | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
<?php | ||
/** | ||
* @author Dmitry Gladyshev <[email protected]> | ||
*/ | ||
|
||
namespace Rucaptcha; | ||
|
||
|
||
class Extra | ||
{ | ||
const PHRASE = 'phrase'; | ||
const REGSENSE = 'regsense'; | ||
const QUESTION = 'question'; | ||
const NUMERIC = 'numeric'; | ||
const CALC = 'calc'; | ||
const MIN_LEN = 'min_len '; | ||
const MAX_LEN = 'max_len '; | ||
const IS_RUSSIAN = 'is_russian'; | ||
const SOFT_ID = 'soft_id'; | ||
const LANGUAGE = 'language'; | ||
const HEADER_ACAO = 'header_acao '; | ||
const TEXTINSTRUCTIONS = 'textinstructions'; | ||
const TEXTCAPTCHA = 'textcaptcha'; | ||
const CONTENT_TYPE = 'content_type'; | ||
} |
Oops, something went wrong.