From 2eebbc45791256ddafeb8011ad4e8cc25c18a1d3 Mon Sep 17 00:00:00 2001 From: Dmitry Gladyshev Date: Sat, 25 Mar 2017 13:41:23 +0300 Subject: [PATCH] Pingback stuff --- CHANGELOG | 7 ++ README.md | 8 ++ examples/pingback.php | 20 +++++ phpunit.xml | 4 +- src/Client.php | 93 ++++++++++++++++++++++-- src/Exception/ErrorResponseException.php | 10 +++ src/GenericClient.php | 5 +- 7 files changed, 138 insertions(+), 9 deletions(-) create mode 100644 examples/pingback.php create mode 100644 src/Exception/ErrorResponseException.php diff --git a/CHANGELOG b/CHANGELOG index d6f95ef..bfb58f1 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,10 @@ +1.0.6 - Add addPingback method + - Add getPingbacks method + - Add deletePingback method + - Add deleteAllPingbacks method + - Pingback examples + - ErrorResponseException + 1.0.5 - Add getLoad method example - Add getCaptchaResultWithCost method - Add codesniffer and fix codestyle diff --git a/README.md b/README.md index 9c3f6bc..25d1f68 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,13 @@ Client::sendCaptcha(string $content, array $extra = []) : int; Client::getCaptchaResult(int $captchaId) : string; Client::getCaptchaResultBulk(array $captchaIds) : array; +/* Pingback stuff */ + +Client::addPingback(string $uri) : bool; +Client::getPingbacks() : array; +Client::deletePingback(string $uri) : bool; +Client::deleteAllPingbacks() : bool; + /* Other */ Client::getLastCaptchaId() : string; @@ -133,3 +140,4 @@ Client::getLoadXml() : \SimpleXmlElement; `header_acao` | integer | 0 | 0 = значение по умолчанию
1 = in.php передаст Access-Control-Allow-Origin: * параметр в заголовке ответа. (Необходимо для кросс-доменных AJAX запросов в браузерных приложениях. Работает также для res.php.) `textinstructions` | string | |Текст, который будет показан работнику. Может содержать в себе инструкции по разгадке капчи. Ограничение - 140 символов. Текст необходимо слать в кодировке UTF-8. `textcaptcha` | string | | Текстовая капча. Картинка при этом не загружается, работник получает только текст и вводит ответ на этот текст. Ограничение - 140 символов. Текст необходимо слать в кодировке UTF-8. +`pingback` | string | | URL для автоматической отправки ответа на капчу (callback). URL должен быть зарегистрирован на сервере. [Больше информации здесь](https://rucaptcha.com/api-rucaptcha#pingback). \ No newline at end of file diff --git a/examples/pingback.php b/examples/pingback.php new file mode 100644 index 0000000..0e9c481 --- /dev/null +++ b/examples/pingback.php @@ -0,0 +1,20 @@ +addPingback($pingbackUrl); + +// List of allowed pingbacks +$allowedPingbacks = $client->getPingbacks(); + +var_dump($allowedPingbacks); + +$client->deletePingback($pingbackUrl); + +// Check +var_dump($client->getPingbacks()); diff --git a/phpunit.xml b/phpunit.xml index 40bb62d..90cf739 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -12,7 +12,9 @@ ./src - ./src/Exception + ./src/Client.php + ./src/Extra.php + ./src/Error.php diff --git a/src/Client.php b/src/Client.php index 51e7955..f7efa95 100644 --- a/src/Client.php +++ b/src/Client.php @@ -2,6 +2,7 @@ namespace Rucaptcha; +use Rucaptcha\Exception\ErrorResponseException; use Rucaptcha\Exception\RuntimeException; /** @@ -71,6 +72,8 @@ public function getCaptchaResultBulk(array $captchaIds) } /** + * Returns balance of account. + * * @return string */ public function getBalance() @@ -80,6 +83,8 @@ public function getBalance() } /** + * Report of wrong recognition. + * * @param $captchaId * @return bool * @throws RuntimeException @@ -90,15 +95,19 @@ public function badCaptcha($captchaId) ->getHttpClient() ->request('GET', "/res.php?key={$this->apiKey}&action=reportbad&id={$captchaId}"); - if ($response->getBody()->__toString() === self::STATUS_OK_REPORT_RECORDED) { + $responseText = $response->getBody()->__toString(); + + if ($responseText === self::STATUS_OK_REPORT_RECORDED) { return true; } - throw new RuntimeException('Report sending trouble: ' . $response->getBody() . '.'); + throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`."); } /** - * @param string|array $paramsList - * @return array + * Returns server health data. + * + * @param string|string[] $paramsList # List of metrics to be returned + * @return array # Array of load metrics $metric => $value formatted */ public function getLoad($paramsList = ['waiting', 'load', 'minbid', 'averageRecognitionTime']) { @@ -118,6 +127,8 @@ public function getLoad($paramsList = ['waiting', 'load', 'minbid', 'averageReco } /** + * Returns load data as XML. + * * @return \SimpleXMLElement */ public function getLoadXml() @@ -136,7 +147,9 @@ public function getLoadXml() */ public function getCaptchaResultWithCost($captchaId) { - $response = $this->getHttpClient()->request('GET', "/res.php?key={$this->apiKey}&action=get2&id={$captchaId}"); + $response = $this + ->getHttpClient() + ->request('GET', "/res.php?key={$this->apiKey}&action=get2&id={$captchaId}"); $responseText = $response->getBody()->__toString(); @@ -153,6 +166,74 @@ public function getCaptchaResultWithCost($captchaId) ]; } - throw new RuntimeException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`."); + throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`."); + } + + /** + * @param string $url + * @return bool # true if added and exception if fail + * @throws RuntimeException + */ + public function addPingback($url) + { + $response = $this + ->getHttpClient() + ->request('GET', "/res.php?key={$this->apiKey}&action=add_pingback&addr={$url}"); + + $responseText = $response->getBody()->__toString(); + + if ($responseText === self::STATUS_OK) { + return true; + } + throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`."); + } + + /** + * @return string[] + * @throws RuntimeException + */ + public function getPingbacks() + { + $response = $this + ->getHttpClient() + ->request('GET', "/res.php?key={$this->apiKey}&action=get_pingback"); + + $responseText = $response->getBody()->__toString(); + + if (strpos($responseText, 'OK|') !== false) { + $data = explode('|', $responseText); + unset($data[0]); + return empty($data[1]) ? [] : array_values($data); + } + + throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`."); + } + + /** + * @param string $uri + * @return bool + * @throws RuntimeException + */ + public function deletePingback($uri) + { + $response = $this + ->getHttpClient() + ->request('GET', "/res.php?key={$this->apiKey}&action=del_pingback&addr={$uri}"); + + $responseText = $response->getBody()->__toString(); + + if ($responseText === self::STATUS_OK) { + return true; + } + throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`."); + } + + /** + * @return bool + * @throws RuntimeException + */ + public function deleteAllPingbacks() + { + return $this->deletePingback('all'); } } diff --git a/src/Exception/ErrorResponseException.php b/src/Exception/ErrorResponseException.php new file mode 100644 index 0000000..ca26fbb --- /dev/null +++ b/src/Exception/ErrorResponseException.php @@ -0,0 +1,10 @@ + + */ + +namespace Rucaptcha\Exception; + +class ErrorResponseException extends RuntimeException +{ +} diff --git a/src/GenericClient.php b/src/GenericClient.php index 65f13d7..a53b6f3 100644 --- a/src/GenericClient.php +++ b/src/GenericClient.php @@ -11,6 +11,7 @@ use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerAwareTrait; use Psr\Log\LoggerInterface; +use Rucaptcha\Exception\ErrorResponseException; use Rucaptcha\Exception\InvalidArgumentException; use Rucaptcha\Exception\RucaptchaException; use Rucaptcha\Exception\RuntimeException; @@ -175,7 +176,7 @@ public function sendCaptcha($content, array $extra = []) return $this->lastCaptchaId; } - throw new RuntimeException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`."); + throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`."); } /** @@ -198,7 +199,7 @@ public function getCaptchaResult($captchaId) return html_entity_decode(trim(explode('|', $responseText)[1])); } - throw new RuntimeException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`."); + throw new ErrorResponseException($this->getErrorMessage($responseText) ?: "Unknown error: `{$responseText}`."); } /**