Skip to content

Commit

Permalink
Pingback stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
Dmitry Gladyshev committed Mar 25, 2017
1 parent 090d63b commit 2eebbc4
Show file tree
Hide file tree
Showing 7 changed files with 138 additions and 9 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -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
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -133,3 +140,4 @@ Client::getLoadXml() : \SimpleXmlElement;
`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.
`pingback` | string | | URL для автоматической отправки ответа на капчу (callback). URL должен быть зарегистрирован на сервере. [Больше информации здесь](https://rucaptcha.com/api-rucaptcha#pingback).
20 changes: 20 additions & 0 deletions examples/pingback.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

require '../vendor/autoload.php';

$client = new Rucaptcha\Client(getenv('__RUCAPTCHA_KEY__'));

$pingbackUrl = 'http://' . getenv('__HOST__') .'/captcha/pingback.php';

// Add pingback url to allowed list
$client->addPingback($pingbackUrl);

// List of allowed pingbacks
$allowedPingbacks = $client->getPingbacks();

var_dump($allowedPingbacks);

$client->deletePingback($pingbackUrl);

// Check
var_dump($client->getPingbacks());
4 changes: 3 additions & 1 deletion phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
<whitelist>
<directory suffix=".php">./src</directory>
<exclude>
<directory>./src/Exception</directory>
<file>./src/Client.php</file>
<file>./src/Extra.php</file>
<file>./src/Error.php</file>
</exclude>
</whitelist>
</filter>
Expand Down
93 changes: 87 additions & 6 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Rucaptcha;

use Rucaptcha\Exception\ErrorResponseException;
use Rucaptcha\Exception\RuntimeException;

/**
Expand Down Expand Up @@ -71,6 +72,8 @@ public function getCaptchaResultBulk(array $captchaIds)
}

/**
* Returns balance of account.
*
* @return string
*/
public function getBalance()
Expand All @@ -80,6 +83,8 @@ public function getBalance()
}

/**
* Report of wrong recognition.
*
* @param $captchaId
* @return bool
* @throws RuntimeException
Expand All @@ -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'])
{
Expand All @@ -118,6 +127,8 @@ public function getLoad($paramsList = ['waiting', 'load', 'minbid', 'averageReco
}

/**
* Returns load data as XML.
*
* @return \SimpleXMLElement
*/
public function getLoadXml()
Expand All @@ -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();

Expand All @@ -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');
}
}
10 changes: 10 additions & 0 deletions src/Exception/ErrorResponseException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php
/**
* @author Dmitry Gladyshev <deel@email.ru>
*/

namespace Rucaptcha\Exception;

class ErrorResponseException extends RuntimeException
{
}
5 changes: 3 additions & 2 deletions src/GenericClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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}`.");
}

/**
Expand All @@ -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}`.");
}

/**
Expand Down

0 comments on commit 2eebbc4

Please sign in to comment.